Example usage for io.netty.bootstrap ServerBootstrap childHandler

List of usage examples for io.netty.bootstrap ServerBootstrap childHandler

Introduction

In this page you can find the example usage for io.netty.bootstrap ServerBootstrap childHandler.

Prototype

ChannelHandler childHandler

To view the source code for io.netty.bootstrap ServerBootstrap childHandler.

Click Source Link

Usage

From source file:io.crate.http.HttpTestServer.java

License:Apache License

public void run() throws InterruptedException {
    // Configure the server.
    ServerBootstrap bootstrap = new ServerBootstrap();
    group = new NioEventLoopGroup();
    bootstrap.group(group);/*from w ww.  j av  a 2  s  .  c  o  m*/
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childHandler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("decoder", new HttpRequestDecoder());
            pipeline.addLast("encoder", new HttpResponseEncoder());
            pipeline.addLast("deflater", new HttpContentCompressor());
            pipeline.addLast("handler", new HttpTestServerHandler());
        }
    });

    // Bind and start to accept incoming connections.
    channel = bootstrap.bind(new InetSocketAddress(port)).sync().channel();
}

From source file:io.grpc.netty.NettyServer.java

License:Apache License

@Override
public void start(ServerListener serverListener) throws IOException {
    listener = checkNotNull(serverListener, "serverListener");

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup);//from   w  w  w  .j av  a2s  .c  o m
    b.channelFactory(channelFactory);
    // For non-socket based channel, the option will be ignored.
    b.option(SO_BACKLOG, 128);
    b.childOption(SO_KEEPALIVE, true);

    if (channelOptions != null) {
        for (Map.Entry<ChannelOption<?>, ?> entry : channelOptions.entrySet()) {
            @SuppressWarnings("unchecked")
            ChannelOption<Object> key = (ChannelOption<Object>) entry.getKey();
            b.childOption(key, entry.getValue());
        }
    }

    b.childHandler(new ChannelInitializer<Channel>() {
        @Override
        public void initChannel(Channel ch) {

            ChannelPromise channelDone = ch.newPromise();

            long maxConnectionAgeInNanos = NettyServer.this.maxConnectionAgeInNanos;
            if (maxConnectionAgeInNanos != MAX_CONNECTION_AGE_NANOS_DISABLED) {
                // apply a random jitter of +/-10% to max connection age
                maxConnectionAgeInNanos = (long) ((.9D + Math.random() * .2D) * maxConnectionAgeInNanos);
            }

            NettyServerTransport transport = new NettyServerTransport(ch, channelDone, protocolNegotiator,
                    streamTracerFactories, transportTracerFactory.create(), maxStreamsPerConnection,
                    flowControlWindow, maxMessageSize, maxHeaderListSize, keepAliveTimeInNanos,
                    keepAliveTimeoutInNanos, maxConnectionIdleInNanos, maxConnectionAgeInNanos,
                    maxConnectionAgeGraceInNanos, permitKeepAliveWithoutCalls, permitKeepAliveTimeInNanos);
            ServerTransportListener transportListener;
            // This is to order callbacks on the listener, not to guard access to channel.
            synchronized (NettyServer.this) {
                if (channel != null && !channel.isOpen()) {
                    // Server already shutdown.
                    ch.close();
                    return;
                }
                // `channel` shutdown can race with `ch` initialization, so this is only safe to increment
                // inside the lock.
                eventLoopReferenceCounter.retain();
                transportListener = listener.transportCreated(transport);
            }

            /**
             * Releases the event loop if the channel is "done", possibly due to the channel closing.
             */
            final class LoopReleaser implements ChannelFutureListener {
                private boolean done;

                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!done) {
                        done = true;
                        eventLoopReferenceCounter.release();
                    }
                }
            }

            transport.start(transportListener);
            ChannelFutureListener loopReleaser = new LoopReleaser();
            channelDone.addListener(loopReleaser);
            ch.closeFuture().addListener(loopReleaser);
        }
    });
    // Bind and start to accept incoming connections.
    ChannelFuture future = b.bind(address);
    try {
        future.await();
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
        throw new RuntimeException("Interrupted waiting for bind");
    }
    if (!future.isSuccess()) {
        throw new IOException("Failed to bind", future.cause());
    }
    channel = future.channel();
    Future<?> channelzFuture = channel.eventLoop().submit(new Runnable() {
        @Override
        public void run() {
            InternalInstrumented<SocketStats> listenSocket = new ListenSocket(channel);
            listenSocketStats.set(listenSocket);
            channelz.addListenSocket(listenSocket);
        }
    });
    try {
        channelzFuture.await();
    } catch (InterruptedException ex) {
        throw new RuntimeException("Interrupted while registering listen socket to channelz", ex);
    }
}

