3

In my websocket server I am retreiving a cutom header which I wan't link to the session it is from. I already got the a working ServerEndpointConfig.Configurator which looks like this:

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));
                }
            }
        }
    }
}

My ServerEndpoint looks like this:

@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);
    }
}

In the function onOpen I want to save link the session to the header value. But how can I access it?

Regards.

2 Answers 2

2

As per Oracle doc https://docs.oracle.com/javaee/7/tutorial/websocket010.htm

you need to update Endpoint Configuration properties in your Custom Configurator

conf.getUserProperties().put("key", value);

and then you can later access it in Endpoint public class MyEndpoint {

    @OnOpen
    public void open(Session s, EndpointConfig conf) {
        String value = conf.getUserProperties().get("key");
..
}
Sign up to request clarification or add additional context in comments.

Comments

1

I found a work around for my problem where I have to put a path parameter to the path.

Not sure if this is the best solution.

@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);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.