Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a WebSocket Endpoint with constructor parameters

Tags:

I am using javax.websocket.* API right now but I don't know how to initialize an Endpoint with some constructor parameters after searching on the Internet.

ServerContainer container = WebSocketServerContainerInitializer.configureContext(context); //jetty
container.addEndpoint(MyWebSocketEndpoint.class);

I want pass through some parameters when initializing MyWebSocketEndpoint then I can use the parameter, say clientQueue, in my onOpen method doing something like:

clientQueue.add(new Client(session));
like image 314
bitdancer Avatar asked Jun 14 '16 15:06

bitdancer


People also ask

Is a WebSocket an endpoint?

The Web Socket Endpoint represents an object that can handle websocket conversations. Developers may extend this class in order to implement a programmatic websocket endpoint. The Endpoint class holds lifecycle methods that may be overridden to intercept websocket open, error and close events.

What is WebSocket container?

A WebSocketContainer is an implementation provided object that provides applications a view on the container running it.

What is WebSocket session?

A Web Socket session represents a conversation between two web socket endpoints. As soon as the websocket handshake completes successfully, the web socket implementation provides the endpoint an open websocket session.


1 Answers

You need to call ServerContainer.addEndpoint(ServerEndpointConfig) and need a ServerEndpointConfig.Configurator implementation to make this work.

First create a custom ServerEndpointConfig.Configurator class which acts as factory for your endpoint:

public class MyWebSocketEndpointConfigurator extends ServerEndpointConfig.Configurator {
    private ClientQueue clientQueue_;

    public MyWebSocketEndpoint(ClientQueue clientQueue) {
        clientQueue_ = clientQueue;
    }

    public <T> T getEndpointInstance(Class<T> clazz) throws InstantiationException {
        return (T)new MyWebSocketEndpoint(clientQueue_);
    }
}

and then register it on the ServerContainer:

ClientQueue clientQueue = ...
ServerContainer container = ...
container.addEndpoint(ServerEndpointConfig.Builder
    .create(MyWebSocketEndpoint.class, "/") // the endpoint url
    .configurator(new MyWebSocketEndpointConfigurator(clientQueue _))
    .build());
like image 96
wero Avatar answered Sep 28 '22 03:09

wero