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.juaby.labs.rpc.server.Rpc2Server.java

License:Apache License

public void start() {
    RpcThreadFactory threadName = new RpcThreadFactory("RPC-SVR-WORKER", false);
    int threads = Runtime.getRuntime().availableProcessors() * 2 + 1;
    bossGroup = new NioEventLoopGroup(threads, threadName);

    workerGroup = new NioEventLoopGroup();
    try {//from   ww  w. ja v  a  2 s. co  m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();

                        // Configure SSL.
                        final SslContext sslCtx;
                        if (SSL) {
                            SelfSignedCertificate ssc = new SelfSignedCertificate();
                            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
                        } else {
                            sslCtx = null;
                        }

                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc()));
                        }
                        p.addLast(
                                //output
                                new Rpc2ServerEncoder(),
                                //input
                                new Rpc2ServerDecoder(ServiceConfig.MAX_OBJECT_SIZE), new Rpc2ServerHandler());
                    }
                });

        // Bind and start to accept incoming connections.
        //b.bind(HOST, PORT).sync().channel().closeFuture().sync();
        b.bind(host, port);
    } finally {
    }
}

From source file:com.just.server.http.https.HttpsStaticFileServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(new FileInputStream("D:\\catest.key"), "catest".toCharArray());
    kmf.init(ks, "catest".toCharArray());
    sslCtx = SslContextBuilder.forServer(kmf).sslProvider(SslProvider.JDK).build();

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//from  www  .  ja  v a2  s.  c o m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new HttpStaticFileServerInitializer(sslCtx));

        Channel ch = b.bind(PORT).sync().channel();

        System.err.println("Open your web browser and navigate to " + "https" + "://127.0.0.1:" + PORT + '/');

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

From source file:com.khs.microservice.whirlpool.whirlpoolserver.WhirlpoolServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*w  ww.  j a  v  a 2  s  .  c o m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast("encoder", new HttpResponseEncoder());
                        p.addLast("decoder", new HttpRequestDecoder());
                        p.addLast("stringDecoder", new StringDecoder(CharsetUtil.UTF_8));
                        p.addLast("stringEncoder", new StringEncoder(CharsetUtil.UTF_8));
                        p.addLast("aggregator", new HttpObjectAggregator(65536));
                        p.addLast("handler", new WhirlpoolServerHandler());
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(PORT).sync();
        logger.info("Whirlpool Server started");

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        logger.info("Whirlpool Server shutdown started");
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
        logger.info("Whirlpool Server shutdown completed");
    }
}

From source file:com.khs.stockticker.StockTickerServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {// w ww. j a  v  a2 s . c  om
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast("encoder", new HttpResponseEncoder());
                        p.addLast("decoder", new HttpRequestDecoder());
                        p.addLast("aggregator", new HttpObjectAggregator(65536));
                        p.addLast("handler", new StockTickerServerHandler());
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(PORT).sync();
        logger.info("Ticket Symbol Server started");

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        logger.info("Ticket Symbol Server shutdown started");
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
        logger.info("Ticket Symbol Server shutdown completed");
    }
}

From source file:com.kingmed.dp.lisclient.demo.DiscardServer.java

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*ww  w .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(new DiscardServerHandler());
                    }
                }).option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.SO_KEEPALIVE, true);
        ChannelFuture f = b.bind(port).sync();
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}

From source file:com.kixeye.kixmpp.p2p.node.NodeServer.java

License:Apache License

public void initialize(final String host, final int port, final EventLoopGroup bossGroup,
        final EventLoopGroup workerGroup, final MessageRegistry messageRegistry,
        final ChannelInboundHandlerAdapter channelListener) {
    ServerBootstrap boot = new ServerBootstrap();
    boot.group(bossGroup, workerGroup);/*from w w  w . java 2  s  . c  o  m*/
    boot.channel(NioServerSocketChannel.class);
    boot.option(ChannelOption.SO_BACKLOG, 32);
    boot.childOption(ChannelOption.SO_KEEPALIVE, true);
    boot.childOption(ChannelOption.TCP_NODELAY, true);
    boot.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();

            //p.addLast(new LoggingHandler());

            // encoders
            p.addLast(new LengthFieldPrepender(4));
            p.addLast(new ProtostuffEncoder(messageRegistry));

            // decoders
            p.addLast(new LengthFieldBasedFrameDecoder(0x100000, 0, 4, 0, 4));
            p.addLast(new ProtostuffDecoder(messageRegistry));
            p.addLast(channelListener);
        }
    });

    // start accepting connection
    try {
        logger.info("Starting NodeServer on [{}]...", port);

        if (host == null) {
            acceptChannel = boot.bind(port).sync().channel();
        } else {
            acceptChannel = boot.bind(host, port).sync().channel();
        }

        logger.info("NodeServer listening on [{}]...", port);
    } catch (InterruptedException e) {
        logger.error("Binding to port {} failed", port, e);
    }

}

From source file:com.kixeye.kixmpp.server.KixmppServer.java

License:Apache License

/**
 * Creates a new {@link KixmppServer} with the given ssl engine.
 * //from w  w w  .j a  v a  2 s .  c  om
 * @param bindAddress
 * @param domain
 */
public KixmppServer(InetSocketAddress bindAddress, String domain, InetSocketAddress clusterAddress,
        NodeDiscovery clusterDiscovery, boolean useEpollIfAvailable) {
    if (useEpollIfAvailable && OS.indexOf("nux") >= 0) {
        this.bootstrap = new ServerBootstrap().group(new EpollEventLoopGroup(), new EpollEventLoopGroup())
                .channel(EpollServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new KixmppCodec());
                        ch.pipeline().addLast(new KixmppServerMessageHandler());
                    }
                });
    } else {
        this.bootstrap = new ServerBootstrap().group(new NioEventLoopGroup(), new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new KixmppCodec());
                        ch.pipeline().addLast(new KixmppServerMessageHandler());
                    }
                });
    }

    this.cluster = new ClusterClient(this, clusterAddress.getHostName(), clusterAddress.getPort(),
            clusterDiscovery, 300000, bootstrap.group());
    this.cluster.getMessageRegistry().addCustomMessage(1, RoomBroadcastTask.class);
    this.cluster.getMessageRegistry().addCustomMessage(2, RoomPresenceBroadcastTask.class);
    this.cluster.getMessageRegistry().addCustomMessage(3, PrivateChatTask.class);
    this.cluster.getMessageRegistry().addCustomMessage(4, GetMucRoomNicknamesRequest.class);
    this.cluster.getMessageRegistry().addCustomMessage(5, GetMucRoomNicknamesResponse.class);
    this.mapReduce = new MapReduceTracker(this, bootstrap.group());
    this.channels = new DefaultChannelGroup("All Channels", GlobalEventExecutor.INSTANCE);

    this.bindAddress = bindAddress;
    this.domain = domain.toLowerCase();
    this.eventEngine = new KixmppEventEngine();

    this.modulesToRegister.add(FeaturesKixmppServerModule.class.getName());
    this.modulesToRegister.add(SaslKixmppServerModule.class.getName());
    this.modulesToRegister.add(BindKixmppServerModule.class.getName());
    this.modulesToRegister.add(SessionKixmppServerModule.class.getName());
    this.modulesToRegister.add(PresenceKixmppServerModule.class.getName());
    this.modulesToRegister.add(MucKixmppServerModule.class.getName());
    this.modulesToRegister.add(RosterKixmppServerModule.class.getName());
    this.modulesToRegister.add(DiscoKixmppServerModule.class.getName());
    this.modulesToRegister.add(ChatKixmppServerModule.class.getName());
}

From source file:com.kixeye.kixmpp.server.KixmppServer.java

License:Apache License

/**
 * Enables the WebSocket port./*from w ww.  j a v a  2s.  com*/
 * 
 * @param webSocketAddress
 */
public KixmppServer enableWebSocket(InetSocketAddress webSocketAddress) {
    if (state.get() != State.STOPPED) {
        throw new IllegalStateException(
                String.format("The current state is [%s] but must be [STOPPED]", state.get()));
    }

    this.webSocketAddress = webSocketAddress;

    if (this.bootstrap.group() instanceof EpollEventLoopGroup
            && this.bootstrap.childGroup() instanceof EpollEventLoopGroup) {
        this.webSocketBootstrap = new ServerBootstrap()
                .group(this.bootstrap.group(), this.bootstrap.childGroup())
                .channel(EpollServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new HttpServerCodec());
                        ch.pipeline().addLast(new HttpObjectAggregator(65536));
                        ch.pipeline().addLast(new WebSocketServerHandler());
                        ch.pipeline().addLast(new KixmppWebSocketCodec());
                        ch.pipeline().addLast(new KixmppServerMessageHandler());
                    }
                });
    } else {
        this.webSocketBootstrap = new ServerBootstrap()
                .group(this.bootstrap.group(), this.bootstrap.childGroup())
                .channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new HttpServerCodec());
                        ch.pipeline().addLast(new HttpObjectAggregator(65536));
                        ch.pipeline().addLast(new WebSocketServerHandler());
                        ch.pipeline().addLast(new KixmppWebSocketCodec());
                        ch.pipeline().addLast(new KixmppServerMessageHandler());
                    }
                });
    }

    return this;
}

From source file:com.kradac.karview.netty.EchoServer.java

public void run() throws Exception {
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from  w  ww  .j a  v  a2  s  .c o m*/
        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 ReadTimeoutHandler(timeout * 60));
                        ch.pipeline().addLast(new MyDecoder());
                        ch.pipeline().addLast(new MyEncoder());
                        ch.pipeline().addLast(
                                //                                    new LoggingHandler(LogLevel.INFO),
                                new EchoServerHandler(t));
                    }
                });

        // Start the server.
        f = b.bind(port).sync();
        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.l2jmobius.commons.network.NetworkManager.java

License:Open Source License

public NetworkManager(EventLoopGroup bossGroup, EventLoopGroup workerGroup,
        ChannelInitializer<SocketChannel> clientInitializer, String host, int port) {
    // @formatter:off
    _serverBootstrap = new ServerBootstrap().group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(clientInitializer)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    // @formatter:on
    _host = host;/* w  ww.ja v  a  2  s .com*/
    _port = port;
}