1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
| @Component public class WebSocketHandler implements WebSocketHandler {
public static ConcurrentHashMap<String, WebSocketSession> webSocketSessionMap = new ConcurrentHashMap<>();
@Override public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception { String websocket_id = (String) webSocketSession.getAttributes().get("socket_id"); webSocketSessionMap.put(websocket_id,webSocketSession); LogUtil.debug(websocket_id + ",建立连接成功..."); }
@Override public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception { LogUtil.debug("获取发来的消息," + webSocketMessage.getPayload().toString()); }
@Override public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception { String websocket_id = (String) webSocketSession.getAttributes().get("socket_id"); webSocketSessionMap.remove(websocket_id); LogUtil.debug(websocket_id + ",连接出现错误..."); }
@Override public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception { String websocket_id = (String) webSocketSession.getAttributes().get("socket_id"); webSocketSessionMap.remove(websocket_id); LogUtil.debug(websocket_id + ",关闭连接..."); } @Override public boolean supportsPartialMessages() { return false; }
public void sendMessageToAllUser(String message){ ConcurrentHashMap.KeySetView<String, WebSocketSession> keySet = webSocketSessionMap.keySet(); Iterator<String> iterator = keySet.iterator(); while (iterator.hasNext()){ String websocket_id = iterator.next(); WebSocketSession webSocketSession = webSocketSessionMap.get(websocket_id); if(webSocketSession != null && webSocketSession.isOpen()){ try { webSocketSession.sendMessage(new TextMessage(message)); } catch (IOException e) { LogUtil.error("websocket 发送数据失败,失败原因:" + e); } } } }
public void sendMessageToOneUser(String socketId,String message){ if(!StringUtils.isEmpty(socketId)){ if(webSocketSessionMap.containsKey(socketId)){ WebSocketSession webSocketSession = webSocketSessionMap.get(socketId); if(webSocketSession != null && webSocketSession.isOpen()){ try { webSocketSession.sendMessage(new TextMessage(message)); } catch (IOException e) { LogUtil.error("websocket 发送数据失败,失败原因:" + e); } } } } } }
|