Search in sources :

Example 6 with NetServer

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

the class StreamsExamples method pipe3.

public void pipe3(Vertx vertx) {
    NetServer server = vertx.createNetServer(new NetServerOptions().setPort(1234).setHost("localhost"));
    server.connectHandler(sock -> {
        sock.handler(buffer -> {
            sock.write(buffer);
            if (sock.writeQueueFull()) {
                sock.pause();
            }
        });
    }).listen();
}
Also used : AsyncFile(io.vertx.core.file.AsyncFile) OpenOptions(io.vertx.core.file.OpenOptions) HttpServer(io.vertx.core.http.HttpServer) Vertx(io.vertx.core.Vertx) NetServerOptions(io.vertx.core.net.NetServerOptions) Pipe(io.vertx.core.streams.Pipe) Buffer(io.vertx.core.buffer.Buffer) NetServer(io.vertx.core.net.NetServer) FileSystem(io.vertx.core.file.FileSystem) ReadStream(io.vertx.core.streams.ReadStream) HttpServerOptions(io.vertx.core.http.HttpServerOptions) Pump(io.vertx.core.streams.Pump) Handler(io.vertx.core.Handler) NetSocket(io.vertx.core.net.NetSocket) NetServerOptions(io.vertx.core.net.NetServerOptions) NetServer(io.vertx.core.net.NetServer)

Example 7 with NetServer

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

the class StreamsExamples method pipe1.

public void pipe1(Vertx vertx) {
    NetServer server = vertx.createNetServer(new NetServerOptions().setPort(1234).setHost("localhost"));
    server.connectHandler(sock -> {
        sock.handler(buffer -> {
            // Write the data straight back
            sock.write(buffer);
        });
    }).listen();
}
Also used : AsyncFile(io.vertx.core.file.AsyncFile) OpenOptions(io.vertx.core.file.OpenOptions) HttpServer(io.vertx.core.http.HttpServer) Vertx(io.vertx.core.Vertx) NetServerOptions(io.vertx.core.net.NetServerOptions) Pipe(io.vertx.core.streams.Pipe) Buffer(io.vertx.core.buffer.Buffer) NetServer(io.vertx.core.net.NetServer) FileSystem(io.vertx.core.file.FileSystem) ReadStream(io.vertx.core.streams.ReadStream) HttpServerOptions(io.vertx.core.http.HttpServerOptions) Pump(io.vertx.core.streams.Pump) Handler(io.vertx.core.Handler) NetSocket(io.vertx.core.net.NetSocket) NetServerOptions(io.vertx.core.net.NetServerOptions) NetServer(io.vertx.core.net.NetServer)

Example 8 with NetServer

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

the class WebSocketTest method doTestClientWebSocketConnectionCloseOnBadResponse.

