5

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));
bitdancer
  • 1,215
  • 2
  • 19
  • 34

1 Answers1

4

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());
wero
  • 32,544
  • 3
  • 59
  • 84
  • This is rather confusing. In the first section you have a constructor for MyWebSocketEndpoint declared as a member of MyWebSocketEndpointConfigurator. Then in the second section you seem to be trying to reference the private clientQueue, although there's a space before the underscore. Or maybe you're referencing the local one but mistyped it? – Evvo Dec 30 '19 at 20:44