Search in sources :

Example 11 with ChannelInitializer

use of io.netty.channel.ChannelInitializer in project CorfuDB by CorfuDB.

the class CorfuServer method main.

public static void main(String[] args) {
    serverRunning = true;
    // Parse the options given, using docopt.
    Map<String, Object> opts = new Docopt(USAGE).withVersion(GitRepositoryState.getRepositoryState().describe).parse(args);
    int port = Integer.parseInt((String) opts.get("<port>"));
    // Print a nice welcome message.
    AnsiConsole.systemInstall();
    printLogo();
    System.out.println(ansi().a("Welcome to ").fg(RED).a("CORFU ").fg(MAGENTA).a("SERVER").reset());
    System.out.println(ansi().a("Version ").a(Version.getVersionString()).a(" (").fg(BLUE).a(GitRepositoryState.getRepositoryState().commitIdAbbrev).reset().a(")"));
    System.out.println(ansi().a("Serving on port ").fg(WHITE).a(port).reset());
    System.out.println(ansi().a("Service directory: ").fg(WHITE).a((Boolean) opts.get("--memory") ? "MEMORY mode" : opts.get("--log-path")).reset());
    // Pick the correct logging level before outputting error messages.
    Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    switch((String) opts.get("--log-level")) {
        case "ERROR":
            root.setLevel(Level.ERROR);
            break;
        case "WARN":
            root.setLevel(Level.WARN);
            break;
        case "INFO":
            root.setLevel(Level.INFO);
            break;
        case "DEBUG":
            root.setLevel(Level.DEBUG);
            break;
        case "TRACE":
            root.setLevel(Level.TRACE);
            break;
        default:
            root.setLevel(Level.INFO);
            log.warn("Level {} not recognized, defaulting to level INFO", opts.get("--log-level"));
    }
    log.debug("Started with arguments: " + opts);
    // Create the service directory if it does not exist.
    if (!(Boolean) opts.get("--memory")) {
        File serviceDir = new File((String) opts.get("--log-path"));
        if (!serviceDir.exists()) {
            if (serviceDir.mkdirs()) {
                log.info("Created new service directory at {}.", serviceDir);
            }
        } else if (!serviceDir.isDirectory()) {
            log.error("Service directory {} does not point to a directory. Aborting.", serviceDir);
            throw new RuntimeException("Service directory must be a directory!");
        }
    }
    // Now, we start the Netty router, and have it route to the correct port.
    router = new NettyServerRouter(opts);
    // Create a common Server Context for all servers to access.
    serverContext = new ServerContext(opts, router);
    // Add each role to the router.
    addSequencer();
    addLayoutServer();
    addLogUnit();
    addManagementServer();
    router.baseServer.setOptionsMap(opts);
    // Setup SSL if needed
    Boolean tlsEnabled = (Boolean) opts.get("--enable-tls");
    Boolean tlsMutualAuthEnabled = (Boolean) opts.get("--enable-tls-mutual-auth");
    if (tlsEnabled) {
        // Get the TLS cipher suites to enable
        String ciphs = (String) opts.get("--tls-ciphers");
        if (ciphs != null) {
            List<String> ciphers = Pattern.compile(",").splitAsStream(ciphs).map(String::trim).collect(Collectors.toList());
            enabledTlsCipherSuites = ciphers.toArray(new String[ciphers.size()]);
        }
        // Get the TLS protocols to enable
        String protos = (String) opts.get("--tls-protocols");
        if (protos != null) {
            List<String> protocols = Pattern.compile(",").splitAsStream(protos).map(String::trim).collect(Collectors.toList());
            enabledTlsProtocols = protocols.toArray(new String[protocols.size()]);
        }
        try {
            sslContext = TlsUtils.enableTls(TlsUtils.SslContextType.SERVER_CONTEXT, (String) opts.get("--keystore"), e -> {
                log.error("Could not load keys from the key store.");
                System.exit(1);
            }, (String) opts.get("--keystore-password-file"), e -> {
                log.error("Could not read the key store password file.");
                System.exit(1);
            }, (String) opts.get("--truststore"), e -> {
                log.error("Could not load keys from the trust store.");
                System.exit(1);
            }, (String) opts.get("--truststore-password-file"), e -> {
                log.error("Could not read the trust store password file.");
                System.exit(1);
            });
        } catch (Exception ex) {
            log.error("Could not build the SSL context");
            System.exit(1);
        }
    }
    Boolean saslPlainTextAuth = (Boolean) opts.get("--enable-sasl-plain-text-auth");
    // Create the event loops responsible for servicing inbound messages.
    EventLoopGroup bossGroup;
    EventLoopGroup workerGroup;
    EventExecutorGroup ee;
    bossGroup = new NioEventLoopGroup(1, new ThreadFactory() {

        final AtomicInteger threadNum = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("accept-" + threadNum.getAndIncrement());
            return t;
        }
    });
    workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2, new ThreadFactory() {

        final AtomicInteger threadNum = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("io-" + threadNum.getAndIncrement());
            return t;
        }
    });
    ee = new DefaultEventExecutorGroup(Runtime.getRuntime().availableProcessors() * 2, new ThreadFactory() {

        final AtomicInteger threadNum = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("event-" + threadNum.getAndIncrement());
            return t;
        }
    });
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100).childOption(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(io.netty.channel.socket.SocketChannel ch) throws Exception {
                if (tlsEnabled) {
                    SSLEngine engine = sslContext.newEngine(ch.alloc());
                    engine.setEnabledCipherSuites(enabledTlsCipherSuites);
                    engine.setEnabledProtocols(enabledTlsProtocols);
                    if (tlsMutualAuthEnabled) {
                        engine.setNeedClientAuth(true);
                    }
                    ch.pipeline().addLast("ssl", new SslHandler(engine));
                }
                ch.pipeline().addLast(new LengthFieldPrepender(4));
                ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                if (saslPlainTextAuth) {
                    ch.pipeline().addLast("sasl/plain-text", new PlainTextSaslNettyServer());
                }
                ch.pipeline().addLast(ee, new NettyCorfuMessageDecoder());
                ch.pipeline().addLast(ee, new NettyCorfuMessageEncoder());
                ch.pipeline().addLast(ee, router);
            }
        });
        ChannelFuture f = b.bind(port).sync();
        while (true) {
            try {
                f.channel().closeFuture().sync();
            } catch (InterruptedException ie) {
            }
        }
    } catch (InterruptedException ie) {
    } catch (Exception ex) {
        log.error("Corfu server shut down unexpectedly due to exception", ex);
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
Also used : ChannelOption(io.netty.channel.ChannelOption) Getter(lombok.Getter) GitRepositoryState(org.corfudb.util.GitRepositoryState) LoggerFactory(org.slf4j.LoggerFactory) NettyCorfuMessageEncoder(org.corfudb.protocols.wireprotocol.NettyCorfuMessageEncoder) Docopt(org.docopt.Docopt) SSLEngine(javax.net.ssl.SSLEngine) PlainTextSaslNettyServer(org.corfudb.security.sasl.plaintext.PlainTextSaslNettyServer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DefaultEventExecutorGroup(io.netty.util.concurrent.DefaultEventExecutorGroup) Map(java.util.Map) Color(org.fusesource.jansi.Ansi.Color) ThreadFactory(java.util.concurrent.ThreadFactory) SocketChannel(io.netty.channel.socket.SocketChannel) LengthFieldPrepender(io.netty.handler.codec.LengthFieldPrepender) TlsUtils(org.corfudb.security.tls.TlsUtils) Ansi.ansi(org.fusesource.jansi.Ansi.ansi) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) NettyCorfuMessageDecoder(org.corfudb.protocols.wireprotocol.NettyCorfuMessageDecoder) EventLoopGroup(io.netty.channel.EventLoopGroup) ChannelInitializer(io.netty.channel.ChannelInitializer) SslContext(io.netty.handler.ssl.SslContext) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator) EventExecutorGroup(io.netty.util.concurrent.EventExecutorGroup) Collectors(java.util.stream.Collectors) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) File(java.io.File) ChannelFuture(io.netty.channel.ChannelFuture) Level(ch.qos.logback.classic.Level) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) AnsiConsole(org.fusesource.jansi.AnsiConsole) Logger(ch.qos.logback.classic.Logger) SslHandler(io.netty.handler.ssl.SslHandler) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Pattern(java.util.regex.Pattern) Version(org.corfudb.util.Version) ThreadFactory(java.util.concurrent.ThreadFactory) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) DefaultEventExecutorGroup(io.netty.util.concurrent.DefaultEventExecutorGroup) SSLEngine(javax.net.ssl.SSLEngine) NettyCorfuMessageEncoder(org.corfudb.protocols.wireprotocol.NettyCorfuMessageEncoder) Logger(ch.qos.logback.classic.Logger) LengthFieldPrepender(io.netty.handler.codec.LengthFieldPrepender) Docopt(org.docopt.Docopt) PlainTextSaslNettyServer(org.corfudb.security.sasl.plaintext.PlainTextSaslNettyServer) SocketChannel(io.netty.channel.socket.SocketChannel) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) DefaultEventExecutorGroup(io.netty.util.concurrent.DefaultEventExecutorGroup) EventExecutorGroup(io.netty.util.concurrent.EventExecutorGroup) ChannelFuture(io.netty.channel.ChannelFuture) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) SslHandler(io.netty.handler.ssl.SslHandler) NettyCorfuMessageDecoder(org.corfudb.protocols.wireprotocol.NettyCorfuMessageDecoder) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) File(java.io.File)