private void doTestClientWebSocketConnectionCloseOnBadResponse(boolean keepAliveInOptions) throws Throwable {
    final Exception serverGotCloseException = new Exception();
    netServer = vertx.createNetServer().connectHandler(sock -> {
        final Buffer fullReq = Buffer.buffer(230);
        sock.handler(b -> {
            fullReq.appendBuffer(b);
            String reqPart = b.toString();
            if (fullReq.toString().contains("\r\n\r\n")) {
                try {
                    String content = "0123456789";
                    content = content + content;
                    content = content + content + content + content + content;
                    String resp = "HTTP/1.1 200 OK\r\n";
                    if (keepAliveInOptions) {
                        resp += "Connection: close\r\n";
                    }
                    resp += "Content-Length: 100\r\n\r\n" + content;
                    sock.write(Buffer.buffer(resp.getBytes("ASCII")));
                } catch (UnsupportedEncodingException e) {
                    addResult(e);
                }
            }
        });
        sock.closeHandler(v -> {
            addResult(serverGotCloseException);
        });
    }).listen(ar -> {
        if (ar.failed()) {
            addResult(ar.cause());
            return;
        }
        NetServer server = ar.result();
        int port = server.actualPort();
        HttpClientOptions opts = new HttpClientOptions().setKeepAlive(keepAliveInOptions);
        client = vertx.createHttpClient(opts);
        client.webSocket(port, "localhost", "/", ar2 -> {
            if (ar2.succeeded()) {
                addResult(new AssertionError("WebSocket unexpectedly connected"));
                ar2.result().close();
            } else {
                addResult(ar2.cause());
            }
        });
    });
    boolean serverGotClose = false;
    boolean clientGotCorrectException = false;
    while (!serverGotClose || !clientGotCorrectException) {
        Throwable result = resultQueue.poll(20, TimeUnit.SECONDS);
        if (result == null) {
            throw new AssertionError("Timed out waiting for expected state, current: serverGotClose = " + serverGotClose + ", clientGotCorrectException = " + clientGotCorrectException);
        } else if (result == serverGotCloseException) {
            serverGotClose = true;
        } else if (result instanceof UpgradeRejectedException && ((UpgradeRejectedException) result).getStatus() == 200) {
            clientGotCorrectException = true;
        } else {
            throw result;
        }
    }
}
Also used : Buffer(io.vertx.core.buffer.Buffer) WebSocketInternal(io.vertx.core.http.impl.WebSocketInternal) MultiMap(io.vertx.core.MultiMap) Context(io.vertx.core.Context) Matcher(java.util.regex.Matcher) PlatformDependent(io.netty.util.internal.PlatformDependent) TestUtils(io.vertx.test.core.TestUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DEFAULT_HTTP_HOST(io.vertx.core.http.HttpTestBase.DEFAULT_HTTP_HOST) ReadStream(io.vertx.core.streams.ReadStream) HAProxy(io.vertx.test.proxy.HAProxy) WebSocketFrameImpl(io.vertx.core.http.impl.ws.WebSocketFrameImpl) CheckingSender(io.vertx.test.core.CheckingSender) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) VertxOptions(io.vertx.core.VertxOptions) Trust(io.vertx.test.tls.Trust) BlockingQueue(java.util.concurrent.BlockingQueue) Future(io.vertx.core.Future) StandardCharsets(java.nio.charset.StandardCharsets) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) CountDownLatch(java.util.concurrent.CountDownLatch) Certificate(java.security.cert.Certificate) Buffer(io.vertx.core.buffer.Buffer) ReferenceCountUtil(io.netty.util.ReferenceCountUtil) AbstractVerticle(io.vertx.core.AbstractVerticle) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Cert(io.vertx.test.tls.Cert) Pattern(java.util.regex.Pattern) UnsupportedEncodingException(java.io.UnsupportedEncodingException) NetSocketInternal(io.vertx.core.net.impl.NetSocketInternal) NetSocket(io.vertx.core.net.NetSocket) java.util(java.util) MessageDigest(java.security.MessageDigest) DEFAULT_HTTP_PORT(io.vertx.core.http.HttpTestBase.DEFAULT_HTTP_PORT) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) TestUtils.assertNullPointerException(io.vertx.test.core.TestUtils.assertNullPointerException) VertxTestBase(io.vertx.test.core.VertxTestBase) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) DEFAULT_HTTPS_HOST(io.vertx.core.http.HttpTestBase.DEFAULT_HTTPS_HOST) BiConsumer(java.util.function.BiConsumer) CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) WebSocket13FrameDecoder(io.netty.handler.codec.http.websocketx.WebSocket13FrameDecoder) AsyncResult(io.vertx.core.AsyncResult) SocketAddress(io.vertx.core.net.SocketAddress) DEFAULT_TEST_URI(io.vertx.core.http.HttpTestBase.DEFAULT_TEST_URI) ConcurrentHashSet(io.vertx.core.impl.ConcurrentHashSet) Promise(io.vertx.core.Promise) TestUtils.randomAlphaString(io.vertx.test.core.TestUtils.randomAlphaString) Vertx(io.vertx.core.Vertx) Test(org.junit.Test) IOException(java.io.IOException) Http1xServerConnection(io.vertx.core.http.impl.Http1xServerConnection) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) WebSocket13FrameEncoder(io.netty.handler.codec.http.websocketx.WebSocket13FrameEncoder) DeploymentOptions(io.vertx.core.DeploymentOptions) NetServer(io.vertx.core.net.NetServer) DEFAULT_HTTPS_PORT(io.vertx.core.http.HttpTestBase.DEFAULT_HTTPS_PORT) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Handler(io.vertx.core.Handler) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException) Http1xClientConnection(io.vertx.core.http.impl.Http1xClientConnection) UnsupportedEncodingException(java.io.UnsupportedEncodingException) NetServer(io.vertx.core.net.NetServer) TestUtils.randomAlphaString(io.vertx.test.core.TestUtils.randomAlphaString) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) TestUtils.assertNullPointerException(io.vertx.test.core.TestUtils.assertNullPointerException) IOException(java.io.IOException) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException)

Example 9 with NetServer

use of io.vertx.core.net.NetServer 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.testResolveASameServer("127.0.0.1");
    // 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()));
    try {
        server.connectHandler(so -> {
            so.end(Buffer.buffer("hello"));
        });
        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);
    } finally {
        server.close();
    }
}
Also used : 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 10 with NetServer

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

