Search in sources :

Example 31 with NetClient

use of io.vertx.core.net.NetClient in project vert.x by eclipse.

the class SocksProxy method start.

/**
   * Start the server.
   * 
   * @param vertx
   *          Vertx instance to use for creating the server and client
   * @param finishedHandler
   *          will be called when the start has started
   */
@Override
public void start(Vertx vertx, Handler<Void> finishedHandler) {
    NetServerOptions options = new NetServerOptions();
    options.setHost("localhost").setPort(PORT);
    server = vertx.createNetServer(options);
    server.connectHandler(socket -> {
        socket.handler(buffer -> {
            Buffer expectedInit = username == null ? clientInit : clientInitAuth;
            if (!buffer.equals(expectedInit)) {
                throw new IllegalStateException("expected " + toHex(expectedInit) + ", got " + toHex(buffer));
            }
            boolean useAuth = buffer.equals(clientInitAuth);
            log.debug("got request: " + toHex(buffer));
            final Handler<Buffer> handler = buffer2 -> {
                if (!buffer2.getBuffer(0, clientRequest.length()).equals(clientRequest)) {
                    throw new IllegalStateException("expected " + toHex(clientRequest) + ", got " + toHex(buffer2));
                }
                int stringLen = buffer2.getUnsignedByte(4);
                log.debug("string len " + stringLen);
                if (buffer2.length() != 7 + stringLen) {
                    throw new IllegalStateException("format error in client request, got " + toHex(buffer2));
                }
                String host = buffer2.getString(5, 5 + stringLen);
                int port = buffer2.getUnsignedShort(5 + stringLen);
                log.debug("got request: " + toHex(buffer2));
                log.debug("connect: " + host + ":" + port);
                socket.handler(null);
                lastUri = host + ":" + port;
                if (forceUri != null) {
                    host = forceUri.substring(0, forceUri.indexOf(':'));
                    port = Integer.valueOf(forceUri.substring(forceUri.indexOf(':') + 1));
                }
                log.debug("connecting to " + host + ":" + port);
                NetClient netClient = vertx.createNetClient(new NetClientOptions());
                netClient.connect(port, host, result -> {
                    if (result.succeeded()) {
                        log.debug("writing: " + toHex(connectResponse));
                        socket.write(connectResponse);
                        log.debug("connected, starting pump");
                        NetSocket clientSocket = result.result();
                        socket.closeHandler(v -> clientSocket.close());
                        clientSocket.closeHandler(v -> socket.close());
                        Pump.pump(socket, clientSocket).start();
                        Pump.pump(clientSocket, socket).start();
                    } else {
                        log.error("exception", result.cause());
                        socket.handler(null);
                        log.debug("writing: " + toHex(errorResponse));
                        socket.write(errorResponse);
                        socket.close();
                    }
                });
            };
            if (useAuth) {
                socket.handler(buffer3 -> {
                    log.debug("auth handler");
                    log.debug("got request: " + toHex(buffer3));
                    Buffer authReply = Buffer.buffer(new byte[] { 1, (byte) username.length() });
                    authReply.appendString(username);
                    authReply.appendByte((byte) username.length());
                    authReply.appendString(username);
                    if (!buffer3.equals(authReply)) {
                        log.debug("expected " + toHex(authReply) + ", got " + toHex(buffer3));
                        socket.handler(null);
                        log.debug("writing: " + toHex(authFailed));
                        socket.write(authFailed);
                        socket.close();
                    } else {
                        socket.handler(handler);
                        log.debug("writing: " + toHex(authSuccess));
                        socket.write(authSuccess);
                    }
                });
                log.debug("writing: " + toHex(serverReplyAuth));
                socket.write(serverReplyAuth);
            } else {
                socket.handler(handler);
                log.debug("writing: " + toHex(serverReply));
                socket.write(serverReply);
            }
        });
    });
    server.listen(result -> {
        log.debug("socks5 server started");
        finishedHandler.handle(null);
    });
}
Also used : Buffer(io.vertx.core.buffer.Buffer) NetServerOptions(io.vertx.core.net.NetServerOptions) Buffer(io.vertx.core.buffer.Buffer) NetServer(io.vertx.core.net.NetServer) Vertx(io.vertx.core.Vertx) Pump(io.vertx.core.streams.Pump) Handler(io.vertx.core.Handler) Logger(io.vertx.core.logging.Logger) NetClient(io.vertx.core.net.NetClient) LoggerFactory(io.vertx.core.logging.LoggerFactory) NetClientOptions(io.vertx.core.net.NetClientOptions) NetSocket(io.vertx.core.net.NetSocket) NetSocket(io.vertx.core.net.NetSocket) NetClientOptions(io.vertx.core.net.NetClientOptions) NetClient(io.vertx.core.net.NetClient) NetServerOptions(io.vertx.core.net.NetServerOptions)

