具有原始的websocket实现:
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new MessageHandler(), "/websocket")
.setAllowedOrigins("*")
.addInterceptors();;
}
}
处理程序:
public class MessageHandler extends TextWebSocketHandler {
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
// The WebSocket has been closed
}
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
String auth = (String) session.getAttributes().get("auth");
System.out.println(auth);
session.sendMessage(new TextMessage("You are now connected to the server. This is the first message."));
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage textMessage) throws Exception {
// A message has been received
}
}
websocket客户端使用/websocket
网址(例如ws://localhost:8080/websocket
但是,现在已建立连接,有没有办法路由消息?假设我有一个提供聊天功能和某些弹出功能的应用程序(为简单起见,该用户向应用程序中的所有朋友发送了弹出消息和一些弹出窗口)。
当然我想将聊天消息路由到/chat
,并弹出到/popup
。
一种实现此目的的方法是将json消息发送到服务器并在其中解析,例如:
protected void handleTextMessage(WebSocketSession session, TextMessage textMessage) throws Exception {
String path = getRouteFromJsonMessage(textMessage);
if( ! "".equals(path) && path.equals("chat")
....
if( ! "".equals(path) && path.equals("popup")
....
}
但这似乎太慢了,在每条消息上解析json。还有其他更好的方法来实现路由吗?
感谢帮助!
答案 0 :(得分:0)
为什么不只注册两个不同的MessageHandlers
public class WebSocketConfig implements WebSocketConfigurer {
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new ChatMessageHandler(), "/chat")
.setAllowedOrigins("*")
.addInterceptors()
.addHandler(new PopUpHandler(), "/popup") //etc;
}
}