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:be.mil.ChatServer.netty.server.TCPServer.java

License:Apache License

public void start() {

    EventLoopGroup producer = new NioEventLoopGroup();
    EventLoopGroup consumer = new NioEventLoopGroup();

    try {/*from w w  w  .  j av  a  2 s.c  o  m*/
        Bootstrap bootstrapClient = new Bootstrap().group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class).handler(new ClientAdapterInitializer());

        ServerBootstrap bootstrap = new ServerBootstrap().group(producer, consumer)
                .channel(NioServerSocketChannel.class).childHandler(serverAdapterInitializer);
        System.out.println("Server started");
        bootstrap.bind(port).sync().channel().closeFuture().sync();
        try {
            channel = bootstrapClient.connect(server, port).sync().channel();

            try {

                channel.write("Hi\n");
                channel.write("Hi\n");
                channel.flush();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {

                bootstrap.group().shutdownGracefully();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        producer.shutdownGracefully();
        consumer.shutdownGracefully();
    }

}

From source file:be.yildizgames.module.network.netty.server.ServerNetty.java

License:MIT License

/**
 * Create a new Netty server./* w  ww .j av a2  s . c  om*/
 *
 */
//@requires bootstrap != null.
//@requires port > 0 < 65535.
private ServerNetty() {
    super();

    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    this.bootstrap = new ServerBootstrap().group(bossGroup, workerGroup).channel(NioServerSocketChannel.class);
    this.bootstrap.option(ChannelOption.TCP_NODELAY, true);
    this.bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
}

From source file:bean.lee.demo.netty.learn.http.file.HttpStaticFileServer.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//from  ww  w. j a va  2 s  .  c om
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new HttpStaticFileServerInitializer());

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

From source file:bean.lee.demo.netty.learn.http.helloworld.HttpHelloWorldServer.java

License:Apache License

public void run() throws Exception {
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*  ww w  .j a va 2  s. c om*/
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new HttpHelloWorldServerInitializer());

        Channel ch = b.bind(port).sync().channel();
        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:bftsmart.communication.client.netty.NettyClientServerCommunicationSystemServerSide.java

License:Apache License

public NettyClientServerCommunicationSystemServerSide(ServerViewController controller) {
    try {//  ww  w.j av a 2  s  .c  o m

        this.controller = controller;
        /* Tulio Ribeiro */
        privKey = controller.getStaticConf().getPrivateKey();

        sessionReplicaToClient = new ConcurrentHashMap<>();
        rl = new ReentrantReadWriteLock();

        // Configure the server.

        serverPipelineFactory = new NettyServerPipelineFactory(this, sessionReplicaToClient, controller, rl);

        EventLoopGroup bossGroup = new NioEventLoopGroup(bossThreads);
        EventLoopGroup workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());

        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_SNDBUF, tcpSendBufferSize)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeoutMsec)
                .option(ChannelOption.SO_BACKLOG, connectionBacklog)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(serverPipelineFactory.getDecoder());
                        ch.pipeline().addLast(serverPipelineFactory.getEncoder());
                        ch.pipeline().addLast(serverPipelineFactory.getHandler());
                    }
                }).childOption(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.TCP_NODELAY, true);
        String myAddress;
        String confAddress = controller.getStaticConf()
                .getRemoteAddress(controller.getStaticConf().getProcessId()).getAddress().getHostAddress();

        if (InetAddress.getLoopbackAddress().getHostAddress().equals(confAddress)) {

            myAddress = InetAddress.getLoopbackAddress().getHostAddress();

        }

        else if (controller.getStaticConf().getBindAddress().equals("")) {

            myAddress = InetAddress.getLocalHost().getHostAddress();

            // If Netty binds to the loopback address, clients will not be able to connect
            // to replicas.
            // To solve that issue, we bind to the address supplied in config/hosts.config
            // instead.
            if (InetAddress.getLoopbackAddress().getHostAddress().equals(myAddress)
                    && !myAddress.equals(confAddress)) {

                myAddress = confAddress;
            }

        } else {

            myAddress = controller.getStaticConf().getBindAddress();
        }

        int myPort = controller.getStaticConf().getPort(controller.getStaticConf().getProcessId());

        ChannelFuture f = b.bind(new InetSocketAddress(myAddress, myPort)).sync();

        logger.info("ID = " + controller.getStaticConf().getProcessId());
        logger.info("N = " + controller.getCurrentViewN());
        logger.info("F = " + controller.getCurrentViewF());
        logger.info("Port (client <-> server) = "
                + controller.getStaticConf().getPort(controller.getStaticConf().getProcessId()));
        logger.info("Port (server <-> server) = "
                + controller.getStaticConf().getServerToServerPort(controller.getStaticConf().getProcessId()));
        logger.info("requestTimeout = " + controller.getStaticConf().getRequestTimeout());
        logger.info("maxBatch = " + controller.getStaticConf().getMaxBatchSize());
        if (controller.getStaticConf().getUseSignatures() == 1)
            logger.info("Using Signatures");
        else if (controller.getStaticConf().getUseSignatures() == 2)
            logger.info("Using benchmark signature verification");
        logger.info("Binded replica to IP address " + myAddress);
        // ******* EDUARDO END **************//

        /* Tulio Ribeiro */
        // SSL/TLS
        logger.info("SSL/TLS enabled, protocol version: {}",
                controller.getStaticConf().getSSLTLSProtocolVersion());

        /* Tulio Ribeiro END */

        mainChannel = f.channel();

    } catch (InterruptedException | UnknownHostException ex) {
        logger.error("Failed to create Netty communication system", ex);
    }
}

