什么是WebSocket?
WebSocket協議是基於TCP的一種新的網絡協議。它實現了瀏覽器與服務器全雙工(full-duplex)通信——允許服務器主動發送信息給客戶端。
為什么需要 WebSocket?
初次接觸 WebSocket 的人,都會問同樣的問題:我們已經有了 HTTP 協議,為什么還需要另一個協議?它能帶來什么好處?
答案很簡單,因為 HTTP 協議有一個缺陷:通信只能由客戶端發起,HTTP 協議做不到服務器主動向客戶端推送信息。
舉例來說,我們想要查詢當前的排隊情況,只能是頁面輪詢向服務器發出請求,服務器返回查詢結果。輪詢的效率低,非常浪費資源(因為必須不停連接,或者 HTTP 連接始終打開)。因此WebSocket 就是這樣發明的。
話不多說,馬上進入干貨時刻。
maven依賴
SpringBoot2.0對WebSocket的支持簡直太棒了,直接就有包可以引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
WebSocketConfig
啟用WebSocket的支持也是很簡單,幾句代碼搞定
1 import org.springframework.context.annotation.Bean; 2 import org.springframework.context.annotation.Configuration; 3 import org.springframework.web.socket.server.standard.ServerEndpointExporter; 4 5 /** 6 * 開啟WebSocket支持 7 * @author zhengkai 8 */ 9 @Configuration 10 public class WebSocketConfig { 11 12 @Bean 13 public ServerEndpointExporter serverEndpointExporter() { 14 return new ServerEndpointExporter(); 15 } 16 17 }
WebSocketServer
因為WebSocket是類似客戶端服務端的形式(采用ws協議),那么這里的WebSocketServer其實就相當於一個ws協議的Controller
直接@ServerEndpoint("/websocket")@Component啟用即可,然后在里面實現@OnOpen,@onClose,@onMessage等方法
1 import java.io.IOException; 2 import java.util.concurrent.CopyOnWriteArraySet; 3 4 import javax.websocket.OnClose; 5 import javax.websocket.OnError; 6 import javax.websocket.OnMessage; 7 import javax.websocket.OnOpen; 8 import javax.websocket.Session; 9 import javax.websocket.server.ServerEndpoint; 10 import org.springframework.stereotype.Component; 11 import cn.hutool.log.Log; 12 import cn.hutool.log.LogFactory; 13 import lombok.extern.slf4j.Slf4j; 14 15 16 @ServerEndpoint("/websocket/{sid}") 17 @Component 18 public class WebSocketServer { 19 20 static Log log=LogFactory.get(WebSocketServer.class); 21 //靜態變量,用來記錄當前在線連接數。應該把它設計成線程安全的。 22 private static int onlineCount = 0; 23 //concurrent包的線程安全Set,用來存放每個客戶端對應的MyWebSocket對象。 24 private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>(); 25 26 //與某個客戶端的連接會話,需要通過它來給客戶端發送數據 27 private Session session; 28 29 //接收sid 30 private String sid=""; 31 /** 32 * 連接建立成功調用的方法*/ 33 @OnOpen 34 public void onOpen(Session session,@PathParam("sid") String sid) { 35 this.session = session; 36 webSocketSet.add(this); //加入set中 37 addOnlineCount(); //在線數加1 38 log.info("有新窗口開始監聽:"+sid+",當前在線人數為" + getOnlineCount()); 39 this.sid=sid; 40 try { 41 sendMessage("連接成功"); 42 } catch (IOException e) { 43 log.error("websocket IO異常"); 44 } 45 } 46 47 /** 48 * 連接關閉調用的方法 49 */ 50 @OnClose 51 public void onClose() { 52 webSocketSet.remove(this); //從set中刪除 53 subOnlineCount(); //在線數減1 54 log.info("有一連接關閉!當前在線人數為" + getOnlineCount()); 55 } 56 57 /** 58 * 收到客戶端消息后調用的方法 59 * 60 * @param message 客戶端發送過來的消息*/ 61 @OnMessage 62 public void onMessage(String message, Session session) { 63 log.info("收到來自窗口"+sid+"的信息:"+message); 64 //群發消息 65 for (WebSocketServer item : webSocketSet) { 66 try { 67 item.sendMessage(message); 68 } catch (IOException e) { 69 e.printStackTrace(); 70 } 71 } 72 } 73 74 /** 75 * 76 * @param session 77 * @param error 78 */ 79 @OnError 80 public void onError(Session session, Throwable error) { 81 log.error("發生錯誤"); 82 error.printStackTrace(); 83 } 84 /** 85 * 實現服務器主動推送 86 */ 87 public void sendMessage(String message) throws IOException { 88 this.session.getBasicRemote().sendText(message); 89 } 90 91 92 /** 93 * 群發自定義消息 94 * */ 95 public static void sendInfo(String message,@PathParam("sid") String sid) throws IOException { 96 log.info("推送消息到窗口"+sid+",推送內容:"+message); 97 for (WebSocketServer item : webSocketSet) { 98 try { 99 //這里可以設定只推送給這個sid的,為null則全部推送 100 if(sid==null) { 101 item.sendMessage(message); 102 }else if(item.sid.equals(sid)){ 103 item.sendMessage(message); 104 } 105 } catch (IOException e) { 106 continue; 107 } 108 } 109 } 110 111 public static synchronized int getOnlineCount() { 112 return onlineCount; 113 } 114 115 public static synchronized void addOnlineCount() { 116 WebSocketServer.onlineCount++; 117 } 118 119 public static synchronized void subOnlineCount() { 120 WebSocketServer.onlineCount--; 121 } 122 }
消息推送
至於推送新信息,可以再自己的Controller寫個方法調用WebSocketServer.sendInfo();即可
@Controller @RequestMapping("/checkcenter") public class CheckCenterController { //頁面請求 @GetMapping("/socket/{cid}") public ModelAndView socket(@PathVariable String cid) { ModelAndView mav=new ModelAndView("/socket"); mav.addObject("cid", cid); return mav; } //推送數據接口 @ResponseBody @RequestMapping("/socket/push/{cid}") public ApiReturnObject pushToWeb(@PathVariable String cid,String message) { try { WebSocketServer.sendInfo(message,cid); } catch (IOException e) { e.printStackTrace(); return ApiReturnUtil.error(cid+"#"+e.getMessage()); } return ApiReturnUtil.success(cid); } }
頁面發起socket請求
然后在頁面用js代碼調用socket,當然,太古老的瀏覽器是不行的,一般新的瀏覽器或者谷歌瀏覽器是沒問題的。還有一點,記得協議是ws的哦,如果像我這樣封裝了一些basePath的路徑類,可以replace(“http”,“ws”)來替換協議
<script> var socket; if(typeof(WebSocket) == "undefined") { console.log("您的瀏覽器不支持WebSocket"); }else{ console.log("您的瀏覽器支持WebSocket"); //實現化WebSocket對象,指定要連接的服務器地址與端口 建立連接 //等同於socket = new WebSocket("ws://localhost:8083/checkcentersys/websocket/20"); socket = new WebSocket("${basePath}websocket/${cid}".replace("http","ws")); //打開事件 socket.onopen = function() { console.log("Socket 已打開"); //socket.send("這是來自客戶端的消息" + location.href + new Date()); }; //獲得消息事件 socket.onmessage = function(msg) { console.log(msg.data); //發現消息進入 開始處理前端觸發邏輯 }; //關閉事件 socket.onclose = function() { console.log("Socket已關閉"); }; //發生了錯誤事件 socket.onerror = function() { alert("Socket發生了錯誤"); //此時可以嘗試刷新頁面 } //離開頁面時,關閉socket //jquery1.8中已經被廢棄,3.0中已經移除 // $(window).unload(function(){ // socket.close(); //}); } </script>
運行效果
v1.1的效果,剛剛修復了日志,並且支持指定監聽某個端口,代碼已經全部更新,現在是這樣的效果
打開兩個頁面:
http://localhost:8083/checkcentersys/checkcenter/socket/20
http://localhost:8083/checkcentersys/checkcenter/socket/22
向前端推送數據:
http://localhost:8083/checkcentersys/checkcenter/socket/push/20?message=cccccccccc
http://localhost:8083/checkcentersys/checkcenter/socket/push/22?message=xxxxx123xxxx
先打開頁面,指定cid,啟用socket接收,然后再另一個頁面調用剛才Controller封裝的推送信息的方法到這個cid的socket,即可向前端推送消息。
后續
針對簡單IM的業務場景,進行了一些優化,可以看后續的文章SpringBoot2+WebSocket之聊天應用實戰(優化版本)
主要變動是CopyOnWriteArraySet改為ConcurrentHashMap,保證多線程安全同時方便利用map.get(userId)進行推送到指定端口。
相比之前的Set,Set遍歷是費事且麻煩的事情,而Map的get是簡單便捷的,當WebSocket數量大的時候,這個小小的消耗就會聚少成多,影響體驗,所以需要優化。
Websocker注入Bean問題
關於這個問題,可以看最新發表的這篇文章,在參考和研究了網上一些攻略后,項目已經通過該方法注入成功,大家可以參考。
關於controller調用controller/service調用service/util調用service/websocket中autowired的解決方法
netty-websocket-spring-boot-starter
Springboot2構建基於Netty的高性能Websocket服務器(netty-websocket-spring-boot-starter)
只需要換個starter即可實現高性能websocket,趕緊使用吧
Springboot2+Netty+Websocket
Springboot2+Netty實現Websocket,使用官方的netty-all的包,比原生的websocket更加穩定更加高性能,同等配置情況下可以handle更多的連接。
代碼樣式全部已經更正,另外也感謝大家的閱讀和評論,一起進步,謝謝!~~
serverEndpointExporter錯誤
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘serverEndpointExporter’ defined in class path resource [com/xxx/WebSocketConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: javax.websocket.server.ServerContainer not available
如果tomcat部署一直報這個錯,請移除 WebSocketConfig 中@Bean ServerEndpointExporter 的注入 。
ServerEndpointExporter 是由Spring官方提供的標准實現,用於掃描ServerEndpointConfig配置類和@ServerEndpoint注解實例。使用規則也很簡單:
如果使用默認的嵌入式容器 比如Tomcat 則必須手工在上下文提供ServerEndpointExporter。
如果使用外部容器部署war包,則不需要提供提供ServerEndpointExporter,因為此時SpringBoot默認將掃描服務端的行為交給外部容器處理,所以線上部署的時候要把WebSocketConfig中這段注入bean的代碼注掉。
文章轉自: https://blog.csdn.net/moshowgame/article/details/80275084
其他參考:
1. https://blog.csdn.net/weixin_38111957/article/details/86352677
2. https://blog.csdn.net/qq_35387940/article/details/93483678
3. https://blog.csdn.net/qq_34409255/article/details/81010075