springboot+websocket 歸納收集
阿新 • • 發佈:2018-03-25
esp 廣泛 .com actor 關於 urn count() mbo ucc
websocket是h5後的技術,主要實現是一個長連接跟tomcat的comet技術差不多,但websocket是基於web協議的,有更廣泛的支持。當然,在處理高並發的情況下,可以結合tomcat的asyncContext來實現長處理的異步返回等操作。
1.引入依賴類
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.18</version> </dependency> <!-- websocket dependency --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
這裏主要是引入websocket的依賴類
2.springboot配置websocket的入口bean
在springboot的配置類下,引入以下的配置bean
@Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); }
3.實現websocket的後端處理邏輯
package com.ouyang.server; import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.websocket.*; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; /** * Created by Administrator on 2018/3/25. */ //@Slf4j @ServerEndpoint(value = "/websocket") @Component public class WebSocketServer { Logger log= LoggerFactory.getLogger(WebSocketServer.class); //靜態變量,用來記錄當前在線連接數。應該把它設計成線程安全的。 private static int onlineCount = 0; //concurrent包的線程安全Set,用來存放每個客戶端對應的MyWebSocket對象。 private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>(); // 備用的同步hashmap //private static ConcurrentHashMap<Session,WebSocketServer> webSocketServerConcurrentHashMap = new ConcurrentHashMap(); //與某個客戶端的連接會話,需要通過它來給客戶端發送數據 private Session session; /** * 連接建立成功調用的方法*/ @OnOpen public void onOpen(Session session) { this.session = session; webSocketSet.add(this); //加入set中 addOnlineCount(); //在線數加1 log.info("有新連接加入!當前在線人數為" + getOnlineCount()); try { sendMessage("連接成功"); } catch (IOException e) { log.error("websocket IO異常"); } } // //連接打開時執行 // @OnOpen // public void onOpen(@PathParam("user") String user, Session session) { // currentUser = user; // System.out.println("Connected ... " + session.getId()); // } /** * 連接關閉調用的方法 */ @OnClose public void onClose() { webSocketSet.remove(this); //從set中刪除 subOnlineCount(); //在線數減1 log.info("有一連接關閉!當前在線人數為" + getOnlineCount()); } /** * 收到客戶端消息後調用的方法 * * @param message 客戶端發送過來的消息*/ @OnMessage public void onMessage(String message, Session session) throws IOException { log.info("來自客戶端的消息:" + message); //群發消息 for (WebSocketServer item : webSocketSet) { try { item.sendMessage("response message:"+message); } catch (IOException e) { e.printStackTrace(); } } //單發的信息 sendMessage("currentWebsocket is ok!!! "); } /** * * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { log.error("發生錯誤"); error.printStackTrace(); } /** * * @param message * @throws IOException */ public void sendMessage(String message) throws IOException { this.session.getBasicRemote().sendText(message); } /** * 群發自定義消息 * */ public static void sendInfo(String message) throws IOException { //log.info(message); for (WebSocketServer item : webSocketSet) { try { item.sendMessage(message); } catch (IOException e) { continue; } } } public static synchronized int getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { WebSocketServer.onlineCount++; } public static synchronized void subOnlineCount() { WebSocketServer.onlineCount--; } }
至此,我們關於後臺的websocket的主要實現類都實現了,接下來我們可以弄一個,測試的接口,用於給所有的websocket推送信息,如下:
@RequestMapping(value="/publicSend",method= RequestMethod.GET) @ResponseBody public String pushVideoListToWeb2(String id) { try { WebSocketServer.sendInfo("有新客戶呼入,sltAccountId:"+id); for(int i= 0;i<20;i++){ WebSocketServer.sendInfo("有新客戶呼入,testing:"+String.valueOf(i)); } }catch (IOException e) { } return "success!"; }
4.前端測試頁面的實現
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.springframework.org/schema/jdbc"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="/static/jquery.js"></script> <script src="/static/stomp.min.js"></script> <script src="/static/sockjs.min.js"></script> <script> //socket = new WebSocket("ws://localhost:8081/begenstom/websocket"); var socket; if(typeof(WebSocket) == "undefined") { console.log("您的瀏覽器不支持WebSocket"); }else { console.log("您的瀏覽器支持WebSocket"); //實現化WebSocket對象,指定要連接的服務器地址與端口 //socket = new WebSocket("ws://localhost:9094/starManager/websocket/張三"); socket = new WebSocket("ws://localhost:8081/websocket"); //打開事件 socket.onopen = function () { console.log("Socket 已打開"); for (var i=0;i<20;i++) { socket.send("這是來自客戶端的消息1:" + i); } //socket.send("這是來自客戶端的消息" + location.href + new Date()); }; //獲得消息事件 socket.onmessage = function (msg) { console.log(msg.data); //發現消息進入 調後臺獲取 document.write(msg.data); }; //關閉事件 socket.onclose = function () { console.log("Socket已關閉"); }; //發生了錯誤事件 socket.onerror = function () { alert("Socket發生了錯誤"); } $(window).unload(function () { socket.close(); }); } </script> </head> <body> </body> </html>
這裏主要用到3個js,可以去github上去當一個。
參考地址:
* https://blog.csdn.net/zhangdehua678/article/details/78913839
* https://github.com/ayman-elgharabawy/Kafka-SpringBoot-WebSocket
* 整合框架 https://github.com/527515025/springBoot
springboot+websocket 歸納收集