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.nitesh.netty.snoop.server.HttpSnoopServer.java

License:Apache License

public void run() throws Exception {
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*  w ww . j  av  a 2s .c o  m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new HttpSnoopServerInitializer());

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

From source file:com.nus.mazegame.server.GameServer.java

public static void init(int port, int x, int y, int treasure, boolean isSlave) throws Exception {
    GameService.gameService = new GameService(x, y, treasure, isSlave);

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//from  ww  w .  j a v a 2  s .  c om
        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();
                        // Decoders
                        p.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4));
                        p.addLast("bytesDecoder", new ByteArrayDecoder());

                        // Encoder
                        p.addLast("frameEncoder", new LengthFieldPrepender(4));
                        p.addLast("bytesEncoder", new ByteArrayEncoder());
                        // p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new GameServerHandler());
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(port).sync();
        Logger.getLogger(GameServerHandler.class.getName()).log(Level.INFO, "Server started...");
        // 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.ogarproject.ogar.server.net.NetworkManager.java

License:Open Source License

public void start() throws IOException, InterruptedException {
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ClientInitializer(server));

    channel = b.bind(server.getConfig().server.port).sync().channel();

    OgarServer.log.info("Server started on port " + server.getConfig().server.port + ".");
}

From source file:com.onion.worker.WorkerDataServer.java

License:Apache License

private ServerBootstrap createServerBootstrap() {
    final ServerBootstrap boot = new ServerBootstrap();
    // If number of worker threads is 0, Netty creates (#processors * 2) threads by default.
    final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    final EventLoopGroup workerGroup = new NioEventLoopGroup(0);
    boot.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class);

    // use pooled buffers
    boot.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    boot.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    // set write buffer
    // this is the default, but its recommended to set it in case of change in future netty.
    boot.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32768);
    boot.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8192);

    return boot;//from  w w  w  .ja va  2s . co  m
}

From source file:com.openddal.server.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();
    Authenticator authenticator = createAuthenticator();
    ProcessorFactory processorFactory = createProcessorFactory();
    RequestFactory requestFactory = createRequestFactory();
    ResponseFactory responseFactory = createResponseFactory();
    final ProtocolHandler protocolHandler = new ProtocolHandler(authenticator, processorFactory, requestFactory,
            responseFactory, 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  ww.jav a 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(), */ protocolHandler);
        }
    });

    return b;
}

From source file:com.opentable.logging.RedisServerRule.java

License:Apache License

@Override
protected void before() throws Throwable {
    try (ServerSocket ss = new ServerSocket(0)) {
        port = ss.getLocalPort();//from   w ww. j  a  v a2  s .  c  om
    }

    // Only execute the command handler in a single thread
    final RedisCommandHandler commandHandler = new RedisCommandHandler(new SimpleRedisServer());

    b = new ServerBootstrap();
    group = new DefaultEventExecutorGroup(1);
    b.group(new NioEventLoopGroup(), new NioEventLoopGroup()).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 100).localAddress(port)
            .childOption(ChannelOption.TCP_NODELAY, true).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    //                 p.addLast(new ByteLoggingHandler(LogLevel.INFO));
                    p.addLast(new RedisCommandDecoder());
                    p.addLast(new RedisReplyEncoder());
                    p.addLast(group, commandHandler);
                }
            });

    // Start the server.
    b.bind().sync();
}

From source file:com.ottogroup.bi.asap.server.emitter.websocket.WebSocketServer.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  .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 WebSocketServerInitializer());

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

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

}

From source file:com.ottogroup.bi.spqr.websocket.server.SPQRWebSocketServer.java

License:Apache License

/**
 * Initializes and executes the server components. Although the other {@link SPQRWebSocketServer#run(String)}
 * could do the same work this one allows better testing as the {@link InputStream} parameter allows
 * to inject a variable which may be controlled much better. In the case it would be necessary to 
 * provide a reference to a temporary file which is controlled by the use case ... somehow too much work ;-)
 * This one is easier.  //from  w  ww  .j a  v  a  2 s  .  com
 * @param configurationFileStream stream holding configuration file content
 * @throws IOException
 * @throws InterruptedException 
 */
protected void run(final InputStream configurationFileStream) throws IOException, InterruptedException {

    ///////////////////////////////////////////////////////////////////
    // parse out configuration from provided input stream
    ObjectMapper jsonMapper = new ObjectMapper();
    SPQRWebSocketServerConfiguration cfg = jsonMapper.readValue(configurationFileStream,
            SPQRWebSocketServerConfiguration.class);
    //
    ///////////////////////////////////////////////////////////////////

    PropertyConfigurator.configure(cfg.getLog4jConfigurationFile());

    EventLoopGroup bossGroup = new NioEventLoopGroup(cfg.getBossEventGroupThreads());
    EventLoopGroup workerGroup = new NioEventLoopGroup(cfg.getWorkerEventGroupThreads());

    logger.info(
            "websocket server [port=" + cfg.getPort() + ", bossGroupThreads=" + cfg.getBossEventGroupThreads()
                    + ", workerGroupThreads=" + cfg.getWorkerEventGroupThreads() + "]");

    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new SPQRWebSocketServerInitializer());

        Channel channel = bootstrap.bind(cfg.getPort()).sync().channel();
        channel.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.outbrain.pajamasproxy.memcached.server.MemCacheDaemon.java

License:Apache License

private void createBootstratp() {
    log.info("Initializing TCP...");
    ServerBootstrap tcpBootstrap = new ServerBootstrap();
    tcpBootstrap.group(eventLoopGroup);//  w w w  . jav  a2  s.  c o m
    tcpBootstrap.channel(NioServerSocketChannel.class);
    tcpBootstrap.childHandler(serverPipelineFactory);

    final ChannelFuture channelFuture = tcpBootstrap.bind(addr).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            log.info("Server started; listening to {}", addr);
            running = true;
        }
    });
}

From source file:com.papteco.client.netty.OpenFileServerBuilder.java

License:Apache License

public void run() {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from   www .j  a  v  a  2  s  . co m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ObjectEncoder(),
                                new NewObjectDecoder(ClassResolvers.cacheDisabled(null)),
                                new OpenFileServerHandler());
                    }
                });

        // Bind and start to accept incoming connections.
        b.bind(PortTranslater(envsetting.getProperty("open_file_port"))).sync().channel().closeFuture().sync();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}