Search in sources :

Example 16 with NetServer

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

the class StreamsExamples method pump4.

public void pump4(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();
                sock.drainHandler(done -> {
                    sock.resume();
                });
            }
        });
    }).listen();
}
Also used : 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) NetSocket(io.vertx.core.net.NetSocket) NetServerOptions(io.vertx.core.net.NetServerOptions) NetServer(io.vertx.core.net.NetServer)

Example 17 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.close();
        client = vertx.createHttpClient(opts).websocket(port, "localhost", "/", ws -> {
            addResult(new AssertionError("Websocket unexpectedly connected"));
            ws.close();
        }, t -> {
            addResult(t);
        });
    });
    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 WebSocketHandshakeException && result.getMessage().equals("Websocket connection attempt returned HTTP status code 200")) {
            clientGotCorrectException = true;
        } else {
            throw result;
        }
    }
}
Also used : Buffer(io.vertx.core.buffer.Buffer) Arrays(java.util.Arrays) MessageDigest(java.security.MessageDigest) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Cert(io.vertx.test.core.tls.Cert) WebSocketHandshakeException(io.netty.handler.codec.http.websocketx.WebSocketHandshakeException) Context(io.vertx.core.Context) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TestUtils(io.vertx.test.core.TestUtils) Map(java.util.Map) ReadStream(io.vertx.core.streams.ReadStream) AsyncResult(io.vertx.core.AsyncResult) ConcurrentHashSet(io.vertx.core.impl.ConcurrentHashSet) java.util.concurrent(java.util.concurrent) Vertx(io.vertx.core.Vertx) Set(java.util.Set) Test(org.junit.Test) Future(io.vertx.core.Future) io.vertx.core.http(io.vertx.core.http) Consumer(java.util.function.Consumer) Base64(java.util.Base64) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) DeploymentOptions(io.vertx.core.DeploymentOptions) NetServer(io.vertx.core.net.NetServer) AbstractVerticle(io.vertx.core.AbstractVerticle) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Handler(io.vertx.core.Handler) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Collections(java.util.Collections) NetSocket(io.vertx.core.net.NetSocket) Trust(io.vertx.test.core.tls.Trust) UnsupportedEncodingException(java.io.UnsupportedEncodingException) NetServer(io.vertx.core.net.NetServer) WebSocketHandshakeException(io.netty.handler.codec.http.websocketx.WebSocketHandshakeException) WebSocketHandshakeException(io.netty.handler.codec.http.websocketx.WebSocketHandshakeException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 18 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.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 19 with NetServer

use of io.vertx.core.net.NetServer in project java-chassis by ServiceComb.

the class TcpServer method init.

public void init(Vertx vertx, String sslKey, AsyncResultCallback<InetSocketAddress> callback) {
    NetServer netServer;
    if (endpointObject.isSslEnabled()) {
        SSLOptionFactory factory = SSLOptionFactory.createSSLOptionFactory(sslKey, null);
        SSLOption sslOption;
        if (factory == null) {
            sslOption = SSLOption.buildFromYaml(sslKey);
        } else {
            sslOption = factory.createSSLOption();
        }
        SSLCustom sslCustom = SSLCustom.createSSLCustom(sslOption.getSslCustomClass());
        NetServerOptions serverOptions = new NetServerOptions();
        VertxTLSBuilder.buildNetServerOptions(sslOption, sslCustom, serverOptions);
        netServer = vertx.createNetServer(serverOptions);
    } else {
        netServer = vertx.createNetServer();
    }
    netServer.connectHandler(netSocket -> {
        TcpServerConnection connection = createTcpServerConnection();
        connection.init(netSocket);
    });
    InetSocketAddress socketAddress = endpointObject.getSocketAddress();
    netServer.listen(socketAddress.getPort(), socketAddress.getHostString(), ar -> {
        if (ar.succeeded()) {
            callback.success(socketAddress);
            return;
        }
        String msg = String.format("listen failed, address=%s", socketAddress.toString());
        callback.fail(new Exception(msg, ar.cause()));
    });
}
Also used : SSLOptionFactory(io.servicecomb.foundation.ssl.SSLOptionFactory) InetSocketAddress(java.net.InetSocketAddress) NetServerOptions(io.vertx.core.net.NetServerOptions) NetServer(io.vertx.core.net.NetServer) SSLOption(io.servicecomb.foundation.ssl.SSLOption) SSLCustom(io.servicecomb.foundation.ssl.SSLCustom)

Example 20 with NetServer

use of io.vertx.core.net.NetServer in project incubator-servicecomb-java-chassis by apache.

the class TcpServer method init.

public void init(Vertx vertx, String sslKey, AsyncResultCallback<InetSocketAddress> callback) {
    NetServer netServer;
    if (endpointObject.isSslEnabled()) {
        SSLOptionFactory factory = SSLOptionFactory.createSSLOptionFactory(sslKey, null);
        SSLOption sslOption;
        if (factory == null) {
            sslOption = SSLOption.buildFromYaml(sslKey);
        } else {
            sslOption = factory.createSSLOption();
        }
        SSLCustom sslCustom = SSLCustom.createSSLCustom(sslOption.getSslCustomClass());
        NetServerOptions serverOptions = new NetServerOptions();
        VertxTLSBuilder.buildNetServerOptions(sslOption, sslCustom, serverOptions);
        netServer = vertx.createNetServer(serverOptions);
    } else {
        netServer = vertx.createNetServer();
    }
    netServer.connectHandler(netSocket -> {
        TcpServerConnection connection = createTcpServerConnection();
        connection.init(netSocket);
    });
    InetSocketAddress socketAddress = endpointObject.getSocketAddress();
    netServer.listen(socketAddress.getPort(), socketAddress.getHostString(), ar -> {
        if (ar.succeeded()) {
            callback.success(socketAddress);
            return;
        }
        // 监听失败
        String msg = String.format("listen failed, address=%s", socketAddress.toString());
        callback.fail(new Exception(msg, ar.cause()));
    });
}
Also used : SSLOptionFactory(org.apache.servicecomb.foundation.ssl.SSLOptionFactory) InetSocketAddress(java.net.InetSocketAddress) NetServerOptions(io.vertx.core.net.NetServerOptions) NetServer(io.vertx.core.net.NetServer) SSLOption(org.apache.servicecomb.foundation.ssl.SSLOption) SSLCustom(org.apache.servicecomb.foundation.ssl.SSLCustom)

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