Example usage for io.netty.bootstrap ServerBootstrap ServerBootstrap

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

Introduction

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

Prototype

public ServerBootstrap() 

Source Link

Usage

From source file:com.flysoloing.learning.network.netty.telnet.TelnetServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from   w  w w.  j  av a 2  s .  c om*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new TelnetServerInitializer(sslCtx));

        b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.flysoloing.learning.network.netty.udt.echo.bytes.ByteEchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    final ThreadFactory acceptFactory = new DefaultThreadFactory("accept");
    final ThreadFactory connectFactory = new DefaultThreadFactory("connect");
    final NioEventLoopGroup acceptGroup = new NioEventLoopGroup(1, acceptFactory, NioUdtProvider.BYTE_PROVIDER);
    final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1, connectFactory,
            NioUdtProvider.BYTE_PROVIDER);

    // Configure the server.
    try {//from w ww  .j  a va 2s.  com
        final ServerBootstrap boot = new ServerBootstrap();
        boot.group(acceptGroup, connectGroup).channelFactory(NioUdtProvider.BYTE_ACCEPTOR)
                .option(ChannelOption.SO_BACKLOG, 10).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<UdtChannel>() {
                    @Override
                    public void initChannel(final UdtChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new ByteEchoServerHandler());
                    }
                });
        // Start the server.
        final ChannelFuture future = boot.bind(PORT).sync();
        // Wait until the server socket is closed.
        future.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        acceptGroup.shutdownGracefully();
        connectGroup.shutdownGracefully();
    }
}

From source file:com.flysoloing.learning.network.netty.udt.echo.message.MsgEchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    final ThreadFactory acceptFactory = new DefaultThreadFactory("accept");
    final ThreadFactory connectFactory = new DefaultThreadFactory("connect");
    final NioEventLoopGroup acceptGroup = new NioEventLoopGroup(1, acceptFactory,
            NioUdtProvider.MESSAGE_PROVIDER);
    final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1, connectFactory,
            NioUdtProvider.MESSAGE_PROVIDER);

    // Configure the server.
    try {//from w w  w  . j  av a2s.c o  m
        final ServerBootstrap boot = new ServerBootstrap();
        boot.group(acceptGroup, connectGroup).channelFactory(NioUdtProvider.MESSAGE_ACCEPTOR)
                .option(ChannelOption.SO_BACKLOG, 10).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<UdtChannel>() {
                    @Override
                    public void initChannel(final UdtChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new MsgEchoServerHandler());
                    }
                });
        // Start the server.
        final ChannelFuture future = boot.bind(PORT).sync();
        // Wait until the server socket is closed.
        future.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        acceptGroup.shutdownGracefully();
        connectGroup.shutdownGracefully();
    }
}

From source file:com.flysoloing.learning.network.netty.worldclock.WorldClockServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from  w  w  w  .  j av a2 s.c  om*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new WorldClockServerInitializer(sslCtx));

        b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.foilen.smalltools.net.netty.NettyServer.java

License:Open Source License

/**
 * Start the server.//w ww. j  av a  2 s  . c o m
 *
 * @param port
 *            the port to listen on (0 for a random port ; get it with {@link #getPort()})
 * @param trustedCertificates
 *            (optional) the certificate to trust connections from
 * @param certificate
 *            (optional) the server's certificate
 * @param channelHandlerContainers
 *            the channel handlers for the incoming connections
 */
public void start(final int port, final RSATrustedCertificates trustedCertificates,
        final RSACertificate certificate, final List<ChannelHandlerContainer> channelHandlerContainers) {

    AssertTools.assertNull(thread, "Server is already started");

    final CountDownLatch countDownLatch = new CountDownLatch(1);
    thread = new Thread(() -> {
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(NettyCommon.EVENT_LOOP_GROUP, NettyCommon.EVENT_LOOP_GROUP);
            serverBootstrap.channel(NioServerSocketChannel.class);

            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {

                    InetSocketAddress remoteAddress = socketChannel.remoteAddress();
                    logger.info("Got a connection from {}:{}", remoteAddress.getHostName(),
                            remoteAddress.getPort());

                    // Add sslCtx if needed
                    if (trustedCertificates != null || certificate != null) {
                        TrustManagerFactory trustManagerFactory = trustedCertificates == null ? null
                                : RSATools.createTrustManagerFactory(trustedCertificates);
                        KeyManagerFactory keyManagerFactory = certificate == null ? null
                                : RSATools.createKeyManagerFactory(certificate);

                        CipherSuiteFilter cipherFilter = IdentityCipherSuiteFilter.INSTANCE;
                        SslContext sslCtx = SslContext.newServerContext(SslProvider.JDK, null,
                                trustManagerFactory, null, null, null, keyManagerFactory, null, cipherFilter,
                                null, 0, 0);
                        SslHandler sslHandler = sslCtx.newHandler(socketChannel.alloc());

                        if (trustManagerFactory == null) {
                            logger.debug("Will not verify client's identity");
                        } else {
                            logger.debug("Will verify client's identity");
                            SSLEngine sslEngine = sslHandler.engine();
                            sslEngine.setNeedClientAuth(true);
                        }

                        socketChannel.pipeline().addLast(sslHandler);
                    }

                    // Add the channel handlers
                    for (ChannelHandlerContainer channelHandlerContainer : channelHandlerContainers) {
                        socketChannel.pipeline()
                                .addLast(ReflectionTools.instantiate(
                                        channelHandlerContainer.getChannelHandlerClass(),
                                        channelHandlerContainer.getConstructorParams()));
                    }
                }
            }) //
                    .option(ChannelOption.SO_BACKLOG, 128) //
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            bindedPort = port;
            logger.info("Server on port {} is starting...", port);
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            SocketAddress socketAddress = channelFuture.channel().localAddress();
            if (socketAddress instanceof InetSocketAddress) {
                InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
                bindedPort = inetSocketAddress.getPort();
            }
            logger.info("Server on port {} is started", bindedPort);
            countDownLatch.countDown();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            logger.info("Server on port {} is interrupted", bindedPort);
        } finally {
            countDownLatch.countDown();
        }
        logger.info("Server on port {} is stopped", bindedPort);
    });
    thread.setName("Netty Server-" + bindedPort);
    thread.start();

    try {
        countDownLatch.await();
    } catch (InterruptedException e) {
        logger.error("Interrupted while waiting for the server to start");
    }
}

