Java websocket在onOpen函数中获取自定义标头

时间:2015-11-06 14:59:22

标签: java websocket

在我的websocket服务器中,我正在检索一个cutom标题,我不想链接到它来自的会话。我已经找到了一个有效的ServerEndpointConfig.Configurator

public class WebSocketConfig extends ServerEndpointConfig.Configurator {

    private static final Logger LOG = LoggerFactory.getLogger(WebSocketConfig.class);

    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        Map<String, List<String>> headers = request.getHeaders();
        if (headers != null) {
            if (headers.containsKey("key")) {
                List<String> header = headers.get("key");
                if (header.size() > 0) {
                    LOG.info(header.get(0));
                }
            }
        }
    }
}

我的ServerEndpoint看起来像这样:

@ServerEndpoint(value = "/websocket", configurator = WebSocketConfig.class)
public class WebSocket {

    private static final Logger LOG = LoggerFactory.getLogger(WebSocket.class);

    public WebSocket() {
    }

    @OnOpen
    public void onOpen(Session session) {
        LOG.info("OnOpen");
    }

    @OnClose
    public void onClose(Session session) {
        LOG.info("OnClose");
    }

    @OnMessage
    public void onMessage(String message, Session session){
        LOG.info("OnMessage: " + message);
    }
}

在函数onOpen中,我想保存将会话链接到标头值。但是我怎样才能访问它?

问候。

1 个答案:

答案 0 :(得分:0)

我找到了解决问题的方法,我必须在路径中添加路径参数。

不确定这是否是最佳解决方案。

@ServerEndpoint(value = "/websocket/{key}", configurator = WebSocketConfig.class)
public class WebSocket {

    private static final Logger LOG = LoggerFactory.getLogger(WebSocket.class);

    public WebSocket() {
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("key") String key) {
        LOG.info("OnOpen");
    }

    @OnClose
    public void onClose(Session session) {
        LOG.info("OnClose");
    }

    @OnMessage
    public void onMessage(String message, Session session){
        LOG.info("OnMessage: " + message);
    }
}