Example usage for io.netty.channel.nio NioEventLoopGroup NioEventLoopGroup

List of usage examples for io.netty.channel.nio NioEventLoopGroup NioEventLoopGroup

Introduction

In this page you can find the example usage for io.netty.channel.nio NioEventLoopGroup NioEventLoopGroup.

Prototype

public NioEventLoopGroup(ThreadFactory threadFactory) 

Source Link

Document

Create a new instance using the default number of threads, the given ThreadFactory and the SelectorProvider which is returned by SelectorProvider#provider() .

Usage

From source file:com.github.ambry.rest.NettyServer.java

License:Open Source License

/**
 * Creates a new instance of NettyServer.
 * @param nettyConfig the {@link NettyConfig} instance that defines the configuration parameters for the NettyServer.
 * @param nettyMetrics the {@link NettyMetrics} instance to use to record metrics.
 * @param channelInitializer A {@link ChannelInitializer} that is used to initialize new channels.
 *///from  w w w.j  a  va 2 s .  com
public NettyServer(NettyConfig nettyConfig, NettyMetrics nettyMetrics,
        ChannelInitializer<SocketChannel> channelInitializer) {
    this.nettyConfig = nettyConfig;
    this.nettyMetrics = nettyMetrics;
    this.channelInitializer = channelInitializer;
    bossGroup = new NioEventLoopGroup(nettyConfig.nettyServerBossThreadCount);
    workerGroup = new NioEventLoopGroup(nettyConfig.nettyServerWorkerThreadCount);
    logger.trace("Instantiated NettyServer");
}

From source file:com.github.ambry.tools.perf.rest.NettyPerfClient.java

License:Open Source License

/**
 * Starts the NettyPerfClient./*from  w ww  .  j  av  a 2s  .  c o  m*/
 * @throws InterruptedException
 */
protected void start() {
    logger.info("Starting NettyPerfClient");
    reporter.start();
    group = new NioEventLoopGroup(concurrency);
    b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            if (sslFactory != null) {
                ch.pipeline().addLast(
                        new SslHandler(sslFactory.createSSLEngine(host, port, SSLFactory.Mode.CLIENT)));
            }
            ch.pipeline().addLast(new HttpClientCodec()).addLast(new ChunkedWriteHandler())
                    .addLast(new ResponseHandler());
        }
    });
    logger.info("Connecting to {}:{}", host, port);
    b.remoteAddress(host, port);
    perfClientStartTime = System.currentTimeMillis();
    for (int i = 0; i < concurrency; i++) {
        b.connect().addListener(channelConnectListener);
    }
    isRunning = true;
    logger.info("Created {} channel(s)", concurrency);
    logger.info("NettyPerfClient started");
}

From source file:com.github.gregwhitaker.requestreply.Client.java

License:Apache License

public void start() throws Exception {
    Publisher<ClientTcpDuplexConnection> publisher = ClientTcpDuplexConnection.create(remoteAddress,
            new NioEventLoopGroup(1));

    ClientTcpDuplexConnection duplexConnection = RxReactiveStreams.toObservable(publisher).toBlocking().last();
    ReactiveSocket reactiveSocket = DefaultReactiveSocket.fromClientConnection(duplexConnection,
            ConnectionSetupPayload.create("UTF-8", "UTF-8"), t -> t.printStackTrace());

    reactiveSocket.startAndWait();//from w w w .  j a va  2s .  c  o  m

    // Create an observable that emits messages at a specific interval.
    Publisher<Payload> requestStream = RxReactiveStreams.toPublisher(
            Observable.interval(1_000, TimeUnit.MILLISECONDS).onBackpressureDrop().map(i -> new Payload() {
                @Override
                public ByteBuffer getData() {
                    return ByteBuffer.wrap(("YO " + i).getBytes());
                }

                @Override
                public ByteBuffer getMetadata() {
                    return Frame.NULL_BYTEBUFFER;
                }
            }));

    final CountDownLatch latch = new CountDownLatch(Integer.MAX_VALUE);

    requestStream.subscribe(new Subscriber<Payload>() {
        @Override
        public void onSubscribe(Subscription s) {
            s.request(Long.MAX_VALUE);
        }

        @Override
        public void onNext(Payload payload) {
            ByteBuf buffer = Unpooled.buffer(payload.getData().capacity());
            buffer.writeBytes(payload.getData());

            byte[] bytes = new byte[buffer.capacity()];
            buffer.readBytes(bytes);

            System.out.println("Client Sent: " + new String(bytes));

            reactiveSocket.requestResponse(payload).subscribe(new Subscriber<Payload>() {
                @Override
                public void onSubscribe(Subscription s) {
                    s.request(Long.MAX_VALUE);
                }

                @Override
                public void onNext(Payload payload) {
                    ByteBuf buffer = Unpooled.buffer(payload.getData().capacity());
                    buffer.writeBytes(payload.getData());

                    byte[] bytes = new byte[buffer.capacity()];
                    buffer.readBytes(bytes);

                    System.out.println("Client Received: " + new String(bytes));

                    latch.countDown();
                }

                @Override
                public void onError(Throwable t) {
                    latch.countDown();
                }

                @Override
                public void onComplete() {
                    latch.countDown();
                }
            });
        }

        @Override
        public void onError(Throwable t) {

        }

        @Override
        public void onComplete() {

        }
    });

    latch.await();
    System.exit(0);
}