Example 12 with ChannelInitializer

use of io.netty.channel.ChannelInitializer in project moco by dreamhead.

the class MocoSocketServer method channelInitializer.

@Override
protected ChannelInitializer<SocketChannel> channelInitializer() {
    return new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("aggregator", new MocoAggregator());
            pipeline.addLast("handler", new MocoSocketHandler(serverSetting));
        }
    };
}
Also used : SocketChannel(io.netty.channel.socket.SocketChannel) ChannelInitializer(io.netty.channel.ChannelInitializer) ChannelPipeline(io.netty.channel.ChannelPipeline)

Example 13 with ChannelInitializer

use of io.netty.channel.ChannelInitializer in project vert.x by eclipse.

the class Http2ServerTest method testPriorKnowledge.

@Test
public void testPriorKnowledge() throws Exception {
    server.close();
    server = vertx.createHttpServer(new HttpServerOptions().setPort(DEFAULT_HTTP_PORT).setHost(DEFAULT_HTTP_HOST));
    server.requestHandler(req -> {
        req.response().end("Hello World");
    });
    startServer();
    TestClient client = new TestClient() {

        @Override
        protected ChannelInitializer channelInitializer(int port, String host, Consumer<Connection> handler) {
            return new ChannelInitializer() {

                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    Http2Connection connection = new DefaultHttp2Connection(false);
                    TestClientHandlerBuilder clientHandlerBuilder = new TestClientHandlerBuilder(handler);
                    TestClientHandler clientHandler = clientHandlerBuilder.build(connection);
                    p.addLast(clientHandler);
                }
            };
        }
    };
    ChannelFuture fut = client.connect(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, request -> {
        request.decoder.frameListener(new Http2EventAdapter() {

            @Override
            public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) throws Http2Exception {
                vertx.runOnContext(v -> {
                    testComplete();
                });
            }
        });
        int id = request.nextStreamId();
        request.encoder.writeHeaders(request.context, id, GET("/"), 0, true, request.context.newPromise());
        request.context.flush();
    });
    fut.sync();
    await();
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Arrays(java.util.Arrays) GZIPInputStream(java.util.zip.GZIPInputStream) HttpServer(io.vertx.core.http.HttpServer) MultiMap(io.vertx.core.MultiMap) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) DefaultHttp2Connection(io.netty.handler.codec.http2.DefaultHttp2Connection) Context(io.vertx.core.Context) Unpooled(io.netty.buffer.Unpooled) Http2ConnectionDecoder(io.netty.handler.codec.http2.Http2ConnectionDecoder) ByteArrayInputStream(java.io.ByteArrayInputStream) HttpVersion(io.vertx.core.http.HttpVersion) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Http2Exception(io.netty.handler.codec.http2.Http2Exception) Map(java.util.Map) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) ReadStream(io.vertx.core.streams.ReadStream) AbstractHttp2ConnectionHandlerBuilder(io.netty.handler.codec.http2.AbstractHttp2ConnectionHandlerBuilder) Http2FrameAdapter(io.netty.handler.codec.http2.Http2FrameAdapter) StreamResetException(io.vertx.core.http.StreamResetException) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) ChannelInitializer(io.netty.channel.ChannelInitializer) Http2Flags(io.netty.handler.codec.http2.Http2Flags) Set(java.util.Set) ChannelPipeline(io.netty.channel.ChannelPipeline) Http2ConnectionHandler(io.netty.handler.codec.http2.Http2ConnectionHandler) Future(io.vertx.core.Future) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) StandardCharsets(java.nio.charset.StandardCharsets) Base64(java.util.Base64) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) SslHandler(io.netty.handler.ssl.SslHandler) Http2Headers(io.netty.handler.codec.http2.Http2Headers) HttpServerResponse(io.vertx.core.http.HttpServerResponse) Http2Error(io.netty.handler.codec.http2.Http2Error) HttpClient(io.vertx.core.http.HttpClient) NetSocket(io.vertx.core.net.NetSocket) Trust(io.vertx.test.core.tls.Trust) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) HttpServerRequest(io.vertx.core.http.HttpServerRequest) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) HttpClientRequest(io.vertx.core.http.HttpClientRequest) ByteBuf(io.netty.buffer.ByteBuf) WriteStream(io.vertx.core.streams.WriteStream) Http2Stream(io.netty.handler.codec.http2.Http2Stream) BiConsumer(java.util.function.BiConsumer) AsyncResult(io.vertx.core.AsyncResult) HttpClientOptions(io.vertx.core.http.HttpClientOptions) HttpConnection(io.vertx.core.http.HttpConnection) EventLoopGroup(io.netty.channel.EventLoopGroup) VertxInternal(io.vertx.core.impl.VertxInternal) ClosedChannelException(java.nio.channels.ClosedChannelException) Vertx(io.vertx.core.Vertx) FileOutputStream(java.io.FileOutputStream) ApplicationProtocolNames(io.netty.handler.ssl.ApplicationProtocolNames) Test(org.junit.Test) IOException(java.io.IOException) SSLHelper(io.vertx.core.net.impl.SSLHelper) File(java.io.File) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) Http2Settings(io.netty.handler.codec.http2.Http2Settings) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Bootstrap(io.netty.bootstrap.Bootstrap) AtomicLong(java.util.concurrent.atomic.AtomicLong) Http2Connection(io.netty.handler.codec.http2.Http2Connection) HttpMethod(io.vertx.core.http.HttpMethod) HttpUtils(io.vertx.core.http.impl.HttpUtils) HttpServerOptions(io.vertx.core.http.HttpServerOptions) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Handler(io.vertx.core.Handler) Collections(java.util.Collections) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) DefaultHttp2Connection(io.netty.handler.codec.http2.DefaultHttp2Connection) Http2Exception(io.netty.handler.codec.http2.Http2Exception) DefaultHttp2Connection(io.netty.handler.codec.http2.DefaultHttp2Connection) Http2Connection(io.netty.handler.codec.http2.Http2Connection) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) HttpServerOptions(io.vertx.core.http.HttpServerOptions) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPipeline(io.netty.channel.ChannelPipeline) BiConsumer(java.util.function.BiConsumer) Consumer(java.util.function.Consumer) Http2Headers(io.netty.handler.codec.http2.Http2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) ChannelInitializer(io.netty.channel.ChannelInitializer) Test(org.junit.Test)

