Websocket ServerEndpoint instance by subprotocol
Asked Answered
I

1

26

Based on this question I'd like to create a server endpoint instance based on the negotiated subprotocol to handle various protocol messages differently. Unfortunately ServerEndpointConfig.Configurator.getEndpointInstance [docs] wouldn't let me access any relevant session data to get the negotiated subprotol so I could instantiate different classes.

public static class ServerEndpointConfigurator extends
        ServerEndpointConfig.Configurator {

    public ServerEndpointConfigurator()
    {
    }

    @Override
    public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
        // useful to work with session data in endpoint instance but not at getEndpointInstance
        HttpSession httpSession = (HttpSession) request.getHttpSession();
        config.getUserProperties().put(HttpSession.class.getName(), httpSession);
    }

    @Override
    public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException {

        // TODO get negotiated subprotocol and instantiate endpoint using switch case or factory

        return (T) new WebSocketControllerA();

        // or return (T) new WebSocketControllerB();
        // or return (T) new WebSocketControllerC();
        // ...
    }
}

Any idea how to solve this problem or are there any widely accepted practices how to handle different subprotocols? I am having a hard time finding example implementations or advanced documentation about subprotocol handling on the web.

Intestine answered 16/1, 2017 at 14:24 Comment(0)
J
1

Is this what you are looking for?

@ServerEndpoint("/ws")
public class MyWebSocket {

    @OnOpen 
    public void onOpen(Session session) {
        session.getNegotiatedSubprotocol();
    }
Janessajanet answered 25/11, 2017 at 22:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.