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.qq.servlet.demo.netty.telnet.TelnetServer.java

License:Apache License

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

        b.bind(port).sync().channel().closeFuture().sync();

    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.quavo.osrs.network.NetworkExecutor.java

License:Open Source License

/**
 * Starts the network for a {@link Server}.
 * //  w ww  .jav a2  s  .  c om
 * @param server The {@link Server} to use for building the network.
 * @return <True> If the network started successfully.
 */
public static void start() {
    EventLoopGroup boss = new NioEventLoopGroup();
    EventLoopGroup worker = new NioEventLoopGroup();
    ServerBootstrap bootstrap = new ServerBootstrap();

    bootstrap.group(boss, worker);
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();

            pipeline.addLast("decoder", new ConnectionDecoder());
            pipeline.addLast("encoder", new ConnectionEncoder());
            pipeline.addLast("adapter", new NetworkMessageHandler());
        }

    });
    bootstrap.childOption(ChannelOption.TCP_NODELAY, true);

    try {
        bootstrap.bind(Constants.HOST_NAME, Constants.HOST_PORT).sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println("Server successfully bootstrapped on port " + Constants.HOST_PORT + " and address "
            + Constants.HOST_NAME + ".");
}

From source file:com.rackspacecloud.blueflood.inputs.handlers.HttpMetricsIngestionServer.java

License:Apache License

/**
 * Starts the Ingest server//from  w ww  .  ja  va2  s  . c  om
 *
 * @throws InterruptedException
 */
public void startServer() throws InterruptedException {

    RouteMatcher router = new RouteMatcher();
    router.get("/v1.0", new DefaultHandler());
    router.post("/v1.0/multitenant/experimental/metrics",
            new HttpMultitenantMetricsIngestionHandler(processor, timeout));
    router.post("/v1.0/:tenantId/experimental/metrics", new HttpMetricsIngestionHandler(processor, timeout));
    router.post("/v1.0/:tenantId/experimental/metrics/statsd",
            new HttpAggregatedIngestionHandler(processor, timeout));

    router.get("/v2.0", new DefaultHandler());
    router.post("/v2.0/:tenantId/ingest/multi", new HttpMultitenantMetricsIngestionHandler(processor, timeout));
    router.post("/v2.0/:tenantId/ingest", new HttpMetricsIngestionHandler(processor, timeout));
    router.post("/v2.0/:tenantId/ingest/aggregated", new HttpAggregatedIngestionHandler(processor, timeout));
    router.post("/v2.0/:tenantId/events", getHttpEventsIngestionHandler());
    router.post("/v2.0/:tenantId/ingest/aggregated/multi",
            new HttpAggregatedMultiIngestionHandler(processor, timeout));
    final RouteMatcher finalRouter = router;

    log.info("Starting metrics listener HTTP server on port {}", httpIngestPort);
    ServerBootstrap server = new ServerBootstrap();
    server.group(acceptorGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel channel) throws Exception {
                    setupPipeline(channel, finalRouter);
                }
            });

    Channel channel = server.bind(new InetSocketAddress(httpIngestHost, httpIngestPort)).sync().channel();
    allOpenChannels.add(channel);

    //register the tracker MBean for JMX/jolokia
    log.info("Registering tracker service");
    Tracker.getInstance().register();
}

From source file:com.rackspacecloud.blueflood.outputs.handlers.HttpMetricDataQueryServer.java

License:Apache License

