|
|
@@ -6,10 +6,12 @@ import org.springframework.web.socket.TextMessage;
|
|
|
import org.springframework.web.socket.WebSocketSession;
|
|
|
import org.springframework.web.socket.handler.TextWebSocketHandler;
|
|
|
|
|
|
+import java.io.IOException;
|
|
|
import java.util.Map;
|
|
|
import java.util.concurrent.ConcurrentHashMap;
|
|
|
|
|
|
@Component
|
|
|
+//@ServerEndpoint(value = "",subprotocols = {"protocol"})
|
|
|
public class WebSocketHandler extends TextWebSocketHandler {
|
|
|
|
|
|
private final Map<String,WebSocketSession> sessions = new ConcurrentHashMap<String,WebSocketSession>();
|
|
|
@@ -17,6 +19,7 @@ public class WebSocketHandler extends TextWebSocketHandler {
|
|
|
@Override
|
|
|
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
|
|
|
sessions.put("123",session);
|
|
|
+
|
|
|
System.out.println("New connection established: " + session.getId());
|
|
|
}
|
|
|
|
|
|
@@ -24,6 +27,7 @@ public class WebSocketHandler extends TextWebSocketHandler {
|
|
|
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
|
|
|
String payload = message.getPayload();
|
|
|
System.out.println("Received message: " + payload);
|
|
|
+ session.sendMessage(new TextMessage("Hello, client!"));
|
|
|
// 处理消息并入数据库
|
|
|
}
|
|
|
|
|
|
@@ -33,7 +37,9 @@ public class WebSocketHandler extends TextWebSocketHandler {
|
|
|
System.out.println("Connection closed: " + session.getId());
|
|
|
}
|
|
|
|
|
|
- public void sendMessageToAll(String message) {
|
|
|
-
|
|
|
+ public void sendMessageToAll(String message) throws IOException {
|
|
|
+ for (WebSocketSession value : sessions.values()) {
|
|
|
+ value.sendMessage(new TextMessage(message));
|
|
|
+ }
|
|
|
}
|
|
|
}
|