From source file:com.github.gregwhitaker.requestreply.Server.java

License:Apache License

/**
 * Starts the server./*from   w  ww  . j  a va  2s  .c o m*/
 *
 * @throws Exception
 */
private void start() throws Exception {
    ServerBootstrap server = new ServerBootstrap();
    server.group(new NioEventLoopGroup(1), new NioEventLoopGroup(4)).channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ReactiveSocketChannelInitializer());

    server.bind(bindAddress).sync();
}

From source file:com.github.herong.rpc.netty.protobuf.demo1.ProtobufServer.java

License:Apache License

public void run() throws Exception {
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from w  w  w .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("frameDecoder", new ProtobufVarint32FrameDecoder())
                                // 
                                .addLast("protobufDecoder",
                                        new ProtobufDecoder(AddressBookProtos.AddressBook.getDefaultInstance()))
                                // 
                                .addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender())
                                .addLast("protobufEncoder", new ProtobufEncoder())
                                // 
                                .addLast("handler", new ProtobufServerHandler());
                    }
                });

        // 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.github.herong.rpc.netty.protobuf.demo2.Demo2ProtobufServer.java

License:Apache License

public void run() throws Exception {
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//w ww  .  j a  va 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 ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                // 
                                .addLast("frameDecoder", new ProtobufVarint32FrameDecoder())
                                // 
                                .addLast("protobufDecoder",
                                        new ProtobufDecoder(Message.DTO.getDefaultInstance()))
                                // 
                                .addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender())
                                .addLast("protobufEncoder", new ProtobufEncoder())
                                // 
                                .addLast("handler", new Demo2ProtobufServerHandler());
                    }
                });

        // 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.github.jonbonazza.puni.core.Application.java

License:Apache License

private void bootstrap() throws Exception {
    SslContext sslContext = null;/*from w w w  . j  a  v a 2 s  .c  o  m*/
    SSLConfiguration sslConfig = config.getSsl();
    if (config.getSsl().isEnabled()) {
        sslContext = SslContext.newServerContext(new File(sslConfig.getCert()),
                new File(sslConfig.getPrivateKey()));
    }

    EventLoopGroup eventGroup = new NioEventLoopGroup(config.getEventLoopThreadCount());

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(eventGroup).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new HttpInitializer(sslContext, muxer));
        Channel ch = b.bind(config.getPort()).sync().channel();
        ch.closeFuture().sync();
        bootstrapped = true;
    } finally {
        eventGroup.shutdownGracefully();
    }
}

From source file:com.github.nettybook.ch7.junit.TelnetServerV3.java

License:Apache License

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

    try {//  www . 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 TelnetServerInitializerV3());

        ChannelFuture future = b.bind(address).sync();

        future.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.github.nettybook.ch8.HttpSnoopServer.java

License:Apache License

@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {
    SslContext sslCtx = null;//from  ww w. ja  va 2 s.  com

    try {
        File certChainFile = new File("netty.crt");
        File keyFile = new File("privatekey.pem");
        keyFile.exists();

        sslCtx = SslContext.newServerContext(certChainFile, keyFile, "1234");
    } catch (SSLException e) {
        e.printStackTrace();
        System.out.println("Can not create SSL context! \n Server will be stop!");
    }

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

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

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

From source file:com.github.nettybook.ch8.TelnetServer.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 a2 s.c om
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new TelnetServerInitializer());

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