javascript
基于SpringBoot的websocket的多人聊天室项目
文章目錄
- 1、websocket
- 什么是websocket?
- 使用步驟
- 1.引入依賴
- 2.建立配置類
- 3.業(yè)務(wù)層
- Web類
- HTML
- 遇到的問題
- 項目github地址
1、websocket
什么是websocket?
WebSocket協(xié)議是基于TCP的一種新的網(wǎng)絡(luò)協(xié)議。它實現(xiàn)了客戶端與服務(wù)器全雙工通信,學(xué)過計算機網(wǎng)絡(luò)都知道,既然是全雙工,就說明了服務(wù)器可以主動發(fā)送信息給客戶端。這與我們的推送技術(shù)或者是多人在線聊天的功能不謀而合。
為什么不使用HTTP 協(xié)議呢?這是因為HTTP是單工通信,通信只能由客戶端發(fā)起,客戶端請求一下,服務(wù)器處理一下,這就太麻煩了。于是websocket應(yīng)運而生。
下面我們就直接開始使用Springboot開始整合。以下案例都在我自己的電腦上測試成功,你可以根據(jù)自己的功能進行修改即可。
現(xiàn)在我們的需求是根據(jù)這個特點,實現(xiàn)一個多個人的聊天室
這是我們的項目結(jié)構(gòu)
使用步驟
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.業(yè)務(wù)層
因為代碼比較多,核心代碼為
/*** 建立成功連接調(diào)用的方法*/ @OnOpen public void onOpen(Session session, @PathParam("sid") String sid) {this.session = session;//如果有重復(fù)直接返回for (WebSocketServer item : webSocketSet) {if (Objects.equals(item.sid, sid)) {return;}}webSocketSet.add(this); //加入set中this.sid = sid;addOnlineCount(); //在線人數(shù)加1try {sendMessage("conn_success");log.info("有新窗口開始監(jiān)聽:" + sid + "當前在線人數(shù)為:" + getOnlineCount());} catch (IOException e) {log.error("websocket IO Exception");} }/*** 收到客戶端調(diào)用的方法*/ @OnMessage public void onMessage(String message, Session session) {log.info("來自窗口:" + sid + "的消息" + message);//群發(fā)消息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 + ",推送內(nèi)容為:" + message);item.sendMessage(message);} catch (IOException e) {throw new RuntimeException(e);}} }因為我們要建立多人的聊天室,那必須要區(qū)分,不同客戶端的類型,于是我想到了可以用Web中的路徑參數(shù)每一個路徑參數(shù)相當于一個id,之后通過thymeleaf的渲染,使他的路徑參數(shù)最終變化為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實現(xiàn)</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()">發(fā)送消息</button> <hr/> <button onclick="closeWebSocket()">關(guān)閉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){//連接發(fā)生錯誤的回調(diào)方法websocket.onerror = function () {setMessageInnerHTML("WebSocket連接發(fā)生錯誤");};//連接成功建立的回調(diào)方法websocket.onopen = function () {setMessageInnerHTML("WebSocket連接成功");}//接收到消息的回調(diào)方法websocket.onmessage = function (event) {console.log(event);setMessageInnerHTML(event.data);}//連接關(guān)閉的回調(diào)方法websocket.onclose = function () {setMessageInnerHTML("WebSocket連接關(guān)閉");}//監(jiān)聽窗口關(guān)閉事件,當窗口關(guān)閉時,主動去關(guān)閉websocket連接,防止連接還沒斷開就關(guān)閉窗口,server端會拋異常。window.onbeforeunload = function () {closeWebSocket();}}//將消息顯示在網(wǎng)頁上function setMessageInnerHTML(innerHTML) {document.getElementById('message').innerHTML += innerHTML + '<br/>';}//關(guān)閉WebSocket連接function closeWebSocket() {websocket.close();}//發(fā)送消息function send() {var message = document.getElementById('text').value;websocket.send('{"msg":"' + message + '"}');} </script> </html>[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-AIJwdazZ-1650793746573)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20220424174125326.png)]
[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(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地址
項目地址
總結(jié)
以上是生活随笔為你收集整理的基于SpringBoot的websocket的多人聊天室项目的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 嵌入式Linux学习笔记—fastboo
- 下一篇: IBM V7000存储Mdisk磁盘掉线