Java Code Examples for io.vertx.core.net.NetClient#connect()
The following examples show how to use
io.vertx.core.net.NetClient#connect() .
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: 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 2
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 3
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 4
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 5
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 6
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 7
Source File: ClientHandler.java From shadowsocks-vertx with Apache License 2.0 | 5 votes |
private void connectToRemote(String addr, int port, Buffer remoteHeader) { // 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; } mServerSocket = res.result(); setFinishHandler(mServerSocket); mServerSocket.handler(buffer -> { // remote socket data handler byte [] data = mEncryptTextBufferQ.appendBuffer(buffer).getBytes(); byte [][] decryptResult = mCrypto.decrypt(data); int lastState = mCrypto.getLastDecryptState(); if (lastState == DecryptState.FAILED) { destory(); } else if (lastState == DecryptState.NEED_MORE) { return; } byte [] decryptData = decryptResult[0]; byte [] encryptDataLeft = decryptResult[1]; cleanEncryptTextBufferQ(); if (encryptDataLeft != null) { mEncryptTextBufferQ.appendBytes(encryptDataLeft); } flowControl(mLocalSocket, mServerSocket); mLocalSocket.write(Buffer.buffer(decryptData)); }); // reply to program. byte [] msg = {0x05, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}; mLocalSocket.write(Buffer.buffer(msg)); // send remote header. byte [] header = remoteHeader.getBytes(); byte [] encryptHeader = mCrypto.encrypt(header); mServerSocket.write(Buffer.buffer(encryptHeader)); }); }
Example 8
Source File: TcpEventBusBridgeTest.java From vertx-tcp-eventbus-bridge with Apache License 2.0 | 5 votes |
@Test public void testErrorReply(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) -> { msg.fail(0, "oops!"); }); 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 9
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 10
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 11
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 12
Source File: DemoRamlRestTest.java From raml-module-builder with Apache License 2.0 | 5 votes |
private void testStreamTcpClient(TestContext context, int size) { Async async = context.async(); NetClient netClient = vertx.createNetClient(); netClient.connect(port, "localhost", con -> { context.assertTrue(con.succeeded()); if (con.failed()) { async.complete(); return; } NetSocket socket = con.result(); socket.write("POST /rmbtests/testStream HTTP/1.1\r\n"); socket.write("Host: localhost:" + Integer.toString(port) + "\r\n"); socket.write("Content-Type: application/octet-stream\r\n"); socket.write("Accept: application/json,text/plain\r\n"); socket.write("X-Okapi-Tenant: " + TENANT + "\r\n"); socket.write("Content-Length: " + Integer.toString(size) + "\r\n"); socket.write("\r\n"); socket.write("123\r\n"); // body is 5 bytes Buffer buf = Buffer.buffer(); socket.handler(buf::appendBuffer); vertx.setTimer(100, x -> { socket.end(); if (!async.isCompleted()) { async.complete(); } }); socket.endHandler(x -> { if (!async.isCompleted()) { async.complete(); } }); }); }
Example 13
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 14
Source File: ServerHandler.java From shadowsocks-vertx with Apache License 2.0 | 5 votes |
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 // Chunk max length = 0x3fff. int chunkMaxLen = 0x3fff; flowControl(mClientSocket, mTargetSocket); while (buffer.length() > 0) { int bufferLength = buffer.length(); int end = bufferLength > chunkMaxLen ? chunkMaxLen : bufferLength; sendToClient(buffer.slice(0, end)); buffer = buffer.slice(end, buffer.length()); } }); if (mPlainTextBufferQ.length() > 0) { handleStageStreaming(); } }); }
Example 15
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 16
Source File: TcpPortWaiting.java From okapi with Apache License 2.0 | 5 votes |
private void tryConnect(Process process, int count, Handler<AsyncResult<Void>> startFuture) { NetClientOptions options = new NetClientOptions().setConnectTimeout(MILLISECONDS); NetClient c = vertx.createNetClient(options); logger.info("tryConnect() host {} port {} count {}", host, port, count); c.connect(port, host, res -> { if (res.succeeded()) { logger.info("Connected to service at host {} port {} count {}", host, port, count); NetSocket socket = res.result(); socket.close(); if (process != null) { try { process.getErrorStream().close(); } catch (Exception e) { logger.error("Closing streams failed: {}", e.getMessage(), e); } } startFuture.handle(Future.succeededFuture()); } else if (process != null && !process.isAlive() && process.exitValue() != 0) { logger.warn("Service returned with exit code {}", process.exitValue()); startFuture.handle(Future.failedFuture(messages.getMessage("11500", process.exitValue()))); } else if (count < maxIterations) { vertx.setTimer((long) (count + 1) * MILLISECONDS, id -> tryConnect(process, count + 1, startFuture)); } else { startFuture.handle(Future.failedFuture(messages.getMessage("11501", Integer.toString(port), res.cause().getMessage()))); } }); }
Example 17
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 18
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 19
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 20
Source File: MqttServerBadClientTest.java From vertx-mqtt with Apache License 2.0 | 4 votes |
@Test public void unknownMessageType(TestContext context) { NetClient client = this.vertx.createNetClient(); Async async = context.async(); client.connect(MQTT_SERVER_PORT, MQTT_SERVER_HOST, done -> { if (done.succeeded()) { byte[] packet = new byte[] { (byte)0xF0, (byte)0x00}; done.result().write(Buffer.buffer(packet)); done.result().closeHandler(v -> { async.complete(); }); } else { context.fail(); } }); async.await(); }