SpringBoot--WebSocket 太过爱你忘了你带给我的痛 2022-05-22 04:08 185阅读 0赞 目录结构: ![70][] 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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.segmentfault</groupId> <artifactId>spring-boot-lesson-13</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>spring-boot-lesson-13</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.6.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</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-websocket</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> chat.html页面: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>聊天室</title> <script src="https://code.jquery.com/jquery-3.2.1.min.js" ></script> </head> <body> 聊天消息内容: <br/> <textarea id="text\_chat\_content" readonly="readonly" cols="100" rows="9"> </textarea> <br/> 用户:<input id="in\_user\_name" value=""/> <button id="btn\_join">加入聊天室</button> <button id="btn\_exit">离开聊天室</button> <br/> 输入框:<input id="in\_msg" value=""/><button id="btn\_send">发送消息</button> <script type="text/javascript"> $(document).ready(function()\{ var urlPrefix ='ws://192.168.0.3:8080/chat-room/'; var ws = null; $('\#btn\_join').click(function()\{ var username = $('\#in\_user\_name').val(); var url = urlPrefix+username; ws = new WebSocket(url); ws.onmessage = function(event)\{ //服务端发送的消息 $('\#text\_chat\_content').append(event.data+'\\n'); \} ws.onclose = function(event)\{ $('\#text\_chat\_content').append('用户\['+username+'\] 已经离开聊天室!'); \} \}); //客户端发送消息到服务器 $('\#btn\_send').click(function()\{ var msg = $('\#in\_msg').val(); if(ws)\{ ws.send(msg); \} \}); //离开聊天室 $('\#btn\_exit').click(function()\{ if(ws)\{ ws.close(); \} \}); \}) </script> </body> </html> package com.segmentfault.springbootlesson13.websocket; import javax.websocket.\*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /\*\* \* 聊天室 \{@link ServerEndpoint\} \* \* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a> \* @see \* @since 2017.08.16 \*/ @ServerEndpoint("/chat-room/\{username\}") public class ChatRoomServerEndpoint \{ private static Map<String, Session> livingSessions = new ConcurrentHashMap<String, Session>(); @OnOpen public void openSession(@PathParam("username") String username, Session session) \{ String sessionId = session.getId(); livingSessions.put(sessionId, session); sendTextAll("欢迎用户\[" + username + "\] 来到聊天室!"); // sendText(session, "欢迎用户\[" + username + "\] 来到聊天室!"); \} @OnMessage public void onMessage(@PathParam("username") String username, Session session, String message) \{ // sendText(session, "用户\[" + username + "\] : " + message); sendTextAll("用户\[" + username + "\] : " + message); \} private void sendTextAll(String message) \{ livingSessions.forEach((sessionId, session) -> \{ sendText(session,message); \}); \} @OnClose public void onClose(@PathParam("username") String username, Session session) \{ String sessionId = session.getId(); //当前的Session 移除 livingSessions.remove(sessionId); //并且通知其他人当前用户已经离开聊天室了 sendTextAll("用户\[" + username + "\] 已经离开聊天室了!"); \} private void sendText(Session session, String message) \{ RemoteEndpoint.Basic basic = session.getBasicRemote(); try \{ basic.sendText(message); \} catch (IOException e) \{ e.printStackTrace(); \} \} \} package com.segmentfault.springbootlesson13; import com.segmentfault.springbootlesson13.websocket.ChatRoomServerEndpoint; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.server.standard.ServerEndpointExporter; @SpringBootApplication @EnableWebSocket public class SpringBootLesson13Application \{ public static void main(String\[\] args) \{ SpringApplication.run(SpringBootLesson13Application.class, args); \} @Bean public ServerEndpointExporter serverEndpointExporter() \{ return new ServerEndpointExporter(); \} @Bean public ChatRoomServerEndpoint chatRoomServerEndpoint() \{ return new ChatRoomServerEndpoint(); \} \} 测试:http://192.168.0.3:8080/chat.html ![70 1][] [70]: /images/20220522/c661407e435d4baca1287bd84a3e6465.png [70 1]: /images/20220522/daba4a63685549d68b7da70becceb45b.png
相关 springbootWebSocket环境搭建 springboot webSocket环境搭建 pom编辑: 添加如下内容: <dependency> <groupId>org.spring 拼搏现实的明天。/ 2022年05月09日 05:06/ 0 赞/ 266 阅读
还没有评论,来说两句吧...