我正在使用 vertx 连接 websocket 服务器,但是当连接关闭/服务器(暂时(关闭时,尝试在一段时间后重新连接。
WebSocket 代码是:
public void start() throws Exception {
HttpClient client = vertx.createHttpClient();
MultiMap form = MultiMap.caseInsensitiveMultiMap();
if(MapUtils.isNotEmpty(header)) {
header.forEach((k,v)-> {
form.set(k, v);
});
}
RequestOptions options = new RequestOptions()
.setHost(host)
.setPort(port)
.setSsl(sslFlag)
.setURI(uri);
Handler<WebSocket> socket = new Handler<WebSocket>() {
@Override
public void handle(WebSocket event) {
event.handler(data -> {
currentCount = 0;
LOGGER.info("Received data " + data.toString("ISO-8859-1"));
});
}
};
Handler<Throwable> exception = new Handler<Throwable>() {
@Override
public void handle(Throwable event) {
LOGGER.error("Exception occured in Websocket connection, retrying count is {}", currentCount, event);
}
};
client.websocket(options, form, socket , exception);
}
上面配置了端口、主机等代码。请有人建议如何重新连接?
您可以关闭客户端并重新启动它:
public void start() {
startClient(this.vertx);
}
private void startClient(Vertx vertx) {
HttpClient client = vertx.createHttpClient();
client.webSocket(8080, "localhost", "/", (ar) -> {
if (ar.succeeded()) {
WebSocket ctx = ar.result();
ctx.textMessageHandler((msg) -> {
System.out.println("Client " + msg);
ctx.writeTextMessage("pong");
}).exceptionHandler((e) -> {
System.out.println("Restarting in 10 seconds");
client.close();
vertx.setTimer(10 * 1000, (__) -> {
startClient(vertx);
});
});
} else {
System.out.println(ar.cause());
}
});
}
已编辑:连接时间时出现任何异常,也会重试,请参见以下代码。
private void startClient(Vertx vertx) {
HttpClient client = vertx.createHttpClient();
MultiMap form = MultiMap.caseInsensitiveMultiMap();
if(MapUtils.isNotEmpty(header)) {
header.forEach((k,v)-> {
form.set(k, v);
});
}
RequestOptions options = new RequestOptions()
.setHost(host)
.setPort(port)
.setSsl(sslFlag)
.setURI(uri);
client.websocket(options, form, (ctx) ->{
ctx.textMessageHandler( msg -> {
System.out.println("Client " + msg);
}).exceptionHandler((e) -> {
client.close();
vertx.setTimer(waitTime * 10 * 1000, (__) -> {
startClient(vertx);
});
});
}, (exec) -> {
vertx.setTimer(waitTime * 10 * 1000, (__) -> {
startClient(vertx);
});
});
}