我有一个连接到远程websocket服务器的Java应用程序。作为一个客户,我使用标准的JavaEEJSR356WebSocketneneneba API:
javax.websocket.WebSocketContainer.connectToServer(...)
然而,我还没有找到使用这个API指定连接超时的方法。当我调用connectToServer(…)方法时,它会阻塞,直到建立连接(这可能永远不会发生)。
是否有方法使用标准API指定连接超时?如果没有,有什么解决办法吗?
不幸的是,这并没有被JSR 356-WebSocket API for Java公开。您将需要使用实现特性,例如Tyrus中的HANDSHAKE_TIMEOUT(参考实现)。其他实现很可能会有类似的东西。
在WEBSOCKET_SPEC中似乎还没有关于这一点的票证,所以如果你想的话,你可以添加一个(我能找到唯一提到SSL属性的问题-WEBSOCKET_SPEC-210)。
您可以简单地重写WsWebSocketContainer 中的方法connectToServer
public class WsWebSocketContainer2 extends WsWebSocketContainer {
@Override
public Session connectToServer(Object pojo, URI path) throws DeploymentException {
ClientEndpoint annotation = pojo.getClass().getAnnotation(ClientEndpoint.class);
if (annotation == null) {
throw new DeploymentException("wsWebSocketContainer.missingAnnotation");
}
Endpoint ep = new PojoEndpointClient(pojo, Arrays.asList(annotation.decoders()));
Class<? extends ClientEndpointConfig.Configurator> configuratorClazz = annotation.configurator();
ClientEndpointConfig.Configurator configurator = null;
if (!ClientEndpointConfig.Configurator.class.equals(configuratorClazz)) {
try {
configurator = configuratorClazz.getConstructor().newInstance();
} catch (ReflectiveOperationException e) {
throw new DeploymentException("wsWebSocketContainer.defaultConfiguratorFail", e);
}
}
ClientEndpointConfig.Builder builder = ClientEndpointConfig.Builder.create();
// Avoid NPE when using RI API JAR - see BZ 56343
if (configurator != null) {
builder.configurator(configurator);
}
ClientEndpointConfig config = builder.decoders(Arrays.asList(annotation.decoders())).encoders(Arrays.asList(annotation.encoders()))
.preferredSubprotocols(Arrays.asList(annotation.subprotocols())).build();
Map<String, Object> userProperties = config.getUserProperties();
userProperties.put(Constants.IO_TIMEOUT_MS_PROPERTY, 999999);
return connectToServer(ep, config, path);
}
}
我自己刚刚开始工作。如果通过Future构造调用connectToServer,则可以在get()方法中使用超时。
你需要一个线程池:
private final ExecutorService pool = Executors.newFixedThreadPool(10);
功能如下:
private Future<Session> asyncConnectToServer(Object annotatedEndpointInstance, URI uri) {
return pool.submit(new Callable<Session>() {
@Override
public Session call() throws Exception {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
return(container.connectToServer(annotatedEndpointInstance, uri));
} catch (DeploymentException | IOException | IllegalStateException e) {
//throw new RuntimeException(e);
return(null);
}
}
});
}
这就是你所说的:
public webSocketClientEndpoint(URI endpointURI, long timeout) {
final Future<Session> futureSes = asyncConnectToServer(this, endpointURI);
try {
Session ses = futureSes.get(timeout, TimeUnit.MILLISECONDS);
} catch(InterruptedException | ExecutionException | TimeoutException e) {
System.out.println("Time out...");
}
}
参考编号:https://dzone.com/articles/javautilconcurrentfuture
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html#get(long,%20java.util.concurrent.TimeUnit)