Example 14 with ChannelInitializer

use of io.netty.channel.ChannelInitializer in project vert.x by eclipse.

the class NetServerBase method listen.

public synchronized void listen(Handler<? super C> handler, int port, String host, Handler<AsyncResult<Void>> listenHandler) {
    if (handler == null) {
        throw new IllegalStateException("Set connect handler first");
    }
    if (listening) {
        throw new IllegalStateException("Listen already called");
    }
    listening = true;
    listenContext = vertx.getOrCreateContext();
    registeredHandler = handler;
    synchronized (vertx.sharedNetServers()) {
        // Will be updated on bind for a wildcard port
        this.actualPort = port;
        id = new ServerID(port, host);
        NetServerBase shared = vertx.sharedNetServers().get(id);
        if (shared == null || port == 0) {
            // Wildcard port will imply a new actual server each time
            serverChannelGroup = new DefaultChannelGroup("vertx-acceptor-channels", GlobalEventExecutor.INSTANCE);
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(availableWorkers);
            bootstrap.channel(NioServerSocketChannel.class);
            sslHelper.validate(vertx);
            bootstrap.childHandler(new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) throws Exception {
                    if (isPaused()) {
                        ch.close();
                        return;
                    }
                    ChannelPipeline pipeline = ch.pipeline();
                    NetServerBase.this.initChannel(ch.pipeline());
                    pipeline.addLast("handler", new ServerHandler(ch));
                }
            });
            applyConnectionOptions(bootstrap);
            handlerManager.addHandler(handler, listenContext);
            try {
                bindFuture = AsyncResolveConnectHelper.doBind(vertx, port, host, bootstrap);
                bindFuture.addListener(res -> {
                    if (res.succeeded()) {
                        Channel ch = res.result();
                        log.trace("Net server listening on " + host + ":" + ch.localAddress());
                        NetServerBase.this.actualPort = ((InetSocketAddress) ch.localAddress()).getPort();
                        NetServerBase.this.id = new ServerID(NetServerBase.this.actualPort, id.host);
                        serverChannelGroup.add(ch);
                        vertx.sharedNetServers().put(id, NetServerBase.this);
                        metrics = vertx.metricsSPI().createMetrics(new SocketAddressImpl(id.port, id.host), options);
                    } else {
                        vertx.sharedNetServers().remove(id);
                    }
                });
            } catch (Throwable t) {
                // Make sure we send the exception back through the handler (if any)
                if (listenHandler != null) {
                    vertx.runOnContext(v -> listenHandler.handle(Future.failedFuture(t)));
                } else {
                    // No handler - log so user can see failure
                    log.error(t);
                }
                listening = false;
                return;
            }
            if (port != 0) {
                vertx.sharedNetServers().put(id, this);
            }
            actualServer = this;
        } else {
            // Server already exists with that host/port - we will use that
            actualServer = shared;
            this.actualPort = shared.actualPort();
            metrics = vertx.metricsSPI().createMetrics(new SocketAddressImpl(id.port, id.host), options);
            actualServer.handlerManager.addHandler(handler, listenContext);
        }
        // just add it to the future so it gets notified once the bind is complete
        actualServer.bindFuture.addListener(res -> {
            if (listenHandler != null) {
                AsyncResult<Void> ares;
                if (res.succeeded()) {
                    ares = Future.succeededFuture();
                } else {
                    listening = false;
                    ares = Future.failedFuture(res.cause());
                }
                listenContext.runOnContext(v -> listenHandler.handle(ares));
            } else if (res.failed()) {
                log.error("Failed to listen", res.cause());
                listening = false;
            }
        });
    }
    return;
}
Also used : DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) ChannelOption(io.netty.channel.ChannelOption) ContextImpl(io.vertx.core.impl.ContextImpl) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) TCPMetrics(io.vertx.core.spi.metrics.TCPMetrics) LoggerFactory(io.vertx.core.logging.LoggerFactory) GlobalEventExecutor(io.netty.util.concurrent.GlobalEventExecutor) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) FixedRecvByteBufAllocator(io.netty.channel.FixedRecvByteBufAllocator) Map(java.util.Map) AsyncResult(io.vertx.core.AsyncResult) Logger(io.vertx.core.logging.Logger) Metrics(io.vertx.core.spi.metrics.Metrics) Closeable(io.vertx.core.Closeable) ChannelGroup(io.netty.channel.group.ChannelGroup) VertxInternal(io.vertx.core.impl.VertxInternal) ChannelInitializer(io.netty.channel.ChannelInitializer) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) MetricsProvider(io.vertx.core.spi.metrics.MetricsProvider) ChannelPipeline(io.netty.channel.ChannelPipeline) EventLoop(io.netty.channel.EventLoop) Future(io.vertx.core.Future) InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) NetServerOptions(io.vertx.core.net.NetServerOptions) SslHandler(io.netty.handler.ssl.SslHandler) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelGroupFuture(io.netty.channel.group.ChannelGroupFuture) Handler(io.vertx.core.Handler) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelPipeline(io.netty.channel.ChannelPipeline)

