如何使用构造函数参数初始化WebSocket端点
问题描述:
我现在正在使用javax.websocket.*
API,但我不知道如何在Internet上搜索后使用一些构造函数参数初始化Endpoint
。如何使用构造函数参数初始化WebSocket端点
ServerContainer container = WebSocketServerContainerInitializer.configureContext(context); //jetty
container.addEndpoint(MyWebSocketEndpoint.class);
我想初始化MyWebSocketEndpoint
时,那么我就可以使用该参数通过一些参数,比如clientQueue
,在我onOpen
方法做这样的事情:
clientQueue.add(new Client(session));
答
你需要调用ServerContainer.addEndpoint(ServerEndpointConfig)
,需要一个ServerEndpointConfig.Configurator
实施这项工作。
首先创建一个自定义ServerEndpointConfig.Configurator
类,用作工厂的端点:
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_);
}
}
,然后注册它的ServerContainer
:
ClientQueue clientQueue = ...
ServerContainer container = ...
container.addEndpoint(ServerEndpointConfig.Builder
.create(MyWebSocketEndpoint.class, "/") // the endpoint url
.configurator(new MyWebSocketEndpointConfigurator(clientQueue _))
.build());