【问题标题】:Websocket ServerEndpoint instance by subprotocol子协议的 Websocket ServerEndpoint 实例
【发布时间】:2017-05-31 10:05:56
【问题描述】:

基于this question 我想创建一个基于协商子协议的服务器端点实例,以不同方式处理各种协议消息。不幸的是,ServerEndpointConfig.Configurator.getEndpointInstance [docs] 不允许我访问任何相关的会话数据以获取协商的子协议,因此我可以实例化不同的类。

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();
        // ...
    }
}

知道如何解决这个问题,或者是否有任何被广泛接受的做法来处理不同的子协议?我很难在网络上找到有关子协议处理的示例实现或高级文档。

【问题讨论】:

    标签: java jakarta-ee websocket javax


    【解决方案1】:

    这是你要找的吗?

    @ServerEndpoint("/ws")
    public class MyWebSocket {
    
        @OnOpen 
        public void onOpen(Session session) {
            session.getNegotiatedSubprotocol();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-08
      • 1970-01-01
      • 2015-02-28
      • 2014-12-27
      • 1970-01-01
      • 2015-04-14
      • 1970-01-01
      相关资源
      最近更新 更多