From source file:io.hekate.network.netty.NettyServer.java

License:Apache License

private void doStart(int attempt) {
    assert Thread.holdsLock(mux) : "Thread must hold lock.";

    ServerBootstrap boot = new ServerBootstrap();

    if (acceptors instanceof EpollEventLoopGroup) {
        if (DEBUG) {
            log.debug("Using EPOLL server socket channel.");
        }/*  ww  w  .j  a va 2 s .  c om*/

        boot.channel(EpollServerSocketChannel.class);
    } else {
        if (DEBUG) {
            log.debug("Using NIO server socket channel.");
        }

        boot.channel(NioServerSocketChannel.class);
    }

    boot.group(acceptors, workers);

    setOpts(boot);
    setChildOpts(boot);

    boot.handler(new ChannelInboundHandlerAdapter() {
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            mayBeRetry(ctx.channel(), attempt, cause);
        }
    });

    boot.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel channel) throws Exception {
            InetSocketAddress remoteAddress = channel.remoteAddress();
            InetSocketAddress localAddress = channel.localAddress();

            synchronized (mux) {
                if (state == STOPPING || state == STOPPED) {
                    if (DEBUG) {
                        log.debug("Closing connection since server is in {} state [address={}].", state,
                                remoteAddress);
                    }

                    channel.close();

                    return;
                }

                // Setup pipeline.
                ChannelPipeline pipe = channel.pipeline();

                // Configure SSL.
                if (ssl != null) {
                    pipe.addLast(ssl.newHandler(channel.alloc()));
                }

                // Message codecs.
                NetworkProtocolCodec codec = new NetworkProtocolCodec(codecs);

                pipe.addLast(new NetworkProtocolVersion.Decoder());
                pipe.addLast(codec.encoder());
                pipe.addLast(codec.decoder());

                // Client handler.
                NettyServerClient client = new NettyServerClient(remoteAddress, localAddress, ssl != null,
                        hbInterval, hbLossThreshold, hbDisabled, handlers, workers);

                pipe.addLast(client);

                // Register client to this server.
                clients.put(channel, client);

                // Unregister client on disconnect.
                channel.closeFuture().addListener(close -> {
                    if (DEBUG) {
                        log.debug("Removing connection from server registry [address={}]", remoteAddress);
                    }

                    synchronized (mux) {
                        clients.remove(channel);
                    }
                });
            }
        }
    });

    ChannelFuture bindFuture = boot.bind(address);

    server = bindFuture.channel();

    bindFuture.addListener((ChannelFutureListener) bind -> {
        if (bind.isSuccess()) {
            synchronized (mux) {
                failoverInProgress = false;

                if (state == STARTING) {
                    state = STARTED;

                    // Updated since port can be automatically assigned by the underlying OS.
                    address = (InetSocketAddress) bind.channel().localAddress();

                    if (DEBUG) {
                        log.debug("Started [address={}]", address);
                    }

                    if (!startFuture.isDone() && callback != null) {
                        callback.onStart(this);
                    }

                    startFuture.complete(this);
                }
            }
        } else {
            mayBeRetry(bind.channel(), attempt, bind.cause());
        }
    });
}

From source file:io.hekate.network.netty.NetworkClientTest.java

License:Apache License

@Test
public void testTimeoutOnHandshake() throws Exception {
    CountDownLatch stopLatch = new CountDownLatch(1);
    AtomicReference<Throwable> error = new AtomicReference<>();

    NioEventLoopGroup serverGroup = new NioEventLoopGroup(2);

    Channel channel = null;//from   w  w  w  .  j  a va2 s.c o m

    try {
        // Prepare fake TCP server.
        ServerBootstrap bootstrap = new ServerBootstrap();

        bootstrap.group(serverGroup, serverGroup);
        bootstrap.channel(NioServerSocketChannel.class);
        bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                try {
                    // Hang on connect.
                    await(stopLatch);
                } catch (Throwable e) {
                    error.set(e);
                }
            }
        });

        InetSocketAddress addr = newNode().socket();

        channel = bootstrap.bind(addr).sync().channel();

        // Prepare client.
        NetworkClient<String> client = createClient(f -> f.setConnectTimeout(200));

        NetworkClientCallbackMock<String> callback = new NetworkClientCallbackMock<>();
        NetworkSendCallbackMock<String> messageCallback = new NetworkSendCallbackMock<>();

        sayTime("Connected", () -> {
            try {
                NetworkFuture<String> future = client.connect(addr, callback);

                client.send("one", messageCallback);
                client.send("two", messageCallback);
                client.send("three", messageCallback);

                get(future);

                fail("Error was expected");
            } catch (ExecutionException e) {
                assertTrue(e.getCause().toString(), ErrorUtils.isCausedBy(ConnectTimeoutException.class, e));
            }
        });

        callback.assertConnects(0);
        callback.assertErrors(1);

        messageCallback.awaitForErrors("one", "two", "three");

        callback.getErrors()
                .forEach(e -> assertTrue(e.toString(), e instanceof NetworkConnectTimeoutException));
    } finally {
        stopLatch.countDown();

        if (channel != null) {
            channel.close().await();
        }

        NettyUtils.shutdown(serverGroup).awaitUninterruptedly();

        assertNull(error.get());
    }
}

