Example usage for io.netty.bootstrap ServerBootstrap group

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

Introduction

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

Prototype

public ServerBootstrap group(EventLoopGroup parentGroup, EventLoopGroup childGroup) 

Source Link

Document

Set the EventLoopGroup for the parent (acceptor) and the child (client).

Usage

From source file:com.srotya.sidewinder.core.ingress.binary.NettyBinaryIngestionServer.java

License:Apache License

public void start() throws InterruptedException {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup(4);

    ServerBootstrap bs = new ServerBootstrap();
    channel = bs.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_RCVBUF, 10485760).option(ChannelOption.SO_SNDBUF, 10485760)
            .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ChannelInitializer<SocketChannel>() {

                @Override/*from  w w  w  .j av a  2  s . c o  m*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new LengthFieldBasedFrameDecoder(3000, 0, 4, 0, 4));
                    p.addLast(new SeriesDataPointDecoder());
                    p.addLast(new SeriesDataPointWriter(storageEngine));
                }

            }).bind("localhost", 9927).sync().channel();
}

From source file:com.srotya.sidewinder.core.ingress.http.NettyHTTPIngestionServer.java

License:Apache License

public void start() throws InterruptedException {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup(4);

    ServerBootstrap bs = new ServerBootstrap();
    channel = bs.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_RCVBUF, 10485760).option(ChannelOption.SO_SNDBUF, 10485760)
            .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ChannelInitializer<SocketChannel>() {

                @Override//  ww  w.  j a  v a2s.c om
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new HttpRequestDecoder());
                    p.addLast(new HttpResponseEncoder());
                    p.addLast(new HTTPDataPointDecoder(storageEngine));
                }

            }).bind("localhost", 9928).sync().channel();
}

From source file:com.streamsets.pipeline.stage.origin.tcp.TCPConsumingServer.java

License:Apache License

@Override
protected AbstractBootstrap bootstrap(boolean enableEpoll) {
    if (enableEpoll) {
        enableDirectBuffers();/*ww w. jav  a  2  s .  c  om*/
        // boss group simply opens channels and hands processing off to the child
        EpollEventLoopGroup bossGroup = new EpollEventLoopGroup(NUM_BOSS_THREADS);
        EventLoopGroup workerGroup = new EpollEventLoopGroup(numThreads);
        groups.add(bossGroup);
        groups.add(workerGroup);
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(EpollServerSocketChannel.class)
                .childHandler(this.channelInitializer)
                .option(ChannelOption.SO_BACKLOG, SOCKET_MAX_INBOUND_CONNECTION_QUEUE_DEPTH)
                .childOption(ChannelOption.SO_KEEPALIVE, SOCKET_KEEPALIVE);
        return b;
    } else {
        disableDirectBuffers();
        EventLoopGroup bossGroup = new NioEventLoopGroup(NUM_BOSS_THREADS);
        EventLoopGroup workerGroup = new NioEventLoopGroup(numThreads);
        groups.add(bossGroup);
        groups.add(workerGroup);
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(this.channelInitializer)
                .option(ChannelOption.SO_BACKLOG, SOCKET_MAX_INBOUND_CONNECTION_QUEUE_DEPTH)
                .childOption(ChannelOption.SO_KEEPALIVE, SOCKET_KEEPALIVE);
        return b;
    }

}

From source file:com.stremebase.examples.todomvc.Todo.java

License:Apache License

public static void main(String[] args) throws Exception {
    css = new String(Files.readAllBytes(Paths.get(System.getProperty("user.dir"), "Web", "index.css")));
    favicon = Files.readAllBytes(Paths.get(System.getProperty("user.dir"), "Web", "favicon.ico"));

    Table.setDefaultDb(new DB("user.dir"));
    data = new Data(itemTableId, "ITEMTABLE");

    @SuppressWarnings("unchecked")
    Router<Integer> router = new Router<Integer>().GET("/", GET).GET("/filter/:filtertype", FILTER)

            .POST("/", POST).POST("/delete", DELETE).POST("/clearcompleted", DELETECOMPLETED)
            .POST("/toggle-status", TOGGLESTATUS)

            .GET(":something/index.css", CSS).GET("/index.css", CSS).GET("/favicon.ico", ICON)
            .notFound(NOTFOUND);/*from   w  w  w .  j  ava 2 s . c  o m*/
    System.out.println(router);

    OioEventLoopGroup bossGroup = new OioEventLoopGroup(1);
    SingleThreadEventLoop workerGroup = new ThreadPerChannelEventLoop(bossGroup);

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).childOption(ChannelOption.TCP_NODELAY, java.lang.Boolean.TRUE)
                .childOption(ChannelOption.SO_KEEPALIVE, java.lang.Boolean.TRUE)
                .childOption(ChannelOption.SO_REUSEADDR, java.lang.Boolean.TRUE)
                .channel(OioServerSocketChannel.class).childHandler(new HttpRouterServerInitializer(router));

        Channel ch = b.bind(PORT).sync().channel();
        System.out.println("Server started: http://127.0.0.1:" + PORT + '/');

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

From source file:com.study.hc.net.netty.EchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure the server.
    // EventLoopGroup   accept NioEventLoop
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    // EventLoopGroup   I/O
    EventLoopGroup workerGroup2 = new NioEventLoopGroup(1);
    try {/*from w  w  w .ja  v a  2 s  .c  om*/
        // ??
        ServerBootstrap b = new ServerBootstrap();
        // ???reactor???
        b.group(bossGroup, workerGroup2).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.DEBUG))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new EchoServerHandler());
                    }
                });
        // bind??
        ChannelFuture f = b.bind(PORT).sync();
        // ??
        f.channel().closeFuture().sync();
    } finally {
        // 
        bossGroup.shutdownGracefully();
        workerGroup2.shutdownGracefully();
    }
}

