简体   繁体   中英

Routing websocket destination in Spring-boot

Having raw websocket implementation:

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new MessageHandler(), "/websocket")
                .setAllowedOrigins("*")
                .addInterceptors();;
    }
}

Handler:

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

    }
}

The websocket client connect to server ( handshake etc. ) with /websocket url eg ws://localhost:8080/websocket

However, now that connection is estabilished is there a way how to route messages? Lets say i have app that provides chat and some pop-up functionality ( for simplicity lets say the user sends pop-up message and some pop-up window shows to all of his friends in app ).

Ofcourse i would like to route chat messages to /chat and popup to /popup .

One way how to achieve this is to send json message to server and parse it there eg:

    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")
          ....

    }

But this seems too slow, parsing json on every message. Is there some other, better way how to achieve routing?

Thanks for help!

Why don't you just register two different MessageHandlers

public class WebSocketConfig implements WebSocketConfigurer {
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new ChatMessageHandler(), "/chat")
                    .setAllowedOrigins("*")
                    .addInterceptors()
                .addHandler(new PopUpHandler(), "/popup") //etc;

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM