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:cc.sharper.netty.TimeServer.java

License:Apache License

public void bind(int port) throws Exception {
    // ??NIO SocketChannel
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//from w w  w. j a  v a2  s  .co  m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024).childHandler(new ChildChannelHandler());//io
        // ???
        ChannelFuture f = b.bind(port).sync();

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

From source file:cf.component.http.SimpleHttpServer.java

License:Open Source License

private void bootstrapServer(SocketAddress localAddress, NioEventLoopGroup parentGroup,
        NioEventLoopGroup childGroup) {/*from  w w w .j  a v a  2  s  .c o m*/
    new ServerBootstrap().group(parentGroup, childGroup).channel(NioServerSocketChannel.class)
            .localAddress(localAddress).childHandler(new SimpleHttpServerInitializer()).bind()
            .awaitUninterruptibly(); // Make sure the server is bound before the constructor returns.

    LOGGER.info("Server listening on {}", localAddress);
}

From source file:ch.ethz.globis.distindex.middleware.net.IndexMiddleware.java

License:Open Source License

private ServerBootstrap initServerBootstrap(final IOHandler<K, V> handler) {
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/*from   ww  w .j ava 2 s  .c o  m*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new MiddlewareMessageDecoder(),
                            new MiddlewareChannelHandler<K, V>(handler) {
                            });
                }
            });
    return b;
}

From source file:chapter10.WebSocketServer.java

License:Apache License

public void run(int port) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/* w  w w  .j  ava2s  .  co  m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast("http-codec", new HttpServerCodec());
                        pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
                        ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
                        pipeline.addLast("handler", new WebSocketServerHandler());
                    }
                });

        Channel ch = b.bind(port).sync().channel();
        System.out.println("Web socket server started at port " + port + '.');
        System.out.println("Open your browser and navigate to http://localhost:" + port + '/');

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

From source file:ChatServer.ChatServer.java

public void run() {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {/*from   w  w  w  . j  a va2 s .c o  m*/
        ServerBootstrap bootstrap = new ServerBootstrap().group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class).childHandler(new ChatServerInitializer());

        bootstrap.bind(port).channel().closeFuture().sync();
    } catch (InterruptedException ex) {
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:cloudeventbus.cli.Server.java

License:Open Source License

public static void main(String[] args) throws Exception {
    final JCommander commander = new JCommander();

    final Options options = new Options();
    commander.addObject(options);//from  w  ww .  jav a  2 s.co  m

    commander.setProgramName("eventbus-server");

    try {
        commander.parse(args);

        DefaultOptions.setLogLevel(options);

        TrustStore trustStore = CertificateUtils.loadTrustStore(options.trustStore);
        if (trustStore != null && trustStore.size() > 0) {
            System.out.println("Using trust store at: " + options.trustStore);
        } else {
            trustStore = null;
        }

        final int port = options.port;

        final CertificateChain certificateChain;
        final PrivateKey privateKey;
        if (options.certificate == null) {
            certificateChain = null;
            privateKey = null;
        } else {
            certificateChain = CertificateUtils.loadCertificateChain(options.certificate);
            System.out.println("Using certificate at: " + options.certificate);
            if (options.privateKey == null) {
                System.err.print("You must specify a private key when using a certificate.");
                System.exit(1);
                return;
            } else {
                privateKey = CertificateUtils.loadPrivateKey(options.privateKey);
                System.out.println("Using private key at: " + options.privateKey);
            }
        }

        final NioEventLoopGroup parentGroup = new NioEventLoopGroup();
        final GlobalHub globalHub = new GlobalHub();
        final ServerConfig serverConfig = new ServerConfig(port, "cloudeventbus-simple-server", trustStore,
                certificateChain, privateKey);
        final ClusterManager clusterManager = new ClusterManager(serverConfig, globalHub, parentGroup);
        if (options.peers != null) {
            for (String peer : options.peers) {
                final String[] parts = peer.split(":");
                if (parts.length != 2) {
                    throw new IllegalArgumentException(
                            "Invalid peer address " + peer + " should be HOST:PORT (e.g. 127.0.0.1:4223)");
                }
                clusterManager.registerPeer(new InetSocketAddress(parts[0], Integer.valueOf(parts[1])));
            }
        }
        new ServerBootstrap().group(parentGroup, new NioEventLoopGroup()).channel(NioServerSocketChannel.class)
                .localAddress(new InetSocketAddress(port))
                .childHandler(new ServerChannelInitializer(serverConfig, clusterManager, globalHub)).bind()
                .awaitUninterruptibly();
        System.out.println("Server listening on port " + port);
    } catch (ParameterException e) {
        System.err.println(e.getMessage());
        commander.usage();
        System.exit(1);
    }
}

From source file:cloudfoundry.norouter.f5.dropsonde.LineEventToMetronServer.java

License:Open Source License

@Autowired
public LineEventToMetronServer(@Qualifier("boss") EventLoopGroup boss,
        @Qualifier("worker") EventLoopGroup worker, RouteRegistrar routeRegistrar, MetronClient metronClient,
        F5Properties properties) {
    final ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(boss, worker).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/* w  ww.  j  a va  2 s .com*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new LineBasedFrameDecoder(64 * 1024));
                    ch.pipeline().addLast(new LineEventDecoder());
                    ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
                                throws Exception {
                            LOGGER.warn("An error occurred processing logging events from the LTM.", cause);
                            ctx.close();
                        }

                        @Override
                        public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
                            LOGGER.info("New connection from {}", ctx.channel().remoteAddress());
                        }

                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            if (msg instanceof LogEvent) {
                                final LogEvent logEvent = (LogEvent) msg;
                                final RouteDetails routeDetails = routeRegistrar
                                        .getRouteByAddress(logEvent.getApplicationAddress());
                                if (routeDetails != null && routeDetails.getApplicationGuid() != null) {
                                    final String appGuid = routeDetails.getApplicationGuid().toString();
                                    final String message = logEvent.getMessage() + " app_id:" + appGuid;
                                    metronClient.createLogEmitter("RTR", logEvent.getLtmIdentifier())
                                            .emit(logEvent.getTimestamp(), appGuid, message);
                                }
                            } else {
                                super.channelRead(ctx, msg);
                            }
                        }
                    });
                }
            });
    bootstrap.bind(properties.getLoggingPort()).syncUninterruptibly();
    LOGGER.info("Listening for logging events from the LTM on port {}", properties.getLoggingPort());
}

From source file:club.jmint.crossing.server.CrossingServer.java

License:Apache License

public void start() {
    //load configuration
    //ConfigWizard cw = (ConfigWizard)WizardManager.getWizard("ConfigWizard");
    ServerConfig config = (ServerConfig) ConfigWizard.getConfig(Constants.CONFIG_SERVER);
    this.address = config.getItem("server.bind_address");
    this.port = Integer.parseInt(config.getItem("server.port"));
    this.backlog = Integer.parseInt(config.getItem("server.backlog"));
    this.ssl = Boolean.parseBoolean(config.getItem("server.ssl"));

    //Configure SSL
    if (ssl) {// w ww. j  ava  2  s.  c  om
        try {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
        } catch (Exception e) {
            CrossLog.printStackTrace(e);
        }
    } else {
        sslCtx = null;
    }

    //Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, backlog).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ServerChannelInitializer(sslCtx));

        // Start the server.
        ChannelFuture f = b.bind(port).sync();
        CrossLog.logger.info("Crossing Server started......");

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();

    } catch (InterruptedException e) {
        CrossLog.printStackTrace(e);
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
        CrossLog.logger.info("Crossing Server shutdown......");
    }
}

From source file:cn.david.main.EchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from  ww w .jav a 2 s.c o  m*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    } else {
        sslCtx = null;
    }

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    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 {
                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc()));
                        }
                        //p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new EchoServerHandler());
                    }
                });

        // Start the server.
        ChannelFuture 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:cn.david.main.PersonServer.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.ja v  a  2  s. co m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ServerInitializer());

        // Start the server.
        ChannelFuture 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();
    }
}