Java 如何使用构造函数参数初始化WebSocket端点
我现在正在使用Java 如何使用构造函数参数初始化WebSocket端点,java,java-websocket,Java,Java Websocket,我现在正在使用javax.websocket.*API,但在互联网上搜索后,我不知道如何使用一些构造函数参数初始化端点 ServerContainer container = WebSocketServerContainerInitializer.configureContext(context); //jetty container.addEndpoint(MyWebSocketEndpoint.class); 我想在初始化MyWebSocketEndpoint时传递一些参数,然后我可以在我
javax.websocket.*
API,但在互联网上搜索后,我不知道如何使用一些构造函数参数初始化端点
ServerContainer container = WebSocketServerContainerInitializer.configureContext(context); //jetty
container.addEndpoint(MyWebSocketEndpoint.class);
我想在初始化MyWebSocketEndpoint
时传递一些参数,然后我可以在我的onOpen
方法中使用参数,比如clientQueue
,执行以下操作:
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_);
}
}
这相当令人困惑。在第一部分中,您将MyWebSocketEndpoint的构造函数声明为MyWebSocketEndpointConfigurator的成员。然后在第二部分中,您似乎试图引用私有clientQueue,尽管下划线前有一个空格。或者你引用的是本地的,但打错了?
ClientQueue clientQueue = ...
ServerContainer container = ...
container.addEndpoint(ServerEndpointConfig.Builder
.create(MyWebSocketEndpoint.class, "/") // the endpoint url
.configurator(new MyWebSocketEndpointConfigurator(clientQueue _))
.build());