Reputation: 806
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.
Upvotes: 26
Views: 1067
Reputation: 6772
Is this what you are looking for?
@ServerEndpoint("/ws")
public class MyWebSocket {
@OnOpen
public void onOpen(Session session) {
session.getNegotiatedSubprotocol();
}
Upvotes: 1