public void startServer() throws InterruptedException {

    RouteMatcher router = new RouteMatcher();
    router.get("/v1.0", new DefaultHandler());
    router.get("/v1.0/:tenantId/experimental/views/metric_data/:metricName", new HttpRollupsQueryHandler());

    router.post("/v1.0/:tenantId/experimental/views/metric_data", new HttpMultiRollupsQueryHandler());
    router.post("/v2.0/:tenantId/views", new HttpMultiRollupsQueryHandler());

    router.get("/v2.0", new DefaultHandler());
    router.get("/v2.0/:tenantId/views/:metricName", new HttpRollupsQueryHandler());
    router.get("/v2.0/:tenantId/metrics/search", new HttpMetricsIndexHandler());
    router.get("/v2.0/:tenantId/metric_name/search", new HttpMetricTokensHandler());
    router.get("/v2.0/:tenantId/events/getEvents", new HttpEventsQueryHandler(getEventsIO()));

    router.options("/v2.0/:tenantId/views/:metricName", new HttpOptionsHandler());
    router.options("/v2.0/:tenantId/views", new HttpOptionsHandler());
    router.options("/v2.0/:tenantId/metrics/search", new HttpOptionsHandler());
    router.options("/v2.0/:tenantId/metric_name/search", new HttpOptionsHandler());
    router.options("/v2.0/:tenantId/events/getEvents", new HttpOptionsHandler());

    final RouteMatcher finalRouter = router;

    log.info("Starting metric data query server (HTTP) on port {}", this.httpQueryPort);
    ServerBootstrap server = new ServerBootstrap();
    server.group(acceptorGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/*w  ww . j a  v a2  s. c  o  m*/
                public void initChannel(SocketChannel channel) throws Exception {
                    setupPipeline(channel, finalRouter);
                }
            });
    serverChannel = server.bind(new InetSocketAddress(httpQueryHost, httpQueryPort)).sync().channel();

    //register the tracker MBean for JMX/jolokia
    log.info("Registering tracker service");
    Tracker.getInstance().register();
}

From source file:com.robert.NettyProject.EchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/* w  ww  .j  av  a  2 s . c  om*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } 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("encode", new StringEncoder());
                        p.addLast("decode", new StringDecoder());
                        // 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:com.rr.echoserver.EchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    System.out.println("Writing on separate threads: " + EchoServer.THREADED);

    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/* ww w  .  j ava2 s.  c  om*/
        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:com.sample.netty.socket.server.Server.java

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*w ww .  j  av a2 s .c o 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 MessageDecoder(), new ServerHandlerInbound());
                        ch.pipeline().addLast(new MessageEncoder(), new ServerHandlerOutbound());
                    }
                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
        ChannelFuture f = b.bind(port).sync();
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}

From source file:com.seed.nettyechoserver.EchoServer.java

public static void main(String[] args) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup(1);
    try {/*from w  ww .j a va  2s.  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 ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        //p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new EchoServerHandler());
                    }
                });

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

From source file:com.Server.java

License:Apache License

/**
 * This is passive mode server/*from ww  w. j  ava  2s. co  m*/
 * @param fs FTP Session Handler
 * @param host Server IP address
 * @param port Passive port no.
 */
public Server(String host, int port, int mode, String fileName) {
    InetSocketAddress inSocketAddress = new InetSocketAddress(host, port);
    try {
        ServerBootstrap bootStrap = new ServerBootstrap();
        bootStrap.group(bossGroup, workerGroup);
        bootStrap.channel(NioServerSocketChannel.class);
        bootStrap.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 1);
        bootStrap.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 1);
        bootStrap.childHandler(new MyChannelInitializer(this, mode, fileName));
        bootStrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
        bootStrap.bind(inSocketAddress);
        System.out.println("Server started");
    } catch (Exception eg) {
        eg.printStackTrace();
        stop();
    }
}

From source file:com.seventh_root.ld33.server.LD33Server.java

License:Apache License

private void start() {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//from  w  w w . ja v  a 2s  . c o  m
        ServerBootstrap bootstrap = new ServerBootstrap();
        handler = new LD33ServerHandler(this);
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel channel) throws Exception {
                        channel.pipeline().addLast(new ObjectEncoder(),
                                new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                                //new LD33ClientBoundPacketEncoder(),
                                //new LD33ServerBoundPacketDecoder(LD33Server.this),
                                handler);
                    }
                });
        Channel channel = bootstrap.bind(getConfig().getInt("port", 37896)).sync().channel();
        setRunning(true);
        long beforeTime, timeDiff, sleep;
        beforeTime = currentTimeMillis();
        while (isRunning()) {
            doTick();
            timeDiff = currentTimeMillis() - beforeTime;
            sleep = DELAY - timeDiff;
            if (sleep > 0) {
                try {
                    Thread.sleep(sleep);
                } catch (InterruptedException exception) {
                    getLogger().log(SEVERE, "Thread interrupted", exception);
                }
            }
            beforeTime = currentTimeMillis();
        }
        channel.closeFuture().sync();
    } catch (InterruptedException exception) {
        getLogger().log(SEVERE, "Event loop group interrupted", exception);
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}