Example 32 with NetClient

use of io.vertx.core.net.NetClient in project vert.x by eclipse.

the class HostnameResolutionTest method testResolveMissingLocalhost.

@Test
public void testResolveMissingLocalhost() throws Exception {
    InetAddress localhost = InetAddress.getByName("localhost");
    // Set a dns resolver that won't resolve localhost
    dnsServer.stop();
    dnsServer = FakeDNSServer.testResolveASameServer("127.0.0.1");
    dnsServer.start();
    dnsServerAddress = (InetSocketAddress) dnsServer.getTransports()[0].getAcceptor().getLocalAddress();
    // Test using the resolver API
    VertxInternal vertx = (VertxInternal) vertx(new VertxOptions().setAddressResolverOptions(new AddressResolverOptions().addServer(dnsServerAddress.getAddress().getHostAddress() + ":" + dnsServerAddress.getPort()).setOptResourceEnabled(false)));
    CompletableFuture<Void> test1 = new CompletableFuture<>();
    vertx.resolveAddress("localhost", ar -> {
        if (ar.succeeded()) {
            InetAddress resolved = ar.result();
            if (resolved.equals(localhost)) {
                test1.complete(null);
            } else {
                test1.completeExceptionally(new AssertionError("Unexpected localhost value " + resolved));
            }
        } else {
            test1.completeExceptionally(ar.cause());
        }
    });
    test1.get(10, TimeUnit.SECONDS);
    CompletableFuture<Void> test2 = new CompletableFuture<>();
    vertx.resolveAddress("LOCALHOST", ar -> {
        if (ar.succeeded()) {
            InetAddress resolved = ar.result();
            if (resolved.equals(localhost)) {
                test2.complete(null);
            } else {
                test2.completeExceptionally(new AssertionError("Unexpected localhost value " + resolved));
            }
        } else {
            test2.completeExceptionally(ar.cause());
        }
    });
    test2.get(10, TimeUnit.SECONDS);
    // Test using bootstrap
    CompletableFuture<Void> test3 = new CompletableFuture<>();
    NetServer server = vertx.createNetServer(new NetServerOptions().setPort(1234).setHost(localhost.getHostAddress()));
    server.connectHandler(so -> {
        so.write("hello").end();
    });
    server.listen(ar -> {
        if (ar.succeeded()) {
            test3.complete(null);
        } else {
            test3.completeExceptionally(ar.cause());
        }
    });
    test3.get(10, TimeUnit.SECONDS);
    CompletableFuture<Void> test4 = new CompletableFuture<>();
    NetClient client = vertx.createNetClient();
    client.connect(1234, "localhost", ar -> {
        if (ar.succeeded()) {
            test4.complete(null);
        } else {
            test4.completeExceptionally(ar.cause());
        }
    });
    test4.get(10, TimeUnit.SECONDS);
}
Also used : AddressResolverOptions(io.vertx.core.dns.AddressResolverOptions) CompletableFuture(java.util.concurrent.CompletableFuture) VertxInternal(io.vertx.core.impl.VertxInternal) NetClient(io.vertx.core.net.NetClient) NetServerOptions(io.vertx.core.net.NetServerOptions) NetServer(io.vertx.core.net.NetServer) InetAddress(java.net.InetAddress) VertxOptions(io.vertx.core.VertxOptions) Test(org.junit.Test)

Example 33 with NetClient

use of io.vertx.core.net.NetClient in project vertx-micrometer-metrics by vert-x3.

the class VertxNetClientServerMetricsTest method runClientRequests.

private void runClientRequests(TestContext ctx) {
    Async clientsFinished = ctx.async(concurrentClients);
    for (int i = 0; i < concurrentClients; i++) {
        ForkJoinPool.commonPool().execute(() -> {
            NetClient client = vertx.createNetClient();
            createdClients.add(client);
            request(client, ctx);
            clientsFinished.countDown();
        });
    }
    clientsFinished.awaitSuccess();
}
Also used : NetClient(io.vertx.core.net.NetClient) Async(io.vertx.ext.unit.Async)

Example 34 with NetClient

use of io.vertx.core.net.NetClient in project okapi by folio-org.

the class ProcessModuleHandle method start.

@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);
    }
}
Also used : NetSocket(io.vertx.core.net.NetSocket) NetClientOptions(io.vertx.core.net.NetClientOptions) NetClient(io.vertx.core.net.NetClient)

Example 35 with NetClient