From source file:io.hydramq.network.server.HydraServerTransport.java

License:Open Source License

public CompletableFuture<Integer> start() {
    CompletableFuture<Integer> future = new CompletableFuture<>();
    try {// w w w  .j ava  2  s  . co m
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(boss);
        bootstrap.channel(NioServerSocketChannel.class);
        bootstrap.childHandler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(final Channel ch) throws Exception {
                ch.attr(ChannelAttributes.COMMAND_FUTURES).set(new ConcurrentHashMap<>());
                ch.pipeline().addLast("frameDecoder",
                        new LengthFieldBasedFrameDecoder(MAX_FRAME_LENGTH, 0, 4, 0, 4));
                ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(4));
                if (verbose) {
                    ch.pipeline().addLast(new LoggingHandler(HydraServerTransport.class, LogLevel.INFO));
                }
                ch.pipeline().addLast(ProtocolSelector.NAME, protocolSelector);
            }
        });
        channel = bootstrap.bind(port).sync().channel();
        future.complete(((InetSocketAddress) channel.localAddress()).getPort());
    } catch (InterruptedException ex) {
        future.completeExceptionally(ex);
    }
    return future;
}

From source file:io.jsync.http.impl.DefaultHttpServer.java

License:Open Source License

public HttpServer listen(int port, String host, final Handler<AsyncResult<HttpServer>> listenHandler) {
    if (requestHandler == null && wsHandler == null) {
        throw new IllegalStateException("Set request or websocket handler first");
    }/*from  www  .java 2s  . c  om*/
    if (listening) {
        throw new IllegalStateException("Listen already called");
    }
    listening = true;

    synchronized (async.sharedHttpServers()) {
        id = new ServerID(port, host);

        serverOrigin = (isSSL() ? "https" : "http") + "://" + host + ":" + port;

        DefaultHttpServer shared = async.sharedHttpServers().get(id);
        if (shared == null || port == 0) {
            serverChannelGroup = new DefaultChannelGroup("async-acceptor-channels",
                    GlobalEventExecutor.INSTANCE);
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(availableWorkers);
            bootstrap.channel(NioServerSocketChannel.class);
            tcpHelper.applyConnectionOptions(bootstrap);
            tcpHelper.checkSSL(async);
            bootstrap.childHandler(new ChannelInitializer<Channel>() {
                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    if (tcpHelper.isSSL()) {
                        pipeline.addLast("ssl", tcpHelper.createSslHandler(async, false));
                    }
                    pipeline.addLast("flashpolicy", new FlashPolicyHandler());
                    pipeline.addLast("httpDecoder", new HttpRequestDecoder(4096, 8192, 8192, false));
                    pipeline.addLast("httpEncoder", new AsyncHttpResponseEncoder());
                    if (compressionSupported) {
                        pipeline.addLast("deflater", new HttpChunkContentCompressor());
                    }
                    if (tcpHelper.isSSL() || compressionSupported) {
                        // only add ChunkedWriteHandler when SSL is enabled otherwise it is not needed as FileRegion is used.
                        pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); // For large file / sendfile support
                    }
                    pipeline.addLast("handler", new ServerHandler());
                }
            });

            addHandlers(this);
            try {
                bindFuture = bootstrap.bind(new InetSocketAddress(InetAddress.getByName(host), port));
                bindFuture.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture channelFuture) throws Exception {
                        if (!channelFuture.isSuccess()) {
                            async.sharedHttpServers().remove(id);
                        } else {
                            Channel channel = channelFuture.channel();
                            InetSocketAddress address = (InetSocketAddress) channel.localAddress();
                            DefaultHttpServer.this.actualPort = address.getPort();
                            serverChannelGroup.add(channel);
                        }
                    }
                });
            } catch (final Throwable t) {
                // Make sure we send the exception back through the handler (if any)
                if (listenHandler != null) {
                    async.runOnContext(new VoidHandler() {
                        @Override
                        protected void handle() {
                            listenHandler.handle(new DefaultFutureResult<HttpServer>(t));
                        }
                    });
                } else {
                    // No handler - log so user can see failure
                    actualCtx.reportException(t);
                }
                listening = false;
                return this;
            }
            async.sharedHttpServers().put(id, this);
            actualServer = this;
        } else {
            // Server already exists with that host/port - we will use that
            actualServer = shared;
            this.actualPort = shared.actualPort;
            addHandlers(actualServer);
        }
        actualServer.bindFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(final ChannelFuture future) throws Exception {
                if (listenHandler != null) {
                    final AsyncResult<HttpServer> res;
                    if (future.isSuccess()) {
                        res = new DefaultFutureResult<HttpServer>(DefaultHttpServer.this);
                    } else {
                        res = new DefaultFutureResult<>(future.cause());
                        listening = false;
                    }
                    actualCtx.execute(future.channel().eventLoop(), new Runnable() {
                        @Override
                        public void run() {
                            listenHandler.handle(res);
                        }
                    });
                } else if (!future.isSuccess()) {
                    listening = false;
                    // No handler - log so user can see failure
                    actualCtx.reportException(future.cause());
                }
            }
        });
    }
    return this;
}

