SpringBoot+WebSocket實現多人在線聊天案例實例
1.pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.3</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.yl</groupId> <artifactId>chat01</artifactId> <version>0.0.1-SNAPSHOT</version> <name>chat01</name> <description>Demo project for Spring Boot</description> <properties> <java.version>11</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--前端庫依賴--> <dependency> <groupId>org.webjars</groupId> <artifactId>sockjs-client</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>stomp-websocket</artifactId> <version>2.3.3</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.5.1</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>webjars-locator-core</artifactId> <!-- <version>0.48</version>--> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
2.消息實體類
package com.yl.chat01.domain; import java.io.Serializable; public class Message implements Serializable { private String name; private String content; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String toString() { return "Message{" + "name='" + name + '\'' + ", content='" + content + '\'' + '}'; } }
3.controller
package com.yl.chat01.controller; import com.yl.chat01.domain.Message; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.stereotype.Controller; @Controller public class GreetingController { @MessageMapping("/hello") //發送消息請求 @SendTo("/topic/greetings") //消息廣播 public Message greeting(Message message) { return message; } }
4.WebSocket的配置文件
package com.yl.chat01.config; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { // 註冊端點,用於前端建立連接的 @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/chat").withSockJS(); } // 配置消息代理,通過廣播的形式來傳遞消息 @Override public void configureMessageBroker(MessageBrokerRegistry registry) { registry.enableSimpleBroker("/topic"); } }
5.前端發送消息頁面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="/webjars/jquery/jquery.min.js"></script> <script src="/webjars/sockjs-client/sockjs.min.js"></script> <script src="/webjars/stomp-websocket/stomp.min.js"></script> </head> <body> <div> <label for="username">請輸入用戶名:</label> <input type="text" id = "username" placeholder="用戶名"/> </div> <div> <input type="button" value="連接" id="connect"/> <input type="button" value="斷開連接" id="disconnect" disabled="disabled"/> </div> <div id="chat"></div> <div> <label for="content">請輸入聊天內容</label> <input type="text" id="content" placeholder="聊天內容"/> </div> <input type="button" value="發送" disabled="disabled" id="send"/> <script> var stompClient; $(function () { //連接 $("#connect").click(function () { connect() }) //發送消息到後臺 $("#send").click(function () { stompClient.send("/hello",{},JSON.stringify({'name':$('#username').val(),'content':$("#content").val()})) }) //斷開連接 $("#disconnect").cilck(function () { stompClient.disconnect(); disableButton(false); }) }) function connect() { if (!$("#username").val()) { alert("請輸入用戶名") return; } //獲取連接地址 var socketjs = new SockJS("/chat"); stompClient = Stomp.over(socketjs); //建立連接 stompClient.connect({},function (frame) { alert("connect success") disableButton(true); //訂閱消息 stompClient.subscribe("/topic/greetings",function (obj) { var msg = JSON.parse(obj.body); $("#chat").append("<div>"+msg.name+ ":" + msg.content+"</div>") }) }) } function disableButton(connected) { $("#connect").prop("disabled",connected); $("#disconnect").prop("disabled",!connected); $("#send").prop("disabled",!connected); } </script> </body> </html>
6.測試
6.1.客戶端A
6.2.客戶端B
到此這篇關於SpringBoot+WebSocket實現多人在線聊天案例實例的文章就介紹到這瞭,更多相關SpringBoot WebSocket 多人聊天內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- SpringBoot的WebSocket實現單聊群聊
- SpringBoot+STOMP協議實現私聊、群聊
- springboot實現mock平臺的示例代碼
- springboot整合redis實現發送郵箱並驗證
- 使用maven開發springboot項目時pom.xml常用配置(推薦)