Websocket ServerEndpoint实例按子协议
问题描述:
根据this question我想创建一个基于协商的子协议的服务器端点实例来处理不同的协议消息。不幸的是ServerEndpointConfig.Configurator.getEndpointInstance
[docs]不会让我访问任何相关的会话数据来获得协商的子原型,所以我可以实例化不同的类。Websocket ServerEndpoint实例按子协议
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();
// ...
}
}
任何想法如何解决这个问题或者是否有任何被广泛接受的做法如何处理不同的子协议?我很难找到有关Web上的子协议处理的示例实现或高级文档。
答
这是你在找什么?
@ServerEndpoint("/ws")
public class MyWebSocket {
@OnOpen
public void onOpen(Session session) {
session.getNegotiatedSubprotocol();
}