Java 类io.vertx.core.net.NetClientOptions 实例源码

项目:okapi    文件:ProcessModuleHandle.java   
@Override
public void start(Handler<AsyncResult<Void>> startFuture) {
  if (port > 0) {
    // fail if port is already in use
    NetClientOptions options = new NetClientOptions().setConnectTimeout(200);
    NetClient c = vertx.createNetClient(options);
    c.connect(port, "localhost", res -> {
      if (res.succeeded()) {
        NetSocket socket = res.result();
        socket.close();
        startFuture.handle(Future.failedFuture("port " + port + " already in use"));
      } else {
        start2(startFuture);
      }
    });
  } else {
    start2(startFuture);
  }
}
项目:okapi    文件:ProcessModuleHandle.java   
private void waitPortToClose(Handler<AsyncResult<Void>> stopFuture, int iter) {
  if (port > 0) {
    // fail if port is already in use
    NetClientOptions options = new NetClientOptions().setConnectTimeout(50);
    NetClient c = vertx.createNetClient(options);
    c.connect(port, "localhost", res -> {
      if (res.succeeded()) {
        NetSocket socket = res.result();
        socket.close();
        if (iter > 0) {
          vertx.setTimer(100, x -> waitPortToClose(stopFuture, iter - 1));
        } else {
          stopFuture.handle(Future.failedFuture("port " + port + " not shut down"));
        }
      } else {
        stopFuture.handle(Future.succeededFuture());
      }
    });
  } else {
    stopFuture.handle(Future.succeededFuture());
  }
}
项目:gravitee-management-rest-api    文件:ManagementApiProbe.java   
@Override
public Future<Result> check() {
    Future<Result> future = Future.future();

    NetClientOptions options = new NetClientOptions().setConnectTimeout(500);
    NetClient client = vertx.createNetClient(options);

    client.connect(port, host, res -> {
        if (res.succeeded()) {
            future.complete(Result.healthy());
        } else {
            future.complete(Result.unhealthy(res.cause()));
        }

        client.close();
    });

    return future;
}
项目:gravitee-gateway    文件:GatewayProbe.java   
@Override
public CompletableFuture<Result> check() {
    VertxCompletableFuture<Result> result = new VertxCompletableFuture<>(vertx);

    NetClientOptions options = new NetClientOptions().setConnectTimeout(500);
    NetClient client = vertx.createNetClient(options);

    client.connect(port, host, res -> {
        if (res.succeeded()) {
            result.complete(Result.healthy());
        } else {
            result.complete(Result.unhealthy(res.cause()));
        }

        client.close();
    });

    return result;
}
项目:vertx-mail-client    文件:SMTPConnectionPool.java   
SMTPConnectionPool(Vertx vertx, MailConfig config) {
  this.config = config;
  this.vertx = vertx;
  maxSockets = config.getMaxPoolSize();
  keepAlive = config.isKeepAlive();
  NetClientOptions netClientOptions = new NetClientOptions().setSsl(config.isSsl()).setTrustAll(config.isTrustAll());
  if ((config.isSsl() || config.getStarttls() != StartTLSOptions.DISABLED) && !config.isTrustAll()) {
    // we can use HTTPS verification, which matches the requirements for SMTPS
    netClientOptions.setHostnameVerificationAlgorithm("HTTPS");
  }
  if (config.getKeyStore() != null) {
    // assume that password could be null if the keystore doesn't use one
    netClientOptions.setTrustStoreOptions(new JksOptions().setPath(config.getKeyStore())
        .setPassword(config.getKeyStorePassword()));
  }
  netClient = vertx.createNetClient(netClientOptions);
}
项目:vertx-fastdfs-client    文件:FdfsClientImpl.java   
public FdfsClientImpl(Vertx vertx, FdfsClientOptions options) {
    this.vertx = vertx;
    this.pool = new FdfsConnectionPool(vertx, new NetClientOptions().setConnectTimeout((int) options.getConnectTimeout()), options.getPoolSize());
    this.options = options;
    this.currentTrackerIndex = 0;
    this.trackerCount = options.getTrackers().size();
}
项目:gpsd4j    文件:GpsdClient.java   
private void createNetClient()
{
   NetClientOptions netClientOptions = new NetClientOptions()
         .setConnectTimeout(options.getConnectTimeout())
         .setIdleTimeout(options.getIdleTimeout())
         .setReconnectAttempts(options.getReconnectAttempts())
         .setReconnectInterval(options.getReconnectInterval())
         .setReceiveBufferSize(BUFFER_SIZE);

   this.netClient = this.vertx.createNetClient(netClientOptions);
}
项目:reactive-pg-client    文件:PgConnectionFactory.java   
public PgConnectionFactory(Context context,
                           boolean registerCloseHook,
                           PgConnectOptions options) {

  hook = this::close;
  this.registerCloseHook = registerCloseHook;

  ctx = context;
  if (registerCloseHook) {
    ctx.addCloseHook(hook);
  }

  NetClientOptions netClientOptions = new NetClientOptions(options);

  // Make sure ssl=false as we will use STARTLS
  netClientOptions.setSsl(false);

  this.ssl = options.isSsl();
  this.host = options.getHost();
  this.port = options.getPort();
  this.database = options.getDatabase();
  this.username = options.getUsername();
  this.password = options.getPassword();
  this.client = context.owner().createNetClient(netClientOptions);
  this.cachePreparedStatements = options.getCachePreparedStatements();
  this.pipeliningLimit = options.getPipeliningLimit();
}
项目:okapi    文件:ProcessModuleHandle.java   
private void tryConnect(Handler<AsyncResult<Void>> startFuture, int count) {
  NetClientOptions options = new NetClientOptions().setConnectTimeout(MILLISECONDS);
  NetClient c = vertx.createNetClient(options);
  c.connect(port, "localhost", res -> {
    if (res.succeeded()) {
      logger.info("Connected to service at port " + port + " count " + count);
      NetSocket socket = res.result();
      socket.close();
      try {
        p.getErrorStream().close();
      } catch (Exception e) {
        logger.error("Closing streams failed: " + e);
      }
      startFuture.handle(Future.succeededFuture());
    } else if (!p.isAlive() && p.exitValue() != 0) {
      logger.warn("Service returned with exit code " + p.exitValue());
      startFuture.handle(Future.failedFuture("Service returned with exit code "
        + p.exitValue()));
    } else if (count < maxIterations) {
      vertx.setTimer((long) (count + 1) * MILLISECONDS,
        id -> tryConnect(startFuture, count + 1));
    } else {
      startFuture.handle(Future.failedFuture("Deployment failed. "
        + "Could not connect to port " + port + ": " + res.cause().getMessage()));
    }
  });
}
项目:shadowsocks-vertx    文件:ServerHandler.java   
private void connectToRemote(String addr, int port) {
    // 5s timeout.
    NetClientOptions options = new NetClientOptions().setConnectTimeout(5000);
    NetClient client = mVertx.createNetClient(options);
    client.connect(port, addr, res -> {  // connect handler
        if (!res.succeeded()) {
            log.error("Failed to connect " + addr + ":" + port + ". Caused by " + res.cause().getMessage());
            destory();
            return;
        }
        mTargetSocket = res.result();
        setFinishHandler(mTargetSocket);
        mTargetSocket.handler(buffer -> { // remote socket data handler
            try {
                byte [] data = buffer.getBytes();
                byte [] encryptData = mCrypto.encrypt(data, data.length);
                flowControl(mClientSocket, mTargetSocket);
                mClientSocket.write(Buffer.buffer(encryptData));
            }catch(CryptoException e){
                log.error("Catch exception", e);
                destory();
            }
        });
        if (mBufferQueue.length() > 0) {
            handleStageData();
        }
    });
}
项目:vertx-amqp-service    文件:MyReceiver.java   
public MyReceiver(String host, int port, String dest) throws MessagingException
{
    NetClient netClient = Vertx.factory.vertx().createNetClient(new NetClientOptions());
    DefaultConnectionSettings settings = new DefaultConnectionSettings();
    settings.setHost(host);
    settings.setPort(port);
    connection = new ManagedConnection(settings, this, false);
    netClient.connect(settings.getPort(), settings.getHost(), result -> {
        if (result.succeeded())
        {
            connection.setNetSocket(result.result());
            connection.write();
            connection.addDisconnectHandler(c -> {
                LOG.warn("Connection lost to peer at  %s:%s", connection.getSettings().getHost(), connection
                    .getSettings().getPort());
            });
            LOG.info("Connected to AMQP peer at %s:%s", connection.getSettings().getHost(), connection
                    .getSettings().getPort());
        }
        else
        {
            LOG.warn("Error {%s}, when connecting to AMQP peer at %s:%s", result.cause(), connection.getSettings()
                    .getHost(), connection.getSettings().getPort());
        }
    });
    link = connection.createInboundLink(dest, ReliabilityMode.AT_LEAST_ONCE, CreditMode.AUTO);
    link.setCredits(10);

}
项目:vertx-amqp-service    文件:MySender.java   
public MySender(String host, int port, String destination) throws MessagingException
{
    NetClient netClient = Vertx.factory.vertx().createNetClient(new NetClientOptions());
    DefaultConnectionSettings settings = new DefaultConnectionSettings();
    settings.setHost(host);
    settings.setPort(port);
    connection = new ManagedConnection(settings, this, false);
    netClient.connect(settings.getPort(), settings.getHost(), result -> {
        if (result.succeeded())
        {
            connection.setNetSocket(result.result());
            connection.write();
            connection.addDisconnectHandler(c -> {
                LOG.warn("Connection lost to peer at  %s:%s", connection.getSettings().getHost(), connection
                    .getSettings().getPort());
            });
            LOG.info("Connected to AMQP peer at %s:%s", connection.getSettings().getHost(), connection
                    .getSettings().getPort());
        }
        else
        {
            LOG.warn("Error {%s}, when connecting to AMQP peer at %s:%s", result.cause(), connection.getSettings()
                    .getHost(), connection.getSettings().getPort());
        }
    });
    link = connection.createOutboundLink(destination, ReliabilityMode.AT_LEAST_ONCE);

}
项目:mipod.x    文件:MpdClient.java   
private CompletableFuture<ConnectionInstance> connect() {
    LOGGER.info("Connecting to MPD...");
    final CompletableFuture<NetSocket> netSocketReady = new CompletableFuture<>();
    vertx.createNetClient(new NetClientOptions()
            .setConnectTimeout(CONNECTION_TIMEOUT)
            .setReceiveBufferSize(DEFAULT_BUFFER_SIZE)
            .setReconnectAttempts(RECONNECT_ATTEMPTS)
            .setReconnectInterval(RECONNECT_INTERVAL_MS)
            .setTcpKeepAlive(true))
            .connect(configuration.getPort(), configuration.getHostname(), res -> {
                if (res.succeeded()) {
                    netSocketReady.complete(res.result());
                    LOGGER.info("Connection successful");
                } else {
                    error("Connection failure", res.cause());
                    netSocketReady.completeExceptionally(res.cause());
                }
            });
    return netSocketReady
            .thenApply(netSocket -> {
                LineStreamer ls = new LineStreamer(netSocket, "\n");
                LOGGER.info(ls);
                return ls;
            })
            .thenCompose(lineStreamer -> lineStreamer.expect(MPD_CONNECT_OK))
            .thenCombine(netSocketReady, ConnectionInstance::new)
            .exceptionally(t -> {
                error("Initial MPD connection failure: ", t);
                return null;
            });
}
项目:vertx-dropwizard-metrics    文件:VertxMetricsImpl.java   
@Override
public TCPMetrics<?> createMetrics(NetClientOptions options) {
  String baseName;
  if (options.getMetricsName() != null) {
    baseName = nameOf("net.clients", options.getMetricsName());
  } else {
   baseName = nameOf("net.clients");
  }
  return new TCPMetricsImpl(registry, baseName);
}
项目:vertx-dropwizard-metrics    文件:MetricsTestBase.java   
protected NetClient createNetClient(NetClientOptions options) {
  NetClient client = vertx.createNetClient(options);
  toClose.add(() -> {
    CountDownLatch latch = new CountDownLatch(1);
    client.close();
    awaitLatch(latch);
    return null;
  });
  return client;
}
项目:vertx-dropwizard-metrics    文件:MetricsTest.java   
@Test
public void testNetMetricsOnClose() throws Exception {
  int requests = 8;
  CountDownLatch latch = new CountDownLatch(requests);

  NetClient client = vertx.createNetClient(new NetClientOptions());
  NetServer server = vertx.createNetServer(new NetServerOptions().setHost("localhost").setPort(1235).setReceiveBufferSize(50)).connectHandler(socket -> {
    socket.handler(buff -> latch.countDown());
  }).listen(ar -> {
    assertTrue(ar.succeeded());
    client.connect(1235, "localhost", ar2 -> {
      assertTrue(ar2.succeeded());
      for (int i = 0; i < requests; i++) {
        ar2.result().write(randomBuffer(50));
      }
    });
  });

  awaitLatch(latch);

  client.close();
  server.close(ar -> {
    assertTrue(ar.succeeded());
    vertx.runOnContext(v -> testComplete());
  });

  await();

  JsonObject metrics = metricsService.getMetricsSnapshot(server);
  assertNotNull(metrics);
  assertTrue(metrics.isEmpty());

  metrics = metricsService.getMetricsSnapshot(client);
  assertNotNull(metrics);
  assertTrue(metrics.isEmpty());

  cleanup(client);
  cleanup(server);
}
项目:vertx-dropwizard-metrics    文件:MetricsTest.java   
@Test
public void testMetricsCleanupedOnVertxClose() throws Exception {
  CountDownLatch latch1 = new CountDownLatch(1);
  HttpServer server = vertx.createHttpServer(new HttpServerOptions().setPort(8080));
  server.requestHandler(req -> {});
  server.listen(onSuccess(res -> {
    latch1.countDown();
  }));
  awaitLatch(latch1);
  HttpClient client = vertx.createHttpClient(new HttpClientOptions());
  CountDownLatch latch2 = new CountDownLatch(1);
  NetServer nServer = vertx.createNetServer(new NetServerOptions().setPort(1234));
  nServer.connectHandler(conn -> {});
  nServer.listen(res -> {
    latch2.countDown();
  });
  awaitLatch(latch2);
  NetClient nClient = vertx.createNetClient(new NetClientOptions());
  DatagramSocket sock = vertx.createDatagramSocket(new DatagramSocketOptions());
  EventBus eb = vertx.eventBus();
  assertFalse(metricsService.getMetricsSnapshot(vertx).isEmpty());
  assertFalse(metricsService.getMetricsSnapshot(server).isEmpty());
  assertFalse(metricsService.getMetricsSnapshot(client).isEmpty());
  assertFalse(metricsService.getMetricsSnapshot(nServer).isEmpty());
  assertFalse(metricsService.getMetricsSnapshot(nClient).isEmpty());
  assertFalse(metricsService.getMetricsSnapshot(sock).isEmpty());
  assertFalse(metricsService.getMetricsSnapshot(eb).isEmpty());
  vertx.close(res -> {
    assertTrue(metricsService.getMetricsSnapshot(vertx).isEmpty());
    assertTrue(metricsService.getMetricsSnapshot(server).isEmpty());
    assertTrue(metricsService.getMetricsSnapshot(client).isEmpty());
    assertTrue(metricsService.getMetricsSnapshot(nServer).isEmpty());
    assertTrue(metricsService.getMetricsSnapshot(nClient).isEmpty());
    assertTrue(metricsService.getMetricsSnapshot(sock).isEmpty());
    assertTrue(metricsService.getMetricsSnapshot(eb).isEmpty());
    testComplete();
  });
  await();
  vertx = null;
}
项目:nassh-relay    文件:ProxyHandler.java   
private Future<UUID> connectTcpEndpoint(final UUID sid, final String host, final int port, final String clienthost) {
    final Future<UUID> future = Future.future();
    final NetClient client = vertx.createNetClient(new NetClientOptions().setReconnectAttempts(10).setReconnectInterval(500));
    client.connect(port, host, asyncResult -> {
        if (asyncResult.succeeded()) {
            logger.info("Connected to ssh server: " + host + ":" + port + " (" + clienthost + ")");
            QueueFactory.createQueue(sid.toString());
            asyncResult.result().drainHandler(v -> asyncResult.result().resume());
            asyncResult.result().handler(buffer -> {
                try {
                    final TransferQueue queue = QueueFactory.getQueue(sid.toString());
                    if (!queue.isFull()) {
                        queue.add(buffer);
                    } else {
                        asyncResult.result().pause();
                    }
                } catch (NoSuchQueueException ex) {
                    logger.warn(ex, ex.fillInStackTrace());
                }
            });
            asyncResult.result().closeHandler(v -> {
                logger.info("ssh server connection closed " + host + ":" + port);
                QueueFactory.deleteQueue(sid.toString());
                sessions.remove(sid.toString());
            });
            final Session session = new Session();
            session.setHandler(asyncResult.result().writeHandlerID());
            sessions.put(sid.toString(), session);
            registerTimerOut(session, client);
            future.complete(sid);
        } else {
            future.fail(asyncResult.cause());
            logger.warn("Could not connect to ssh server: " + asyncResult.cause().getMessage(), asyncResult.cause());
        }
    });
    return future;
}
项目:vertx-spring    文件:VertxMetricsAdapter.java   
@Override
default TCPMetrics<?> createMetrics(NetClientOptions options) {
    return DummyVertxMetrics.DummyTCPMetrics.INSTANCE;
}
项目:vertx-spring    文件:DispatchingVertxMetrics.java   
@Override
public TCPMetrics<?> createMetrics(NetClientOptions options) {
    return this.<TCPMetrics<?>> createSubMetrics(v -> v.createMetrics(options),
            d -> new DispatchingTcpMetrics(d));
}
项目:vertx-spring    文件:VertxActuatorMetrics.java   
@Override
public TCPMetrics<?> createMetrics(NetClientOptions options) {
    return new NetClientMetricsImpl(counterService, gaugeService, properties.getNet().getClient());
}
项目:vertx-fastdfs-client    文件:FdfsConnectionPool.java   
public FdfsConnectionPool(Vertx vertx, NetClientOptions options, int poolSize) {
    this.client = vertx.createNetClient(options);
    this.poolSize = poolSize;

    this.pools = new ConcurrentHashMap<>();
}
项目:vertx-prometheus-metrics    文件:VertxPrometheusMetrics.java   
@Override
public @NotNull TCPMetrics<?> createMetrics(@NotNull NetClientOptions netClientOptions) {
  return options.isEnabled(NetClient)
      ? new NetClientPrometheusMetrics(options.getRegistry(), getLocalAddress(netClientOptions.getLocalAddress()))
      : super.createMetrics(netClientOptions);
}
项目:GDH    文件:GDHVertex.java   
private CompletableFuture<Boolean> sendMessage(Node n, JsonObject msg) {
    NetClientOptions options = new NetClientOptions();
    options.setSendBufferSize(Constants.BUFFER_SIZE);

    NetClient tcpClient = vertx.createNetClient(options);

    CompletableFuture<Boolean> future = new CompletableFuture<>();
    Long[] timingAndRetries = new Long[2];
    for (int t = 0; t < timingAndRetries.length; t++)
        timingAndRetries[t] = Long.valueOf("0");

    timingAndRetries[0] = vertx.setPeriodic(Constants.SEND_RETRY, ((Long myLong) -> {
        tcpClient.connect(Integer.parseInt(n.getPort()), n.getIP(), ((AsyncResult<NetSocket> result) -> {
            NetSocket socket = result.result();
            if (socket != null) {
                socket.handler((Buffer buffer) -> {
                    String reply = buffer.getString(0, buffer.length());
                    if (reply.equals(Constants.ACK)) {
                        conf.getLogger().debug(getNode().toString() + " Got an ack from " + n.toString());
                        future.complete(true);
                        vertx.cancelTimer(timingAndRetries[0]);
                        socket.close();
                        tcpClient.close();
                    }

                });
                conf.getLogger().debug(getNode().toString() + " " + Constants.LOG_OUT + " to: " + 
                n.toString() + " " + msg.toString());
                socket.write(msg.toString());
            }
            timingAndRetries[1]++;
            if (timingAndRetries[1] == conf.getRetries()) {
                // No more retries left. Exit...
                conf.getLogger().error(getNode().toString() + " Retry parameter exceeded " + conf.getRetries());
                future.completeExceptionally(
                        new TimeoutException(Constants.EXCEPTIONRETRIESEXCEEDED + conf.getRetries()));
                if (socket != null)
                    socket.close();
                vertx.cancelTimer(timingAndRetries[0]);
                tcpClient.close();
                server.close();
            }
        }));
    }));
    return future;
}
项目:sfs    文件:SfsVertxImpl.java   
@Override
public NetClient createNetClient(NetClientOptions options) {
    return vertx.createNetClient(options);
}
项目:lumber-mill    文件:VertxReconnectableSocket.java   
public VertxReconnectableSocket (URI uri) {
 this(uri, new NetClientOptions()
   .setConnectTimeout(1000)
   .setReconnectAttempts (5)
   .setReconnectInterval (1000));
}
项目:lumber-mill    文件:VertxReconnectableSocket.java   
public VertxReconnectableSocket (URI uri, NetClientOptions options) {
  client = vertx.createNetClient(options);
  this.uri = uri;
}
项目:vertx-amqp-service    文件:LinkManager.java   
@SuppressWarnings("serial")
public LinkManager(Vertx vertx, AmqpServiceConfig config, AMQPServiceImpl parent) {
  DEFAULT_OUTGOING_LINK_OPTIONS.setReliability(ReliabilityMode.AT_LEAST_ONCE);
  _vertx = vertx;
  _config = config;
  _listener = parent;
  _client = _vertx.createNetClient(new NetClientOptions());

  URL_CACHE = Collections.synchronizedMap(new LinkedHashMap<String, ConnectionSettings>(config
    .getMaxedCachedURLEntries() + 1, 1.1f, true) {
    @Override
    protected boolean removeEldestEntry(Map.Entry<String, ConnectionSettings> eldest) {
      return size() > config.getMaxedCachedURLEntries();
    }
  });

  NetServerOptions serverOp = new NetServerOptions();
  serverOp.setHost(config.getInboundHost());
  serverOp.setPort(config.getInboundPort());
  _server = _vertx.createNetServer(serverOp);
  _server.connectHandler(sock -> {
    DefaultConnectionSettings settings = new DefaultConnectionSettings();
    settings.setHost(sock.remoteAddress().host());
    settings.setPort(sock.remoteAddress().port());
    ManagedConnection connection = new ManagedConnection(settings, this, true);
    connection.setNetSocket(sock);
    connection.write();
    _inboundConnections.add(connection);
    connection.addDisconnectHandler(c -> {
      _inboundConnections.remove(c);
    });
  });

  _server.listen(result -> {
    if (result.failed()) {
      String error = format("Error {%s} Server was unable to bind to %s:%s", result.cause(),
        _config.getInboundHost(), _config.getInboundPort());
      LOG.fatal(error, result.cause());
      // We need to stop the verticle
      LOG.fatal("Initiating the shutdown of AMQP Service due to : %s", error);
      parent.stopInternal();
    }
  });
}
项目:vertx-hawkular-metrics    文件:VertxMetricsImpl.java   
@Override
public TCPMetrics createMetrics(NetClientOptions options) {
  NetClientMetricsSupplier supplier = (NetClientMetricsSupplier) metricSuppliers.get(NET_CLIENT);
  return supplier != null ? new NetClientMetricsImpl(supplier) : super.createMetrics(options);
}
项目:vertx-dropwizard-metrics    文件:MetricsTestBase.java   
protected NetClient createNetClient() {
  return createNetClient(new NetClientOptions());
}
项目:usher    文件:SocketPool.java   
private NetClientOptions buildOptions(JsonObject configObj) {
    return new NetClientOptions(configObj);
}