/** 消息处理,在客户端通过Websocket API发送的消息会经过这里,然后进行相应的处理 */ public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { if (message.getPayloadLength() == 0) return; Message msg = new Gson().fromJson(message.getPayload().toString(), Message.class); msg.setDate(new Date()); sendMessageToUser( msg.getTo(), new TextMessage( new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create().toJson(msg))); }
@Test public void handleMessageToClientConnected() { UserSessionRegistry registry = new DefaultUserSessionRegistry(); this.protocolHandler.setUserSessionRegistry(registry); StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECTED); Message<byte[]> message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build(); this.protocolHandler.handleMessageToClient(this.session, message); assertEquals(1, this.session.getSentMessages().size()); WebSocketMessage<?> textMessage = this.session.getSentMessages().get(0); assertEquals("CONNECTED\n" + "user-name:joe\n" + "\n" + "\u0000", textMessage.getPayload()); assertEquals(Collections.singleton("s1"), registry.getSessionIds("joe")); }
/** 处理会话 */ @Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { // TODO Auto-generated method stub Map<String, String> select = JsonUtil.jsonToMap(message.getPayload().toString()); String result = webSocketService.getNewMessage(select); session.sendMessage(new TextMessage(result.toString())); WebSocketCache.putMemberSession(select.get("userId"), session); }