io.vertx.core.net.NetClient Java Examples
The following examples show how to use
io.vertx.core.net.NetClient.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GraviteeApisProbe.java From gravitee-management-rest-api with Apache License 2.0 | 6 votes |
@Override public CompletableFuture<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 VertxCompletableFuture.from(vertx, future); }
Example #2
Source File: TcpEventBusBridgeTest.java From vertx-tcp-eventbus-bridge with Apache License 2.0 | 6 votes |
@Test public void testSendMessageWithReplyBacktrack(TestContext context) { // Send a request and get a response NetClient client = vertx.createNetClient(); final Async async = context.async(); client.connect(7000, "localhost", context.asyncAssertSuccess(socket -> { final FrameParser parser = new FrameParser(parse -> { context.assertTrue(parse.succeeded()); JsonObject frame = parse.result(); context.assertNotEquals("err", frame.getString("type")); context.assertEquals(true, frame.getBoolean("send")); context.assertEquals("Hello vert.x", frame.getJsonObject("body").getString("value")); client.close(); async.complete(); }); socket.handler(parser); FrameHelper.sendFrame("send", "hello", "#backtrack", new JsonObject().put("value", "vert.x"), socket); })); }
Example #3
Source File: TcpEventBusBridgeTest.java From vertx-tcp-eventbus-bridge with Apache License 2.0 | 6 votes |
@Test public void testSendsFromOtherSideOfBridge(TestContext context) { NetClient client = vertx.createNetClient(); final Async async = context.async(); client.connect(7000, "localhost", context.asyncAssertSuccess(socket -> { final FrameParser parser = new FrameParser(parse -> { context.assertTrue(parse.succeeded()); JsonObject frame = parse.result(); context.assertNotEquals("err", frame.getString("type")); context.assertEquals(true, frame.getBoolean("send")); context.assertEquals("hi", frame.getJsonObject("body").getString("value")); client.close(); async.complete(); }); socket.handler(parser); FrameHelper.sendFrame("register", "ping", null, socket); })); }
Example #4
Source File: TcpEventBusBridgeTest.java From vertx-tcp-eventbus-bridge with Apache License 2.0 | 6 votes |
@Test public void testNoHandlers(TestContext context) { // Send a request and get a response NetClient client = vertx.createNetClient(); final Async async = context.async(); client.connect(7000, "localhost", context.asyncAssertSuccess(socket -> { final FrameParser parser = new FrameParser(parse -> { context.assertTrue(parse.succeeded()); JsonObject frame = parse.result(); context.assertEquals("err", frame.getString("type")); context.assertEquals("#backtrack", frame.getString("address")); client.close(); async.complete(); }); socket.handler(parser); FrameHelper.sendFrame("send", "test", "#backtrack", new JsonObject().put("value", "vert.x"), socket); })); }
Example #5
Source File: TcpEventBusBridgeTest.java From vertx-tcp-eventbus-bridge with Apache License 2.0 | 6 votes |
@Test public void testSendMessageWithDuplicateReplyID(TestContext context) { // replies must always return to the same origin NetClient client = vertx.createNetClient(); final Async async = context.async(); client.connect(7000, "localhost", context.asyncAssertSuccess(socket -> { vertx.eventBus().consumer("third-party-receiver", msg -> context.fail()); final FrameParser parser = new FrameParser(parse -> { context.assertTrue(parse.succeeded()); client.close(); async.complete(); }); socket.handler(parser); FrameHelper.sendFrame("send", "hello", "third-party-receiver", new JsonObject().put("value", "vert.x"), socket); })); }
Example #6
Source File: TcpEventBusBridgeInteropTest.java From vertx-tcp-eventbus-bridge with Apache License 2.0 | 6 votes |
@Test public void testSendMessageWithDuplicateReplyID(TestContext context) { // replies must always return to the same origin NetClient client = vertx.createNetClient(); final Async async = context.async(); client.connect(7000, "localhost", conn -> { context.assertFalse(conn.failed()); NetSocket socket = conn.result(); vertx.eventBus().consumer("third-party-receiver", msg -> context.fail()); final FrameParser parser = new FrameParser(parse -> { context.assertTrue(parse.succeeded()); client.close(); async.complete(); }); socket.handler(parser); FrameHelper.sendFrame("send", "hello", "third-party-receiver", new JsonObject().put("value", "vert.x"), socket); }); }
Example #7
Source File: TcpEventBusBridgeInteropTest.java From vertx-tcp-eventbus-bridge with Apache License 2.0 | 6 votes |
@Test public void testSendMessageWithReplyBacktrack(TestContext context) { // Send a request and get a response NetClient client = vertx.createNetClient(); final Async async = context.async(); client.connect(7000, "localhost", conn -> { context.assertFalse(conn.failed()); NetSocket socket = conn.result(); final FrameParser parser = new FrameParser(parse -> { context.assertTrue(parse.succeeded()); JsonObject frame = parse.result(); context.assertNotEquals("err", frame.getString("type")); context.assertEquals("Hello vert.x", frame.getJsonObject("body").getString("value")); client.close(); async.complete(); }); socket.handler(parser); FrameHelper.sendFrame("send", "hello", "#backtrack", new JsonObject().put("value", "vert.x"), socket); }); }
Example #8
Source File: TcpEventBusBridgeTest.java From vertx-tcp-eventbus-bridge with Apache License 2.0 | 6 votes |
@Test public void testSendPing(TestContext context) { NetClient client = vertx.createNetClient(); final Async async = context.async(); // MESSAGE for ping final FrameParser parser = new FrameParser(parse -> { context.assertTrue(parse.succeeded()); JsonObject frame = parse.result(); context.assertEquals("pong", frame.getString("type")); client.close(); async.complete(); }); client.connect(7000, "localhost", context.asyncAssertSuccess(socket -> { socket.handler(parser); FrameHelper.sendFrame("register", "echo", null, socket); FrameHelper.sendFrame("ping", socket); })); }
Example #9
Source File: TcpEventBusBridgeTest.java From vertx-tcp-eventbus-bridge with Apache License 2.0 | 6 votes |
@Test public void testNoAddress(TestContext context) { NetClient client = vertx.createNetClient(); final Async async = context.async(); final AtomicBoolean errorOnce = new AtomicBoolean(false); final FrameParser parser = new FrameParser(parse -> { context.assertTrue(parse.succeeded()); JsonObject frame = parse.result(); if (!errorOnce.compareAndSet(false, true)) { context.fail("Client gets error message twice!"); } else { context.assertEquals("err", frame.getString("type")); context.assertEquals("missing_address", frame.getString("message")); vertx.setTimer(200, l -> { client.close(); async.complete(); }); } }); client.connect(7000, "localhost", context.asyncAssertSuccess(socket -> { socket.handler(parser); FrameHelper.sendFrame("send", socket); })); }
Example #10
Source File: MqttServerConnectionTest.java From vertx-mqtt with Apache License 2.0 | 6 votes |
@Test public void noConnectSent(TestContext context) { NetClient client = this.vertx.createNetClient(); Async async = context.async(); client.connect(MQTT_SERVER_PORT, MQTT_SERVER_HOST, done -> { if (done.succeeded()) { done.result().closeHandler(v -> { log.info("No CONNECT sent in " + MQTT_TIMEOUT_ON_CONNECT + " secs. Closing connection."); async.complete(); }); } else { context.fail(); } }); // check that the async is completed (so connection was closed by server) in // the specified timeout (+500 ms just for being sure) async.await(500 + MQTT_TIMEOUT_ON_CONNECT * 1000); if (!async.isCompleted()) context.fail(); }
Example #11
Source File: HttpServerProbe.java From gravitee-gateway with Apache License 2.0 | 6 votes |
@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; }
Example #12
Source File: SMTPConnection.java From vertx-mail-client with Apache License 2.0 | 6 votes |
SMTPConnection(NetClient client, ConnectionLifeCycleListener listener) { broken = true; idle = false; doShutdown = false; socketClosed = false; socketShutDown = false; this.client = client; this.listener = listener; this.nsHandler = new MultilineParser(buffer -> { if (commandReplyHandler == null) { log.debug("dropping reply arriving after we stopped processing the buffer."); } else { // make sure we only call the handler once Handler<String> currentHandler = commandReplyHandler; commandReplyHandler = null; currentHandler.handle(buffer.toString()); } }); }
Example #13
Source File: ProtonTransport.java From vertx-proton with Apache License 2.0 | 6 votes |
ProtonTransport(Connection connection, Vertx vertx, NetClient netClient, NetSocket socket, ProtonSaslAuthenticator authenticator, ProtonTransportOptions options) { this.connection = connection; this.vertx = vertx; this.netClient = netClient; this.socket = socket; int maxFrameSize = options.getMaxFrameSize() == 0 ? DEFAULT_MAX_FRAME_SIZE : options.getMaxFrameSize(); transport.setMaxFrameSize(maxFrameSize); transport.setOutboundFrameSizeLimit(maxFrameSize); transport.setEmitFlowEventOnSend(false); // TODO: make configurable transport.setIdleTimeout(2 * options.getHeartbeat()); ((TransportInternal) transport).setUseReadOnlyOutputBuffer(false); if (authenticator != null) { authenticator.init(this.socket, (ProtonConnection) this.connection.getContext(), transport); } this.authenticator = authenticator; transport.bind(connection); connection.collect(collector); socket.endHandler(this::handleSocketEnd); socket.handler(this::handleSocketBuffer); }
Example #14
Source File: ProcessModuleHandle.java From okapi with Apache License 2.0 | 6 votes |
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( messages.getMessage("11503", Integer.toString(port)))); } } else { stopFuture.handle(Future.succeededFuture()); } }); } else { stopFuture.handle(Future.succeededFuture()); } }
Example #15
Source File: ProcessModuleHandle.java From okapi with Apache License 2.0 | 6 votes |
@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( messages.getMessage("11502", Integer.toString(port)))); } else { start2(startFuture); } }); } else { start2(startFuture); } }
Example #16
Source File: VertxNetClientServerMetricsTest.java From vertx-micrometer-metrics with Apache License 2.0 | 6 votes |
private void request(NetClient client, TestContext ctx) { for (int i = 0; i < SENT_COUNT; i++) { Async async = ctx.async(); client.connect(9194, "localhost", res -> { if (res.failed()) { async.complete(); ctx.fail(res.cause()); return; } NetSocket socket = res.result().exceptionHandler(t -> { async.complete(); ctx.fail(t); }); socket.handler(buf -> socket.close()); socket.write(CLIENT_REQUEST); socket.closeHandler(v -> async.complete()); }); async.await(); } }
Example #17
Source File: ProxyHandler.java From nassh-relay with GNU General Public License v2.0 | 6 votes |
private void registerTimerOut(final Session session, final NetClient client) { vertx.setPeriodic(config.getJsonObject("application").getInteger("tcp-session-timeout", 1200) * 1000, new Handler<Long>() { private int readCount = 0; private int writeCount = 0; @Override public void handle(Long timerID) { if ((session.getRead_count() <= readCount) && (session.getWrite_count() <= writeCount)) { session.setActive(false); if (client != null) { client.close(); } vertx.cancelTimer(timerID); } readCount = session.getRead_count(); writeCount = session.getWrite_count(); } }); }
Example #18
Source File: StompClientExamples.java From vertx-stomp with Apache License 2.0 | 5 votes |
public void example7(Vertx vertx, NetClient netClient) { StompClient.create(vertx) .connect(netClient) .onSuccess(connection -> { // use the connection connection .errorHandler(frame -> System.out.println("ERROR frame received : " + frame)); }) .onFailure(err -> System.out.println( "Failed to connect to the STOMP server: " + err.toString())); }
Example #19
Source File: TcpEventBusBridgeTest.java From vertx-tcp-eventbus-bridge with Apache License 2.0 | 5 votes |
@Test public void testRegister(TestContext context) { // Send a request and get a response NetClient client = vertx.createNetClient(); final Async async = context.async(); client.connect(7000, "localhost", context.asyncAssertSuccess(socket -> { // 1 reply will arrive // MESSAGE for echo final FrameParser parser = new FrameParser(parse -> { context.assertTrue(parse.succeeded()); JsonObject frame = parse.result(); context.assertNotEquals("err", frame.getString("type")); context.assertEquals(false, frame.getBoolean("send")); context.assertEquals("Vert.x", frame.getJsonObject("body").getString("value")); client.close(); async.complete(); }); socket.handler(parser); FrameHelper.sendFrame("register", "echo", null, socket); // now try to publish a message so it gets delivered both to the consumer registred on the startup and to this // remote consumer FrameHelper.sendFrame("publish", "echo", new JsonObject().put("value", "Vert.x"), socket); })); }
Example #20
Source File: TcpEventBusBridgeTest.java From vertx-tcp-eventbus-bridge with Apache License 2.0 | 5 votes |
@Test public void testFailFromClient(TestContext context) { // Send a request from java and get a response from the client NetClient client = vertx.createNetClient(); final Async async = context.async(); final String address = "test"; client.connect(7000, "localhost", context.asyncAssertSuccess(socket -> { final FrameParser parser = new FrameParser(parse -> { context.assertTrue(parse.succeeded()); JsonObject frame = parse.result(); if ("message".equals(frame.getString("type"))) { context.assertEquals(true, frame.getBoolean("send")); context.assertEquals("Vert.x", frame.getJsonObject("body").getString("value")); FrameHelper.writeFrame(new JsonObject().put("type","send").put("address",frame.getString("replyAddress")).put("failureCode", 1234).put("message", "ooops!"), socket); } }); socket.handler(parser); FrameHelper.sendFrame("register", address, null, socket); // There is now way to know that the register actually happened, wait a bit before sending. vertx.setTimer( 500L, timerId -> { vertx.eventBus().request(address, new JsonObject().put("value", "Vert.x"), respMessage -> { context.assertTrue(respMessage.failed()); context.assertEquals("ooops!", respMessage.cause().getMessage()); client.close(); async.complete(); }); }); })); }
Example #21
Source File: TcpEventBusBridgeTest.java From vertx-tcp-eventbus-bridge with Apache License 2.0 | 5 votes |
@Test public void testReplyFromClient(TestContext context) { // Send a request from java and get a response from the client NetClient client = vertx.createNetClient(); final Async async = context.async(); final String address = "test"; client.connect(7000, "localhost", context.asyncAssertSuccess(socket -> { final FrameParser parser = new FrameParser(parse -> { context.assertTrue(parse.succeeded()); JsonObject frame = parse.result(); if ("message".equals(frame.getString("type"))) { context.assertEquals(true, frame.getBoolean("send")); context.assertEquals("Vert.x", frame.getJsonObject("body").getString("value")); FrameHelper.sendFrame("send", frame.getString("replyAddress"), new JsonObject().put("value", "You got it"), socket); } }); socket.handler(parser); FrameHelper.sendFrame("register", address, null, socket); // There is now way to know that the register actually happened, wait a bit before sending. vertx.setTimer( 500L, timerId -> { vertx.eventBus().<JsonObject>request(address, new JsonObject().put("value", "Vert.x"), respMessage -> { context.assertTrue(respMessage.succeeded()); context.assertEquals("You got it", respMessage.result().body().getString("value")); client.close(); async.complete(); }); }); })); }
Example #22
Source File: ProtonClientImpl.java From vertx-proton with Apache License 2.0 | 5 votes |
private void connectNetClient(NetClient netClient, String host, int port, String username, String password, ConnectCompletionHandler connectHandler, ProtonClientOptions options) { String serverName = options.getSniServerName() != null ? options.getSniServerName() : (options.getVirtualHost() != null ? options.getVirtualHost() : null); netClient.connect(port, host, serverName, res -> { if (res.succeeded()) { String virtualHost = options.getVirtualHost() != null ? options.getVirtualHost() : host; ProtonConnectionImpl conn = new ProtonConnectionImpl(vertx, virtualHost, (ContextInternal) Vertx.currentContext()); conn.disconnectHandler(h -> { LOG.trace("Connection disconnected"); if(!connectHandler.isComplete()) { connectHandler.handle(Future.failedFuture(new VertxException("Disconnected"))); } }); ProtonSaslClientAuthenticatorImpl authenticator = new ProtonSaslClientAuthenticatorImpl(username, password, options.getEnabledSaslMechanisms(), connectHandler); ProtonTransportOptions transportOptions = new ProtonTransportOptions(); transportOptions.setHeartbeat(options.getHeartbeat()); transportOptions.setMaxFrameSize(options.getMaxFrameSize()); conn.bindClient(netClient, res.result(), authenticator, transportOptions); // Need to flush here to get the SASL process going, or it will wait until calls on the connection are processed // later (e.g open()). conn.flush(); } else { connectHandler.handle(Future.failedFuture(res.cause())); } }); }
Example #23
Source File: VertxTcpClientProvider.java From jetlinks-community with Apache License 2.0 | 5 votes |
public void initClient(VertxTcpClient client, TcpClientProperties properties) { NetClient netClient = vertx.createNetClient(properties.getOptions()); client.setClient(netClient); client.setKeepAliveTimeoutMs(properties.getLong("keepAliveTimeout").orElse(Duration.ofMinutes(10).toMillis())); netClient.connect(properties.getPort(), properties.getHost(), result -> { if (result.succeeded()) { log.debug("connect tcp [{}:{}] success", properties.getHost(), properties.getPort()); client.setRecordParser(payloadParserBuilder.build(properties.getParserType(), properties)); client.setSocket(result.result()); } else { log.error("connect tcp [{}:{}] error", properties.getHost(), properties.getPort(),result.cause()); } }); }
Example #24
Source File: MetricsTestBase.java From vertx-dropwizard-metrics with Apache License 2.0 | 5 votes |
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; }
Example #25
Source File: TcpEventBusBridgeTest.java From vertx-tcp-eventbus-bridge with Apache License 2.0 | 5 votes |
@Test public void testSendMessageWithReplyBacktrackTimeout(TestContext context) { // Send a request and get a response NetClient client = vertx.createNetClient(); final Async async = context.async(); // This does not reply and will provoke a timeout vertx.eventBus().consumer("test", (Message<JsonObject> msg) -> { /* Nothing! */ } ); client.connect(7000, "localhost", context.asyncAssertSuccess(socket -> { final FrameParser parser = new FrameParser(parse -> { context.assertTrue(parse.succeeded()); JsonObject frame = parse.result(); context.assertEquals("err", frame.getString("type")); context.assertEquals("TIMEOUT", frame.getString("failureType")); context.assertEquals(-1, frame.getInteger("failureCode")); context.assertEquals("#backtrack", frame.getString("address")); client.close(); async.complete(); }); socket.handler(parser); JsonObject headers = new JsonObject().put("timeout", 100L); FrameHelper.sendFrame("send", "test", "#backtrack", headers, null, new JsonObject().put("value", "vert.x"), socket); })); }
Example #26
Source File: ProxyHandler.java From nassh-relay with GNU General Public License v2.0 | 5 votes |
private Promise<UUID> connectTcpEndpoint(final UUID sid, final String host, final int port, final String clienthost) { final Promise<UUID> promise = Promise.promise(); 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); promise.complete(sid); } else { promise.fail(asyncResult.cause()); logger.warn("Could not connect to ssh server: " + asyncResult.cause().getMessage(), asyncResult.cause()); } }); return promise; }
Example #27
Source File: TcpEventBusBridgeTest.java From vertx-tcp-eventbus-bridge with Apache License 2.0 | 5 votes |
@Test public void testSendVoidMessage(TestContext context) { // Send a request and get a response NetClient client = vertx.createNetClient(); final Async async = context.async(); vertx.eventBus().consumer("test", (Message<JsonObject> msg) -> { client.close(); async.complete(); }); client.connect(7000, "localhost", context.asyncAssertSuccess(socket -> { FrameHelper.sendFrame("send", "test", new JsonObject().put("value", "vert.x"), socket); })); }
Example #28
Source File: VertxTcpClient.java From jetlinks-community with Apache License 2.0 | 5 votes |
public void setClient(NetClient client) { if (this.client != null && this.client != client) { this.client.close(); } keepAlive(); this.client = client; }
Example #29
Source File: SocketClient.java From enode with MIT License | 5 votes |
public static void main(String[] args) throws Exception { NetClient client = Vertx.vertx().createNetClient(); String host = "127.0.0.1"; long start = System.currentTimeMillis(); int total = 1000000; CompletableFuture<NetSocket> future = new CompletableFuture<>(); if (smap.putIfAbsent(host, future) == null) { client.connect(6008, host, socketAsyncResult -> { if (socketAsyncResult.succeeded()) { NetSocket socket = socketAsyncResult.result(); socket.closeHandler(x -> { smap.remove(host); }).endHandler(x -> { smap.remove(host); logger.info("end:{}", x); }); future.complete(socket); } }); } smap.get(host).thenAccept(socket -> { for (int i = 0; i < total; i++) { socket.write("send message:" + i + SysProperties.DELIMITED); } }); long end = System.currentTimeMillis(); logger.info("time:{}", end - start); System.in.read(); }
Example #30
Source File: VertxNetClientServerMetricsTest.java From vertx-micrometer-metrics with Apache License 2.0 | 5 votes |
private void runClientRequests(TestContext ctx) { Async clientsFinished = ctx.async(concurrentClients); for (int i = 0; i < concurrentClients; i++) { ForkJoinPool.commonPool().execute(() -> { NetClient client = vertx.createNetClient(); request(client, ctx); clientsFinished.countDown(); }); } clientsFinished.awaitSuccess(); }