TCP Client

Creating a TCP client

最简单的创建TCP客户端的方式是使用默认的NetClientOptions

  1. NetClient client = vertx.createNetClient();

Configuring a TCP client

如果你不想要使用默认的NetClientOptions配置,那么你可以创建一个NetClientOptions实例进行TCP客户端创建:

  1. NetClientOptions options = new NetClientOptions().setConnectTimeout(10000);
  2. NetClient client = vertx.createNetClient(options);

Making connections

为了和服务器创建一个连接,你需要使用connect方法,在该方法中需要指定hsotport,同时需要设置一个handler,当连接成功或者失败之后,handler会获得一个NetSocket的参数.

  1. NetClientOptions options = new NetClientOptions().setConnectTimeout(10000);
  2. NetClient client = vertx.createNetClient(options);
  3. client.connect(4321, "localhost", res -> {
  4. if (res.succeeded()) {
  5. System.out.println("Connected!");
  6. NetSocket socket = res.result();
  7. } else {
  8. System.out.println("Failed to connect: " + res.cause().getMessage());
  9. }
  10. });

Configuring connection attempts

A client can be configured to automatically retry connecting to the server in the event that it cannot connect. This is configured with setReconnectInterval and setReconnectAttempts. 客户端可以被配制成当连接不成功的时候在event里自动响应服务器的应答. 通过setReconnectIntervalsetReconnectAttempts来设置这种机制.

NOTE Currently Vert.x will not attempt to reconnect if a connection fails, reconnect attempts and interval only apply to creating initial connections. 注意:当连接失败之后,Vertx不会尝试自动重连,

  1. NetClientOptions options = new NetClientOptions();
  2. options.setReconnectAttempts(10).setReconnectInterval(500);
  3. NetClient client = vertx.createNetClient(options);

在默认情况下,创建多个连接是会失败的.