From source file:io.jsync.net.impl.DefaultNetServer.java

License:Open Source License

public NetServer listen(final int port, final String host,
        final Handler<AsyncResult<NetServer>> listenHandler) {
    if (connectHandler == null) {
        throw new IllegalStateException("Set connect handler first");
    }/*from w  w  w. ja va2s.c  o m*/
    if (listening) {
        throw new IllegalStateException("Listen already called");
    }
    listening = true;
    this.host = host;

    synchronized (async.sharedNetServers()) {
        id = new ServerID(port, host);
        DefaultNetServer shared = (DefaultNetServer) async.sharedNetServers().get(id);
        if (shared == null || port == 0) { // Wildcard port will imply a new actual server each time
            serverChannelGroup = new DefaultChannelGroup("async-acceptor-channels",
                    GlobalEventExecutor.INSTANCE);

            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(availableWorkers);
            bootstrap.channel(NioServerSocketChannel.class);
            tcpHelper.checkSSL(async);

            bootstrap.childHandler(new ChannelInitializer<Channel>() {
                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    if (tcpHelper.isSSL()) {
                        SslHandler sslHandler = tcpHelper.createSslHandler(async, false);
                        pipeline.addLast("ssl", sslHandler);
                    }
                    if (tcpHelper.isSSL()) {
                        // only add ChunkedWriteHandler when SSL is enabled otherwise it is not needed as FileRegion is used.
                        pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); // For large file / sendfile support
                    }
                    pipeline.addLast("handler", new ServerHandler());
                }
            });

            tcpHelper.applyConnectionOptions(bootstrap);

            if (connectHandler != null) {
                // Share the event loop thread to also serve the NetServer's network traffic.
                handlerManager.addHandler(connectHandler, actualCtx);
            }

            try {
                InetSocketAddress addr = new InetSocketAddress(InetAddress.getByName(host), port);
                bindFuture = bootstrap.bind(addr).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        runListeners();
                    }
                });
                this.addListener(new Runnable() {
                    @Override
                    public void run() {
                        if (bindFuture.isSuccess()) {
                            log.trace("Net server listening on " + host + ":"
                                    + bindFuture.channel().localAddress());
                            // Update port to actual port - wildcard port 0 might have been used
                            DefaultNetServer.this.port = ((InetSocketAddress) bindFuture.channel()
                                    .localAddress()).getPort();
                            DefaultNetServer.this.id = new ServerID(DefaultNetServer.this.port, id.host);
                            async.sharedNetServers().put(id, DefaultNetServer.this);
                        } else {
                            async.sharedNetServers().remove(id);
                        }
                    }
                });
                serverChannelGroup.add(bindFuture.channel());
            } catch (final Throwable t) {
                // Make sure we send the exception back through the handler (if any)
                if (listenHandler != null) {
                    async.runOnContext(new VoidHandler() {
                        @Override
                        protected void handle() {
                            listenHandler.handle(new DefaultFutureResult<NetServer>(t));
                        }
                    });
                } else {
                    // No handler - log so user can see failure
                    actualCtx.reportException(t);
                }
                listening = false;
                return this;
            }
            if (port != 0) {
                async.sharedNetServers().put(id, this);
            }
            actualServer = this;
        } else {
            // Server already exists with that host/port - we will use that
            checkConfigs(actualServer, this);
            actualServer = shared;
            this.port = shared.port();
            if (connectHandler != null) {
                // Share the event loop thread to also serve the NetServer's network traffic.
                actualServer.handlerManager.addHandler(connectHandler, actualCtx);
            }
        }

        // just add it to the future so it gets notified once the bind is complete
        actualServer.addListener(new Runnable() {
            public void run() {
                if (listenHandler != null) {
                    final AsyncResult<NetServer> res;
                    if (actualServer.bindFuture.isSuccess()) {
                        res = new DefaultFutureResult<NetServer>(DefaultNetServer.this);
                    } else {
                        listening = false;
                        res = new DefaultFutureResult<>(actualServer.bindFuture.cause());
                    }
                    actualCtx.execute(actualServer.bindFuture.channel().eventLoop(), new Runnable() {
                        @Override
                        public void run() {
                            listenHandler.handle(res);
                        }
                    });
                } else if (!actualServer.bindFuture.isSuccess()) {
                    // No handler - log so user can see failure
                    actualCtx.reportException(actualServer.bindFuture.cause());
                    listening = false;
                }
            }
        });

    }
    return this;
}

