在Vertx中一段时间​​后如何实现WebSocket客户端重新连接?

时间:2019-02-09 16:12:53

标签: java websocket vert.x

我正在使用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);

}

以上代码已配置端口,主机等。请任何人建议如何重新连接?

1 个答案:

答案 0 :(得分:1)

您可以关闭客户端并重新启动它:

public void start() {
    startClient(this.vertx);
}

private void startClient(Vertx vertx) {
    HttpClient client = vertx.createHttpClient();

    client.websocket(8080, "localhost", "/", (ctx) -> {
        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);
            });
        });
    });
}

已编辑:在连接时间同时重试的任何异常也会在以下代码中发生。

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);
      });
  });
}