the class HostnameResolutionTest method testAsyncResolveConnectIsNotifiedOnChannelEventLoop.

@Test
public void testAsyncResolveConnectIsNotifiedOnChannelEventLoop() throws Exception {
    CountDownLatch listenLatch = new CountDownLatch(1);
    NetServer server = vertx.createNetServer().connectHandler(so -> {
    });
    try {
        server.listen(1234, "localhost", onSuccess(v -> listenLatch.countDown()));
        awaitLatch(listenLatch);
        AtomicReference<Thread> channelThread = new AtomicReference<>();
        CountDownLatch connectLatch = new CountDownLatch(1);
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.channelFactory(((VertxInternal) vertx).transport().channelFactory(false));
        bootstrap.group(vertx.nettyEventLoopGroup());
        bootstrap.resolver(((VertxInternal) vertx).nettyAddressResolverGroup());
        bootstrap.handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                channelThread.set(Thread.currentThread());
                connectLatch.countDown();
            }
        });
        ChannelFuture channelFut = bootstrap.connect("localhost", 1234);
        awaitLatch(connectLatch);
        channelFut.addListener(v -> {
            assertTrue(v.isSuccess());
            assertEquals(channelThread.get(), Thread.currentThread());
            testComplete();
        });
        await();
    } finally {
        server.close();
    }
}
Also used : VertxException(io.vertx.core.VertxException) RecordClass(org.apache.directory.server.dns.messages.RecordClass) java.util(java.util) HttpServer(io.vertx.core.http.HttpServer) CompletableFuture(java.util.concurrent.CompletableFuture) VertxTestBase(io.vertx.test.core.VertxTestBase) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) InetAddress(java.net.InetAddress) TestUtils(io.vertx.test.core.TestUtils) JsonObject(io.vertx.core.json.JsonObject) FakeDNSServer(io.vertx.test.fakedns.FakeDNSServer) NetClient(io.vertx.core.net.NetClient) ResourceRecord(org.apache.directory.server.dns.messages.ResourceRecord) VertxImpl(io.vertx.core.impl.VertxImpl) VertxInternal(io.vertx.core.impl.VertxInternal) ChannelInitializer(io.netty.channel.ChannelInitializer) AddressResolver(io.vertx.core.impl.AddressResolver) DnsAttribute(org.apache.directory.server.dns.store.DnsAttribute) VertxOptions(io.vertx.core.VertxOptions) Test(org.junit.Test) InetSocketAddress(java.net.InetSocketAddress) UnknownHostException(java.net.UnknownHostException) File(java.io.File) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) TimeUnit(java.util.concurrent.TimeUnit) Bootstrap(io.netty.bootstrap.Bootstrap) CountDownLatch(java.util.concurrent.CountDownLatch) NetServerOptions(io.vertx.core.net.NetServerOptions) Buffer(io.vertx.core.buffer.Buffer) NetServer(io.vertx.core.net.NetServer) HttpMethod(io.vertx.core.http.HttpMethod) RecordType(org.apache.directory.server.dns.messages.RecordType) HttpClient(io.vertx.core.http.HttpClient) ChannelFuture(io.netty.channel.ChannelFuture) VertxInternal(io.vertx.core.impl.VertxInternal) Channel(io.netty.channel.Channel) NetServer(io.vertx.core.net.NetServer) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) VertxException(io.vertx.core.VertxException) UnknownHostException(java.net.UnknownHostException) Bootstrap(io.netty.bootstrap.Bootstrap) Test(org.junit.Test)

Aggregations

NetServer (io.vertx.core.net.NetServer)28 NetServerOptions (io.vertx.core.net.NetServerOptions)20 Buffer (io.vertx.core.buffer.Buffer)16 Vertx (io.vertx.core.Vertx)15 Test (org.junit.Test)15 NetSocket (io.vertx.core.net.NetSocket)13 Handler (io.vertx.core.Handler)12 NetClient (io.vertx.core.net.NetClient)11 VertxOptions (io.vertx.core.VertxOptions)10 Pump (io.vertx.core.streams.Pump)10 HttpServer (io.vertx.core.http.HttpServer)9 ReadStream (io.vertx.core.streams.ReadStream)7 InetSocketAddress (java.net.InetSocketAddress)7 CountDownLatch (java.util.concurrent.CountDownLatch)7 TimeUnit (java.util.concurrent.TimeUnit)7 TestUtils (io.vertx.test.core.TestUtils)6 File (java.io.File)6 CompletableFuture (java.util.concurrent.CompletableFuture)6 AsyncFile (io.vertx.core.file.AsyncFile)5 FileSystem (io.vertx.core.file.FileSystem)5