|
|
@@ -0,0 +1,39 @@
|
|
|
+package com.xunmei.mediator.websocket;
|
|
|
+
|
|
|
+import org.springframework.stereotype.Component;
|
|
|
+import org.springframework.web.socket.CloseStatus;
|
|
|
+import org.springframework.web.socket.TextMessage;
|
|
|
+import org.springframework.web.socket.WebSocketSession;
|
|
|
+import org.springframework.web.socket.handler.TextWebSocketHandler;
|
|
|
+
|
|
|
+import java.util.Map;
|
|
|
+import java.util.concurrent.ConcurrentHashMap;
|
|
|
+
|
|
|
+@Component
|
|
|
+public class WebSocketHandler extends TextWebSocketHandler {
|
|
|
+
|
|
|
+ private final Map<String,WebSocketSession> sessions = new ConcurrentHashMap<String,WebSocketSession>();
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public void afterConnectionEstablished(WebSocketSession session) throws Exception {
|
|
|
+ sessions.put("123",session);
|
|
|
+ System.out.println("New connection established: " + session.getId());
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
|
|
|
+ String payload = message.getPayload();
|
|
|
+ System.out.println("Received message: " + payload);
|
|
|
+ // 处理消息并入数据库
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
|
|
|
+ sessions.remove(session);
|
|
|
+ System.out.println("Connection closed: " + session.getId());
|
|
|
+ }
|
|
|
+
|
|
|
+ public void sendMessageToAll(String message) {
|
|
|
+
|
|
|
+ }
|
|
|
+}
|