websocket小記

websocket可以實現(xiàn)消息的實時推送,應(yīng)用較為廣泛,在工作中可以結(jié)合大數(shù)據(jù)數(shù)據(jù)的推送,后臺接收并推送到前端展示,下面是我做的一個簡單測試。

首先在pom.xml文件的<dependencies></dependencies>中引入依賴:

<dependency>

? ? <groupId>org.springframework.boot</groupId>

? ? <artifactId>spring-boot-starter-websocket

</dependency>

創(chuàng)建TestWebSocketServer類:

@ServerEndpoint(value = "/websocket/test", configurator = HttpSessionConfigurator.class)

@Component

public class TestWebSocketServer extends TextWebSocketHandler {

private static final Loggerlogger = LoggerFactory.getLogger(TestWebSocketServer.class);

? ? /**

* concurrent包的線程安全Set,用來存放每個客戶端對應(yīng)的MyWebSocket對象。

*/

? ? private static CopyOnWriteArraySet<TestWebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();

? ? /**

* 與客戶端的連接會話,通過該對象給客戶端發(fā)送數(shù)據(jù)

*/

? ? private Session session;

? ? /**

* 連接建立成功調(diào)用的方法

*/

? ? @OnOpen

? ? public void onOpen(Session session, EndpointConfig config){

????????this.session = session;

? ? ? ? webSocketSet.add(this);? ? //加入set中

? ? ? ? logger.info("有新窗口開始監(jiān)聽");

? ? ? ? try {

????????????sendMessage("連接成功");

? ? ? ? }catch (IOException e) {

????????????logger.error("websocket IO異常");

? ? ? ? }

}

/**

* 連接關(guān)閉調(diào)用的方法

*/

? ? @OnClose

? ? public void onClose() {

????????// 從set中刪除

? ? ? ? webSocketSet.remove(this);

? ? ? ? logger.info("連接關(guān)閉");

? ? }

/**

* 收到客戶端消息后調(diào)用的方法

*

? ? * @param message 客戶端發(fā)送過來的消息

*/

? ? @OnMessage

? ? public void onMessage(String message, Session session) {

????????logger.info("收到來自客戶端的信息:"+message);

? ? ? ? //群發(fā)消息

? ? ? ? for (TestWebSocketServer item :webSocketSet) {

????????????try {

????????????????item.sendMessage(session.getId()+":"+message);

? ? ? ? ? ? }catch (IOException e) {

????????????????e.printStackTrace();

? ? ? ? ? ? }

????}

}

/**

* 發(fā)生錯誤時調(diào)用

? ? * @param session

? ? * @param error

? ? */

? ? @OnError

? ? public void onError(Session session, Throwable error) {

????????logger.error("發(fā)生錯誤");

? ? ? ? error.printStackTrace();

? ? }

/**

* 向客戶端發(fā)送數(shù)據(jù)

*

? ? * @param message 數(shù)據(jù)

? ? * @throws IOException 異常

*/

? ? public void sendMessage(String message)throws IOException {

????????logger.info("消息:{}",message);

? ? ? ? this.session.getBasicRemote().sendText(message);

? ? }

/**

* 群發(fā)自定義消息

? ? * @param message

? ? * @throws IOException

*/

? ? public void sendInfo(String message)throws IOException {

? ? ? ? ? ? logger.info(message);

? ? ? ? ? ? for (TestWebSocketServer item :webSocketSet) {

????????????????try {

????????????????????item.sendMessage("AI:"+message);

? ? ? ? ? ? ? ? }catch (IOException e) {

????????????????????continue;

? ? ? ? ? ? ? ? }

????????}

? ? }

}

Controller類中調(diào)用TestWebSocketServer

@Autowired

private TestWebSocketServer testWebSockeServer;

接收數(shù)據(jù)并推送:

@RequestMapping(value ="/test/infos",method = RequestMethod.POST)

public ResponseResult sendMessage(@Valid @RequestBody final TestWebsocketPojo[] testWebsocketPojos){

ResponseResult result =new ResponseResult();

? ? try{

????????????if(testWebsocketPojos==null || testWebsocketPojos.length==0){

????????????result.setErrMsg("參數(shù)為空");

? ? ? ? ? ? result.setSuccess(false);

? ? ? ? ? ? return result;

? ? ? ? }

????for(TestWebsocketPojo pojo: testWebsocketPojos){

????????????testWebSockeServer.sendInfo("hello,開始我們的測試");

? ? ? ? ? ? testWebSockeServer.sendInfo(pojo.toString());

? ? ? ? }

????????result.setErrMsg("傳輸數(shù)據(jù)成功");

? ? ? ? result.setSuccess(true);

? ? }catch(Exception e){

????????result.setErrMsg("服務(wù)出現(xiàn)異常"+e.getMessage());

? ? ? ? result.setSuccess(false);

? ? }

????????return result;

}

測試頁面及js調(diào)用:

<!DOCTYPE html>

<html lang="en">

? ? <meta charset="UTF-8">

? ? <title>testWebsocket

? ? // 初始化一個 WebSocket 對象

? ? var ws =new WebSocket("ws://localhost:8002/websocket/test");

? ? // 建立 web socket 連接成功觸發(fā)事件

? ? ws.onopen =function () {

????????// 使用 send() 方法發(fā)送數(shù)據(jù)

? ? ? ? console.log("Socket 已打開");

? ? ? ? ws.send("發(fā)送數(shù)據(jù)");

? ? ? ? alert("數(shù)據(jù)發(fā)送中...");

? ? };

? ????? // 接收服務(wù)端數(shù)據(jù)時觸發(fā)事件

? ????? ws.onmessage =function (evt) {

????????console.log(evt.data);

? ? ? ? var received_msg = evt.data;

? ? ? ? alert("數(shù)據(jù)已接收...");

? ? };

? ? ????// 斷開 web socket 連接成功觸發(fā)事件

? ? ????ws.onclose =function () {

????????console.log("Socket已關(guān)閉");

? ? ? ? alert("連接已關(guān)閉...");

? ? };

? ? 測試websocket<a href="/index.html">跳轉(zhuǎn)

</html>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容