我有一个连接到远程websocket服务器的Java应用程序。作为客户,我使用标准的Java EE JSR356 WebSocket API:
javax.websocket.WebSocketContainer.connectToServer(...)
但是,我还没有找到使用此API指定连接超时的方法。当我调用connectToServer(...)方法时,它会阻塞,直到它建立连接(可能永远不会发生)。
有没有办法使用标准API指定连接超时?如果没有,是否有任何解决方法?
答案 0 :(得分:3)
不幸的是,JSR 356 - WebSocket API for Java没有公开这一点。您需要使用实现功能,例如HANDSHAKE_TIMEOUT中的Tyrus(参考实现)。其他实现很可能会有类似的东西。
好像在WEBSOCKET_SPEC中还没有关于这个的故障,所以如果你愿意,你可以添加一个(我只能找到提及SSL属性的问题 - WEBSOCKET_SPEC-210)。
答案 1 :(得分:0)
您可以简单地在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);
}
}
答案 2 :(得分:-2)
我自己就这样做了。如果通过Future构造调用connectToServer,则可以在get()方法中使用timeout。
您需要一个ThreadPool:
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...");
}
}