Example 15 with ChannelInitializer

use of io.netty.channel.ChannelInitializer in project netty by netty.

the class LocalEcho method main.

public static void main(String[] args) throws Exception {
    // Address to bind on / connect to.
    final LocalAddress addr = new LocalAddress(PORT);
    EventLoopGroup serverGroup = new DefaultEventLoopGroup();
    // NIO event loops are also OK
    EventLoopGroup clientGroup = new NioEventLoopGroup();
    try {
        // Note that we can use any event loop to ensure certain local channels
        // are handled by the same event loop thread which drives a certain socket channel
        // to reduce the communication latency between socket channels and local channels.
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(serverGroup).channel(LocalServerChannel.class).handler(new ChannelInitializer<LocalServerChannel>() {

            @Override
            public void initChannel(LocalServerChannel ch) throws Exception {
                ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
            }
        }).childHandler(new ChannelInitializer<LocalChannel>() {

            @Override
            public void initChannel(LocalChannel ch) throws Exception {
                ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new LocalEchoServerHandler());
            }
        });
        Bootstrap cb = new Bootstrap();
        cb.group(clientGroup).channel(LocalChannel.class).handler(new ChannelInitializer<LocalChannel>() {

            @Override
            public void initChannel(LocalChannel ch) throws Exception {
                ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new LocalEchoClientHandler());
            }
        });
        // Start the server.
        sb.bind(addr).sync();
        // Start the client.
        Channel ch = cb.connect(addr).sync().channel();
        // Read commands from the stdin.
        System.out.println("Enter text (quit to end)");
        ChannelFuture lastWriteFuture = null;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        for (; ; ) {
            String line = in.readLine();
            if (line == null || "quit".equalsIgnoreCase(line)) {
                break;
            }
            // Sends the received line to the server.
            lastWriteFuture = ch.writeAndFlush(line);
        }
        // Wait until all messages are flushed before closing the channel.
        if (lastWriteFuture != null) {
            lastWriteFuture.awaitUninterruptibly();
        }
    } finally {
        serverGroup.shutdownGracefully();
        clientGroup.shutdownGracefully();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) LoggingHandler(io.netty.handler.logging.LoggingHandler) LocalAddress(io.netty.channel.local.LocalAddress) InputStreamReader(java.io.InputStreamReader) LocalChannel(io.netty.channel.local.LocalChannel) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Channel(io.netty.channel.Channel) LocalChannel(io.netty.channel.local.LocalChannel) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) LocalServerChannel(io.netty.channel.local.LocalServerChannel) BufferedReader(java.io.BufferedReader) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Aggregations

ChannelInitializer (io.netty.channel.ChannelInitializer)19 Channel (io.netty.channel.Channel)13 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)12 InetSocketAddress (java.net.InetSocketAddress)12 ChannelPipeline (io.netty.channel.ChannelPipeline)10 Bootstrap (io.netty.bootstrap.Bootstrap)9 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)8 ChannelFuture (io.netty.channel.ChannelFuture)7 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)7 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)6 SocketChannel (io.netty.channel.socket.SocketChannel)6 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)6 SslHandler (io.netty.handler.ssl.SslHandler)6 EventLoopGroup (io.netty.channel.EventLoopGroup)5 Map (java.util.Map)5 VertxInternal (io.vertx.core.impl.VertxInternal)4 ByteBuf (io.netty.buffer.ByteBuf)3 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)3 ChannelOption (io.netty.channel.ChannelOption)3 NioDatagramChannel (io.netty.channel.socket.nio.NioDatagramChannel)3