From source file:blazingcache.network.netty.NettyChannelAcceptor.java

License:Apache License

public void start() throws Exception {
    if (ssl) {/*from  w ww .j av a2s  .c  o  m*/
        if (sslCertFile == null) {
            LOGGER.log(Level.SEVERE, "start SSL with self-signed auto-generated certificate");
            if (sslCiphers != null) {
                LOGGER.log(Level.SEVERE, "required sslCiphers " + sslCiphers);
            }
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            try {
                sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).ciphers(sslCiphers)
                        .build();
            } finally {
                ssc.delete();
            }
        } else {
            LOGGER.log(Level.SEVERE, "start SSL with certificate " + sslCertFile.getAbsolutePath()
                    + " chain file " + sslCertChainFile.getAbsolutePath());
            if (sslCiphers != null) {
                LOGGER.log(Level.SEVERE, "required sslCiphers " + sslCiphers);
            }
            sslCtx = SslContextBuilder.forServer(sslCertChainFile, sslCertFile, sslCertPassword)
                    .ciphers(sslCiphers).build();
        }

    }
    if (callbackThreads == 0) {
        callbackExecutor = Executors.newCachedThreadPool();
    } else {
        callbackExecutor = Executors.newFixedThreadPool(callbackThreads, new ThreadFactory() {
            private final AtomicLong count = new AtomicLong();

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "blazingcache-callbacks-" + count.incrementAndGet());
            }
        });
    }
    bossGroup = new NioEventLoopGroup(workerThreads);
    workerGroup = new NioEventLoopGroup(workerThreads);
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    NettyChannel session = new NettyChannel("unnamed", ch, callbackExecutor, null);
                    if (acceptor != null) {
                        acceptor.createConnection(session);
                    }

                    //                        ch.pipeline().addLast(new LoggingHandler());
                    // Add SSL handler first to encrypt and decrypt everything.
                    if (ssl) {
                        ch.pipeline().addLast(sslCtx.newHandler(ch.alloc()));
                    }

                    ch.pipeline().addLast("lengthprepender", new LengthFieldPrepender(4));
                    ch.pipeline().addLast("lengthbaseddecoder",
                            new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                    //
                    ch.pipeline().addLast("messageencoder", new DataMessageEncoder());
                    ch.pipeline().addLast("messagedecoder", new DataMessageDecoder());
                    ch.pipeline().addLast(new InboundMessageHandler(session));
                }
            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

    ChannelFuture f = b.bind(host, port).sync(); // (7)
    this.channel = f.channel();

}

From source file:book.netty.n4delimiterC5P1.EchoServer.java

License:Apache License

public void bind(int port) throws Exception {
    // ??NIO/* w ww. ja v  a2 s .  c o m*/
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
                        ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new EchoServerHandler());
                    }
                });

        // ???
        ChannelFuture f = b.bind(port).sync();

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

From source file:book.netty.n5fixedLenC5P2.EchoServer.java

License:Apache License

public void bind(int port) throws Exception {
    // ??NIO/*from  www  . j av a 2 s  .  c  o m*/
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new FixedLengthFrameDecoder(20));
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new EchoServerHandler());
                    }
                });

        // ???
        ChannelFuture f = b.bind(port).sync();

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

From source file:books.netty.codec.marshalling.SubReqServer.java

License:Apache License

public void bind(int port) throws Exception {
    // ??NIO//from w w w. j a v  a  2s  .c  om
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) {
                        ch.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
                        ch.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
                        ch.pipeline().addLast(new SubReqServerHandler());
                    }
                });

        // ???
        ChannelFuture f = b.bind(port).sync();

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

From source file:books.netty.codec.protobuf.SubReqServer.java

License:Apache License

public void bind(int port) throws Exception {
    // ??NIO//from   www  .  ja  v  a  2  s.c  om
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) {
                        ch.pipeline().addLast(new ProtobufVarint32FrameDecoder());
                        ch.pipeline().addLast(
                                new ProtobufDecoder(SubscribeReqProto.SubscribeReq.getDefaultInstance()));
                        ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
                        ch.pipeline().addLast(new ProtobufEncoder());
                        ch.pipeline().addLast(new SubReqServerHandler());
                    }
                });

        // ???
        ChannelFuture f = b.bind(port).sync();

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