javascript
基于SpringBoot的websocket的多人聊天室项目
文章目錄
- 1、websocket
- 什么是websocket?
- 使用步驟
- 1.引入依賴
- 2.建立配置類
- 3.業務層
- Web類
- HTML
- 遇到的問題
- 項目github地址
1、websocket
什么是websocket?
WebSocket協議是基于TCP的一種新的網絡協議。它實現了客戶端與服務器全雙工通信,學過計算機網絡都知道,既然是全雙工,就說明了服務器可以主動發送信息給客戶端。這與我們的推送技術或者是多人在線聊天的功能不謀而合。
為什么不使用HTTP 協議呢?這是因為HTTP是單工通信,通信只能由客戶端發起,客戶端請求一下,服務器處理一下,這就太麻煩了。于是websocket應運而生。
下面我們就直接開始使用Springboot開始整合。以下案例都在我自己的電腦上測試成功,你可以根據自己的功能進行修改即可。
現在我們的需求是根據這個特點,實現一個多個人的聊天室
這是我們的項目結構
使用步驟
1.引入依賴
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency> </dependencies>2.建立配置類
@Configuration public class WebSocketConfig {@Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();} }3.業務層
因為代碼比較多,核心代碼為
/*** 建立成功連接調用的方法*/ @OnOpen public void onOpen(Session session, @PathParam("sid") String sid) {this.session = session;//如果有重復直接返回for (WebSocketServer item : webSocketSet) {if (Objects.equals(item.sid, sid)) {return;}}webSocketSet.add(this); //加入set中this.sid = sid;addOnlineCount(); //在線人數加1try {sendMessage("conn_success");log.info("有新窗口開始監聽:" + sid + "當前在線人數為:" + getOnlineCount());} catch (IOException e) {log.error("websocket IO Exception");} }/*** 收到客戶端調用的方法*/ @OnMessage public void onMessage(String message, Session session) {log.info("來自窗口:" + sid + "的消息" + message);//群發消息for (WebSocketServer item : webSocketSet) {try {item.sendMessage("來自窗口:" + sid + "的消息" + message);} catch (IOException e) {e.printStackTrace();}} }public static void sendInfo(String message) {for (WebSocketServer item : webSocketSet) {try {log.info("推送消息到窗口:" + item.sid + ",推送內容為:" + message);item.sendMessage(message);} catch (IOException e) {throw new RuntimeException(e);}} }因為我們要建立多人的聊天室,那必須要區分,不同客戶端的類型,于是我想到了可以用Web中的路徑參數每一個路徑參數相當于一個id,之后通過thymeleaf的渲染,使他的路徑參數最終變化為WebSocket。
Web類
//頁面請求 @GetMapping("/index/{user}") public String socket(@PathVariable String user, Model model) {model.addAttribute("user",user);return "index"; }HTML
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head><meta charset="utf-8"><title>Java后端WebSocket的Tomcat實現</title><script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <button onclick="create(value)" th:attr="value = ${user}">連接Socket</button> <br/> Welcome <br/><input id="text" type="text"/><button onclick="send()">發送消息</button> <hr/> <button onclick="closeWebSocket()">關閉WebSocket連接</button> <hr/> <div id="message"></div> </body> <script type="text/javascript">function create(user) {//判斷當前瀏覽器是否支持WebSocketif ('WebSocket' in window) {//改成你的地址if (user == null) {websocket = new WebSocket("ws://localhost:8080/api/websocket/101");init(websocket)} else {websocket = new WebSocket("ws://localhost:8080/api/websocket/" + user);init(websocket)}setMessageInnerHTML(user + "連接成功");return websocket;} else {alert('當前瀏覽器 Not support websocket')}}function init(websocket){//連接發生錯誤的回調方法websocket.onerror = function () {setMessageInnerHTML("WebSocket連接發生錯誤");};//連接成功建立的回調方法websocket.onopen = function () {setMessageInnerHTML("WebSocket連接成功");}//接收到消息的回調方法websocket.onmessage = function (event) {console.log(event);setMessageInnerHTML(event.data);}//連接關閉的回調方法websocket.onclose = function () {setMessageInnerHTML("WebSocket連接關閉");}//監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket連接,防止連接還沒斷開就關閉窗口,server端會拋異常。window.onbeforeunload = function () {closeWebSocket();}}//將消息顯示在網頁上function setMessageInnerHTML(innerHTML) {document.getElementById('message').innerHTML += innerHTML + '<br/>';}//關閉WebSocket連接function closeWebSocket() {websocket.close();}//發送消息function send() {var message = document.getElementById('text').value;websocket.send('{"msg":"' + message + '"}');} </script> </html>[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-AIJwdazZ-1650793746573)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20220424174125326.png)]
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-8XEVhnom-1650793746574)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20220424174111899.png)]
遇到的問題
ssage = document.getElementById(‘text’).value;
websocket.send(‘{“msg”:"’ + message + ‘"}’);
}
項目github地址
項目地址
總結
以上是生活随笔為你收集整理的基于SpringBoot的websocket的多人聊天室项目的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 嵌入式Linux学习笔记—fastboo
- 下一篇: Spring Security OAut