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);
});
}
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);
}
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();
}
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);
}
}
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);
}
}
}
}
Aggregations