use of io.vertx.core.net.NetClient in project vert.x by eclipse.

the class HttpMetricsTestBase method testHttpMetricsLifecycle.

@Test
public void testHttpMetricsLifecycle() throws Exception {
    int numBuffers = 10;
    int chunkSize = 1000;
    int contentLength = numBuffers * chunkSize;
    AtomicReference<HttpServerMetric> serverMetric = new AtomicReference<>();
    server.requestHandler(req -> {
        assertEquals(protocol, req.version());
        FakeHttpServerMetrics serverMetrics = FakeMetricsBase.getMetrics(server);
        assertNotNull(serverMetrics);
        HttpServerMetric metric = serverMetrics.getRequestMetric(req);
        serverMetric.set(metric);
        assertSame(((HttpServerRequestInternal) req).metric(), metric);
        assertNotNull(serverMetric.get());
        assertNotNull(serverMetric.get().socket);
        assertNull(serverMetric.get().response.get());
        assertTrue(serverMetric.get().socket.connected.get());
        assertNull(serverMetric.get().route.get());
        req.routed("/route/:param");
        assertEquals("/route/:param", serverMetric.get().route.get());
        req.bodyHandler(buff -> {
            assertEquals(contentLength, buff.length());
            assertTrue(serverMetric.get().requestEnded.get());
            assertEquals(contentLength, serverMetric.get().bytesRead.get());
            HttpServerResponse resp = req.response().setChunked(true);
            AtomicInteger numBuffer = new AtomicInteger(numBuffers);
            vertx.setPeriodic(1, timerID -> {
                Buffer chunk = TestUtils.randomBuffer(chunkSize);
                if (numBuffer.decrementAndGet() == 0) {
                    resp.end(chunk);
                    assertTrue(serverMetric.get().responseEnded.get());
                    assertEquals(contentLength, serverMetric.get().bytesWritten.get());
                    assertNull(serverMetrics.getRequestMetric(req));
                    vertx.cancelTimer(timerID);
                } else {
                    resp.write(chunk);
                    assertSame(serverMetric.get().response.get(), resp);
                }
            });
        });
    });
    startServer();
    CountDownLatch latch = new CountDownLatch(1);
    AtomicReference<HttpClientMetric> clientMetric = new AtomicReference<>();
    AtomicReference<SocketMetric> clientSocketMetric = new AtomicReference<>();
    FakeHttpClientMetrics metrics = FakeMetricsBase.getMetrics(client);
    NetClient netClient = ((HttpClientImpl) client).netClient();
    FakeTCPMetrics tcpMetrics = FakeMetricsBase.getMetrics(netClient);
    assertSame(metrics, tcpMetrics);
    Context ctx = vertx.getOrCreateContext();
    ctx.runOnContext(v -> {
        assertEquals(Collections.emptySet(), metrics.endpoints());
        client.request(new RequestOptions().setPort(DEFAULT_HTTP_PORT).setHost(DEFAULT_HTTP_HOST).setURI(TestUtils.randomAlphaString(16))).onComplete(onSuccess(req -> {
            req.response(onSuccess(resp -> {
                clientSocketMetric.set(metrics.firstMetric(SocketAddress.inetSocketAddress(8080, "localhost")));
                assertNotNull(clientSocketMetric.get());
                assertEquals(Collections.singleton("localhost:8080"), metrics.endpoints());
                clientMetric.set(metrics.getMetric(resp.request()));
                assertNotNull(clientMetric.get());
                assertEquals(contentLength, clientMetric.get().bytesWritten.get());
                // assertNotNull(clientMetric.get().socket);
                // assertTrue(clientMetric.get().socket.connected.get());
                assertEquals((Integer) 1, metrics.connectionCount("localhost:8080"));
                assertEquals((Integer) 1, metrics.connectionCount(SocketAddress.inetSocketAddress(8080, "localhost")));
                resp.bodyHandler(buff -> {
                    assertEquals(contentLength, clientMetric.get().bytesRead.get());
                    assertNull(metrics.getMetric(resp.request()));
                    assertEquals(contentLength, buff.length());
                    latch.countDown();
                });
            })).exceptionHandler(this::fail).setChunked(true);
            assertNull(metrics.getMetric(req));
            for (int i = 0; i < numBuffers; i++) {
                req.write(TestUtils.randomBuffer(chunkSize));
            }
            req.end();
        }));
    });
    awaitLatch(latch);
    client.close();
    AsyncTestBase.assertWaitUntil(() -> metrics.endpoints().isEmpty());
    assertEquals(null, metrics.connectionCount("localhost:8080"));
    AsyncTestBase.assertWaitUntil(() -> !serverMetric.get().socket.connected.get());
    AsyncTestBase.assertWaitUntil(() -> contentLength == serverMetric.get().socket.bytesRead.get());
    AsyncTestBase.assertWaitUntil(() -> contentLength == serverMetric.get().socket.bytesWritten.get());
    AsyncTestBase.assertWaitUntil(() -> !clientSocketMetric.get().connected.get());
    assertEquals(contentLength, clientSocketMetric.get().bytesRead.get());
    assertEquals(contentLength, clientSocketMetric.get().bytesWritten.get());
    for (Iterator<Long> it : Arrays.asList(clientSocketMetric.get().bytesReadEvents.iterator(), serverMetric.get().socket.bytesWrittenEvents.iterator())) {
        while (it.hasNext()) {
            long val = it.next();
            if (it.hasNext()) {
                assertEquals(4096, val);
            } else {
                assertTrue(val < 4096);
            }
        }
    }
}
Also used : Buffer(io.vertx.core.buffer.Buffer) Context(io.vertx.core.Context) Arrays(java.util.Arrays) HttpClientImpl(io.vertx.core.http.impl.HttpClientImpl) FakeMetricsBase(io.vertx.test.fakemetrics.FakeMetricsBase) HttpServerMetric(io.vertx.test.fakemetrics.HttpServerMetric) CompletableFuture(java.util.concurrent.CompletableFuture) Context(io.vertx.core.Context) AtomicReference(java.util.concurrent.atomic.AtomicReference) FakeHttpServerMetrics(io.vertx.test.fakemetrics.FakeHttpServerMetrics) TestUtils(io.vertx.test.core.TestUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) FakeTCPMetrics(io.vertx.test.fakemetrics.FakeTCPMetrics) HttpClientMetric(io.vertx.test.fakemetrics.HttpClientMetric) NetClient(io.vertx.core.net.NetClient) SocketAddress(io.vertx.core.net.SocketAddress) Iterator(java.util.Iterator) FakeMetricsFactory(io.vertx.test.fakemetrics.FakeMetricsFactory) VertxOptions(io.vertx.core.VertxOptions) Test(org.junit.Test) Future(io.vertx.core.Future) SocketMetric(io.vertx.test.fakemetrics.SocketMetric) HttpServerRequestInternal(io.vertx.core.http.impl.HttpServerRequestInternal) CountDownLatch(java.util.concurrent.CountDownLatch) Buffer(io.vertx.core.buffer.Buffer) MetricsOptions(io.vertx.core.metrics.MetricsOptions) AsyncTestBase(io.vertx.test.core.AsyncTestBase) Collections(java.util.Collections) FakeHttpClientMetrics(io.vertx.test.fakemetrics.FakeHttpClientMetrics) FakeTCPMetrics(io.vertx.test.fakemetrics.FakeTCPMetrics) HttpServerMetric(io.vertx.test.fakemetrics.HttpServerMetric) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) NetClient(io.vertx.core.net.NetClient) FakeHttpServerMetrics(io.vertx.test.fakemetrics.FakeHttpServerMetrics) SocketMetric(io.vertx.test.fakemetrics.SocketMetric) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) FakeHttpClientMetrics(io.vertx.test.fakemetrics.FakeHttpClientMetrics) HttpClientImpl(io.vertx.core.http.impl.HttpClientImpl) HttpClientMetric(io.vertx.test.fakemetrics.HttpClientMetric) Test(org.junit.Test)

Aggregations

NetClient (io.vertx.core.net.NetClient)52 NetSocket (io.vertx.core.net.NetSocket)35 Test (org.junit.Test)34 NetServerOptions (io.vertx.core.net.NetServerOptions)24 Vertx (io.vertx.core.Vertx)23 JsonObject (io.vertx.core.json.JsonObject)21 Async (io.vertx.ext.unit.Async)20 Handler (io.vertx.core.Handler)19 FrameParser (io.vertx.ext.eventbus.bridge.tcp.impl.protocol.FrameParser)19 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)19 NetClientOptions (io.vertx.core.net.NetClientOptions)17 BridgeOptions (io.vertx.ext.bridge.BridgeOptions)16 PermittedOptions (io.vertx.ext.bridge.PermittedOptions)16 Before (org.junit.Before)16 Message (io.vertx.core.eventbus.Message)15 BridgeEventType (io.vertx.ext.bridge.BridgeEventType)15 FrameHelper (io.vertx.ext.eventbus.bridge.tcp.impl.protocol.FrameHelper)15 TestContext (io.vertx.ext.unit.TestContext)15 VertxUnitRunner (io.vertx.ext.unit.junit.VertxUnitRunner)15 After (org.junit.After)15