From source file:com.frank.netty.protocol.http.fileServer.HttpFileServer.java

License:Apache License

public void run(final int port, final String url) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*  w ww. j a va  2s  .  c  o m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast("http-decoder", new HttpRequestDecoder());
                        ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536));
                        ch.pipeline().addLast("http-encoder", new HttpResponseEncoder());
                        ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
                        ch.pipeline().addLast("fileServerHandler", new HttpFileServerHandler(url));
                    }
                });
        ChannelFuture future = b.bind("192.168.1.102", port).sync();
        System.out.println(
                "HTTP??? : " + "http://192.168.1.102:" + port + url);
        future.channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.friz.audio.AudioServer.java

License:Open Source License

@Override
public void initialize() {
    group = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());
    bootstrap = new ServerBootstrap();

    AudioServer s = this;

    bootstrap.group(group).channel(NioServerSocketChannel.class)
            //.handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<NioSocketChannel>() {

                @Override/*from   w w  w. j  av  a 2  s.  c  o m*/
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(HttpServerCodec.class.getName(), new HttpServerCodec());
                    p.addLast(HttpObjectAggregator.class.getName(), new HttpObjectAggregator(65536));
                    p.addLast(ChunkedWriteHandler.class.getName(), new ChunkedWriteHandler());
                    p.addLast(AudioChannelHandler.class.getName(), new AudioChannelHandler(s));
                }

            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.TCP_NODELAY, true);

    hub.listen(AudioRequestEvent.class, new AudioRequestEventListener());

    service.startAsync();
}

From source file:com.friz.game.GameServer.java

License:Open Source License

@Override
public void initialize() {
    group = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());
    bootstrap = new ServerBootstrap();

    GameServer s = this;

    bootstrap.group(group).channel(NioServerSocketChannel.class)
            //.handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<NioSocketChannel>() {

                @Override/*from   www  . j  a  v  a 2s  . c  o  m*/
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(LoginInitEncoder.class.getName(), new LoginInitEncoder());
                    p.addLast(LoginInitDecoder.class.getName(), new LoginInitDecoder());
                    p.addLast(GameChannelHandler.class.getName(), new GameChannelHandler(s));
                }

            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.TCP_NODELAY, true);
}

From source file:com.friz.lobby.LobbyServer.java

License:Open Source License

@Override
public void initialize() {
    group = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());
    bootstrap = new ServerBootstrap();

    LobbyServer s = this;

    bootstrap.group(group).channel(NioServerSocketChannel.class)
            //.handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<NioSocketChannel>() {

                @Override//from w w w .ja v  a 2  s  .c  o  m
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(LobbyInitEncoder.class.getName(), new LobbyInitEncoder());
                    p.addLast(LobbyInitDecoder.class.getName(), new LobbyInitDecoder());
                    p.addLast(LobbyChannelHandler.class.getName(), new LobbyChannelHandler(s));
                }

            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.TCP_NODELAY, true);

    eventHub.listen(LobbyInitRequestEvent.class, new LobbyInitEventListener());
    eventHub.listen(SocialInitRequestEvent.class, new SocialInitEventListener());
    eventHub.listen(CreationRequestEvent.class, new CreationEventListener());
    eventHub.listen(LoginRequestEvent.class, new LoginRequestEventListener());

    moduleHub.listen(ClientVersionModule.class, new ClientVersionModuleListener());
    moduleHub.listen(ClientTypeModule.class, new ClientTypeModuleListener());
}

From source file:com.friz.login.LoginServer.java

License:Open Source License

@Override
public void initialize() {
    group = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());
    bootstrap = new ServerBootstrap();

    LoginServer s = this;

    bootstrap.group(group).channel(NioServerSocketChannel.class)
            //.handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<NioSocketChannel>() {

                @Override/* ww w  . j av  a 2s .c  om*/
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(IdleStateHandler.class.getName(), new IdleStateHandler(15, 0, 0));
                    p.addLast(LoginChannelHandler.class.getName(), new LoginChannelHandler(s));
                }

            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.TCP_NODELAY, true);
}