您现在的位置是:首页 >技术杂谈 >springboot集成websocket向同一房间中的所有人发送信息网站首页技术杂谈
springboot集成websocket向同一房间中的所有人发送信息
简介springboot集成websocket向同一房间中的所有人发送信息
springboot集成websocket向同一房间中的所有人发送信息
-
maven依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
-
配置类
import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { private final SocketHandler socketHandler; public WebSocketConfig(SocketHandler webSocketHandler) { this.socketHandler = webSocketHandler; } @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { // 设置允许的跨域请求 registry.addHandler(socketHandler, "/websocket") .setAllowedOrigins("*"); } }
-
服务
import org.springframework.stereotype.Component; import org.springframework.web.socket.*; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.HashMap; import java.util.Map; @ServerEndpoint("/websocket") @Component public class SocketHandler implements WebSocketHandler { private static final Map<String, Map<String, WebSocketSession>> roomSessionsMap = new HashMap<>(); @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { System.out.println("WebSocket连接建立:" + session.getId()); // 获取房间号 String roomId = session.getUri().getQuery(); // 获取该房间的WebSocketSession Map,如果不存在则创建 Map<String, WebSocketSession> roomSessions = roomSessionsMap.get(roomId); if (roomSessions == null) { roomSessions = new HashMap<>(); roomSessionsMap.put(roomId, roomSessions); } // 将WebSocketSession与房间号关联 roomSessions.put(session.getId(), session); } @Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { System.out.println("接收到WebSocket消息:" + message.getPayload()); // 处理收到的消息 String roomId = session.getUri().getQuery(); Map<String, WebSocketSession> roomSessions = roomSessionsMap.get(roomId); if (roomSessions != null) { // 遍历发送给同一个房间的所有WebSocketSession for (WebSocketSession roomSession : roomSessions.values()) { try { roomSession.sendMessage(new TextMessage("服务器收到来自房间号:"+roomId+"的消息:" + message.getPayload())); } catch (IOException e) { // 处理发送异常 e.printStackTrace(); } } } } @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { System.out.println("WebSocket连接关闭:" + session.getId()); // 获取房间号 String roomId = session.getUri().getQuery(); // 获取该房间的WebSocketSession Map Map<String, WebSocketSession> roomSessions = roomSessionsMap.get(roomId); if (roomSessions != null) { // 移除与房间号关联的WebSocketSession roomSessions.remove(session.getId()); // 如果房间中没有其他WebSocketSession了,移除房间 if (roomSessions.isEmpty()) { roomSessionsMap.remove(roomId); } } } @Override public boolean supportsPartialMessages() { return false; } }
-
前端html代码
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>WebSocket Example</title> <script> var socket = null; function initWebSocket() { var roomId = document.getElementById("roomId").value; // 设置房间号 console.log("房间号:", roomId); if (roomId == null || roomId == "") { alert("请输入房间名"); return; } alert("ws://localhost:8523/websocket?roomId=" + roomId) socket = new WebSocket("ws://localhost:8523/websocket?roomId=" + roomId); socket.onopen = function() { console.log("WebSocket连接已建立"); socket.send("Hello, Server!"); }; socket.onmessage = function(event) { console.log("接收到WebSocket消息:" + event.data); }; socket.onclose = function(event) { console.log("WebSocket连接已关闭", event); }; } function sendMessage() { var message = document.getElementById("messageInput").value; socket.send(message); } </script> </head> <body> <input type="text" id="roomId" placeholder="房间号"/> <input type="button" value="进入聊天室" onclick="initWebSocket()" /><br/> <input type="text" id="messageInput" placeholder="输入消息"> <button onclick="sendMessage()">发送</button> </body> </html>
注意事项
:如果连接失败,可以看一下配置类代码中的路径,看和自己设置的路径是否一致:registry.addHandler(socketHandler, "/websocket").setAllowedOrigins("*");
风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。