From source file:com.supermy.im.Application.java

License:Apache License

@SuppressWarnings("unchecked")
@Bean(name = "serverBootstrap")
public ServerBootstrap bootstrap() {

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup(), workerGroup()) //???accept???io
            .channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.ERROR))
            .childHandler(imChannelInitializer);

    /**// w  w  w  . j ava2 s  .c  o  m
     * ?
     */
    Map<ChannelOption<?>, Object> tcpChannelOptions = tcpChannelOptions();
    Set<ChannelOption<?>> keySet = tcpChannelOptions.keySet();
    for (@SuppressWarnings("rawtypes")
    ChannelOption option : keySet) {
        b.option(option, tcpChannelOptions.get(option));
    }

    return b;
}

From source file:com.system.distribute.server.FileServer.java

License:Apache License

public void run() throws Exception {
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//from ww  w  .  j  a  va2  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 StringEncoder(CharsetUtil.UTF_8),
                                new LineBasedFrameDecoder(8192), new StringDecoder(CharsetUtil.UTF_8),
                                new FileHandler());
                    }
                });

        // 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:com.tc.websocket.server.DominoWebSocketServer.java

License:Apache License

@Override
public synchronized void start() {

    if (this.isOn())
        return;//ww  w .  j  av a 2 s .c  o m

    try {
        try {

            ServerBootstrap boot = new ServerBootstrap();

            if (cfg.isNativeTransport()) {
                boot.channel(EpollServerSocketChannel.class);
            } else {
                boot.channel(NioServerSocketChannel.class);
            }

            boot.group(bossGroup, workerGroup).option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .childOption(ChannelOption.WRITE_BUFFER_WATER_MARK,
                            new WriteBufferWaterMark(8 * 1024, 32 * 1024))
                    .childOption(ChannelOption.SO_SNDBUF, cfg.getSendBuffer())
                    .childOption(ChannelOption.SO_RCVBUF, cfg.getReceiveBuffer())
                    .childOption(ChannelOption.TCP_NODELAY, true).childHandler(init);

            //bind to the main port
            boot.bind(cfg.getPort()).sync();

            //bind to the redirect port (e.g. 80 will redirect to 443)
            for (Integer port : cfg.getRedirectPorts()) {
                ChannelFuture f = boot.bind(port);
                f.sync();
            }

            this.on.set(true);

            String version = BundleUtils.getVersion(Activator.bundle);
            String name = BundleUtils.getName(Activator.bundle);
            cfg.print(name + " ready and listening on " + cfg.getPort() + " running version " + version);

        } finally {

        }
    } catch (Exception e) {
        LOG.log(Level.SEVERE, null, e);
    }
}

From source file:com.tch.test.chat.netty.NettyServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from  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 MyServerChannelInitializer());

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

From source file:com.tesora.dve.db.mysql.portal.MySqlPortal.java

License:Open Source License

public MySqlPortal(Properties props) throws PEException {
    // This is the port the Portal is going to listen on -
    // default to Mysql's port
    int port = Singletons.require(HostService.class).getPortalPort(props);
    Singletons.replace(MySqlPortalService.class, this);

    InternalLoggerFactory.setDefaultFactory(new Log4JLoggerFactory());

    int max_concurrent = KnownVariables.MAX_CONCURRENT.getValue(null).intValue();

    //TODO: parse/plan is on this pool, which is probably ok, especially with blocking calls to catalog.  Check for responses that can be done by backend netty threads and avoid two context shifts.

    clientExecutorService = new PEThreadPoolExecutor(max_concurrent, max_concurrent, 30L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(), //The thread count limits concurrency here.  Using a bounded queue here would block netty threads (very bad), so this pool could be overrun by 'bad' clients that pipeline. -sgossard
            new PEDefaultThreadFactory("msp-client"));
    clientExecutorService.allowCoreThreadTimeOut(true);

    bossGroup = new NioEventLoopGroup(1, new PEDefaultThreadFactory("msp-boss"));

    //fixes the number of Netty NIO threads to the number of available CPUs.
    workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors(),
            new PEDefaultThreadFactory("netty-worker"));

    ServerBootstrap b = new ServerBootstrap();
    try {/*from  w  w  w  .  j a  v  a2s.  co m*/
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        if (PACKET_LOGGER)
                            ch.pipeline().addFirst(new LoggingHandler(LogLevel.INFO));
                        ch.pipeline()
                                .addLast(MSPProtocolDecoder.class.getSimpleName(),
                                        new MSPProtocolDecoder(
                                                MSPProtocolDecoder.MyDecoderState.READ_CLIENT_AUTH))
                                .addLast(new MSPAuthenticateHandlerV10())
                                .addLast(MSPCommandHandler.class.getSimpleName(),
                                        new MSPCommandHandler(clientExecutorService))
                                .addLast(ConnectionHandlerAdapter.getInstance());
                    }
                })

                .childOption(ChannelOption.ALLOCATOR,
                        USE_POOLED_BUFFERS ? PooledByteBufAllocator.DEFAULT : UnpooledByteBufAllocator.DEFAULT)
                .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
                .bind(port).sync();

        logger.info("DVE Server bound to port " + port);

    } catch (Exception e) {
        throw new PEException("Failed to bind DVE server to port " + port + " - " + e.getMessage(), e);
    }
}