From source file:io.mycat.netty.NettyServer.java

License:Apache License

private ServerBootstrap configServer() {
    bossGroup = new NioEventLoopGroup(args.bossThreads, new DefaultThreadFactory("NettyBossGroup", true));
    workerGroup = new NioEventLoopGroup(args.workerThreads, new DefaultThreadFactory("NettyWorkerGroup", true));
    userExecutor = createUserThreadExecutor();

    final ProtocolHandler handshakeHandler = newHandshakeHandler(userExecutor);
    final ProtocolHandler protocolHandler = newProtocolHandler(userExecutor);

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.TCP_NODELAY, true);

    if (args.socketTimeoutMills > 0) {
        b.childOption(ChannelOption.SO_TIMEOUT, args.socketTimeoutMills);
    }/*w  w  w.  ja  va 2 s  .  co m*/

    if (args.recvBuff > 0) {
        b.childOption(ChannelOption.SO_RCVBUF, args.recvBuff);
    }

    if (args.sendBuff > 0) {
        b.childOption(ChannelOption.SO_SNDBUF, args.sendBuff);
    }

    b.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(createProtocolDecoder(), /* createProtocolEncoder(), */ handshakeHandler,
                    protocolHandler);
        }
    });

    return b;
}

From source file:io.nebo.container.NettyEmbeddedServletContainer.java

License:Apache License

@Override
public void start() throws EmbeddedServletContainerException {
    ServerBootstrap b = new ServerBootstrap();
    groups(b);//from   w w w. ja v a2 s  .co m
    //        servletExecutor = new DefaultEventExecutorGroup(50);
    //        b.childHandler(new NettyEmbeddedServletInitializer(servletExecutor, context));
    b.childHandler(new ChannelInitializer() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(new DispatcherInbound(address, context));
        }
    });
    // Don't yet need the complexity of lifecycle state, listeners etc, so tell the context it's initialised here

    ChannelFuture future = b.bind(address).awaitUninterruptibly();
    //noinspection ThrowableResultOfMethodCallIgnored
    Throwable cause = future.cause();
    if (null != cause) {
        throw new EmbeddedServletContainerException("Could not start Netty server", cause);
    }
    logger.info(context.getServerInfo() + " started on port: " + getPort());
    context.setInitialised(true);
    context.addFilter(HessianConstant.HESSIAN_PATH, new HessianFilter(context));
    ServletNettyHttpSessionManager.start();
}

From source file:io.netty.example.mqtt.heartBeat.MqttHeartBeatBroker.java

License:Apache License

public static void main(String[] args) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {//from   ww  w. ja va  2 s. c o  m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup);
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.channel(NioServerSocketChannel.class);
        b.childHandler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast("encoder", MqttEncoder.INSTANCE);
                ch.pipeline().addLast("decoder", new MqttDecoder());
                ch.pipeline().addLast("heartBeatHandler", new IdleStateHandler(45, 0, 0, TimeUnit.SECONDS));
                ch.pipeline().addLast("handler", MqttHeartBeatBrokerHandler.INSTANCE);
            }
        });

        ChannelFuture f = b.bind(1883).sync();
        System.out.println("Broker initiated...");

        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}