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() 

Source Link

Document

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

Usage

From source file:com.eightkdata.mongowp.mongoserver.MongoServer.java

License:Open Source License

public void run() {
    // TODO: provide custom ThreadFactories to the EventLoopGroup to name threads correctly?
    connectionGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();
    try {/*from w  w w.  j  a  v  a  2 s.  c o  m*/
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(connectionGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        buildChildHandlerPipeline(socketChannel.pipeline());
                    }
                })
        // TODO: set TCP channel options?
        ;

        ChannelFuture channelFuture = bootstrap.bind(port).awaitUninterruptibly();

        try {
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException interruptedException) {
            LOGGER.error("Error", interruptedException);
            // TODO: perform proper shutdown
        } catch (Throwable throwable) {
            LOGGER.error("Error", throwable);
            // TODO: perform proper shutdown
        }
    } finally {
        workerGroup.shutdownGracefully();
        connectionGroup.shutdownGracefully();
    }
}

From source file:com.elephant.framework.network.telnet.netty.TelnetClient.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {//  w  ww. j  a  v  a2 s.co  m
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new TelnetClientInitializer());

        // Start the connection attempt.
        Channel ch = b.connect(host, port).sync().channel();

        // Read commands from the stdin.
        ChannelFuture lastWriteFuture = null;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        for (;;) {
            String line = in.readLine();
            if (line == null) {
                break;
            }

            // Sends the received line to the server.
            lastWriteFuture = ch.writeAndFlush(line + "\r\n");

            // If user typed the 'bye' command, wait until the server closes
            // the connection.
            if ("bye".equals(line.toLowerCase())) {
                ch.closeFuture().sync();
                break;
            }
        }

        // Wait until all messages are flushed before closing the channel.
        if (lastWriteFuture != null) {
            lastWriteFuture.sync();
        }
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.example.client.ClientMain.java

License:Apache License

public void run() throws InterruptedException {
    final NioEventLoopGroup workerLoop = new NioEventLoopGroup();
    try (final GracefulShutdown ignored = GracefulShutdown.gracefulShutdown(workerLoop::shutdownGracefully)) {
        final Bootstrap bootstrap = new Bootstrap(); // ServerBootstrap ??????????
        final ChannelFuture future = bootstrap.group(workerLoop) // ??? ????? boss /worker ??????
                .channel(NioSocketChannel.class) // NioServerSocketChannel ???????
                .option(ChannelOption.SO_KEEPALIVE, true) // ???? parent ??????? childOption ????
                .handler(ClientChannelInitializerConfigurer.channelInitializer()).connect(host, port) // bind ????? connect
                .sync();//  w  ww .  j a  va  2 s . co m
        future.channel().closeFuture().sync();
    }
}

From source file:com.example.discard.DiscardServerMain.java

License:Apache License

public void run() throws Exception {
    final NioEventLoopGroup bossGroup = new NioEventLoopGroup();//1
    final NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    try (AutoCloseable ignore = new ShutDownGracefully(bossGroup, workerGroup)) {
        final ServerBootstrap bootstrap = new ServerBootstrap();//2
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)//3
                .childHandler(new ChannelInitializer<SocketChannel>() {//4
                    @Override/*from   w w w.j  a v  a 2  s .co m*/
                    protected void initChannel(final SocketChannel ch) {
                        ch.pipeline().addLast(new DiscardServerHandler());
                    }
                }).option(ChannelOption.SO_BACKLOG, 128)//5
                .childOption(ChannelOption.SO_KEEPALIVE, true); //6
        final ChannelFuture channelFuture = bootstrap.bind(port).sync();//7
        channelFuture.channel().closeFuture().sync();
    }
}

From source file:com.example.http.hello.HttpHelloServer.java

License:Apache License

private void run() throws InterruptedException {
    final NioEventLoopGroup bossGroup = new NioEventLoopGroup();
    final NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    try (final GracefulShutdown ignored = GracefulShutdown.gracefulShutdown(bossGroup::shutdownGracefully,
            workerGroup::shutdownGracefully)) {
        final ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.option(ChannelOption.SO_BACKLOG, 1024);
        serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(ServerChannelInitializationConfigurer.channelInitializer());

        final Channel channel = serverBootstrap.bind(port).sync().channel();

        log.info("server started: http://localhost:{}/", port);

        channel.closeFuture().sync();//  ww w . j  a  va  2  s  .co m
    }
}

From source file:com.example.server.ServerMain.java

License:Apache License

public void run() throws InterruptedException {
    final NioEventLoopGroup parentGroup = new NioEventLoopGroup();
    final NioEventLoopGroup workerGroup = new NioEventLoopGroup();

    try (final GracefulShutdown ignored = GracefulShutdown.gracefulShutdown(parentGroup::shutdownGracefully,
            workerGroup::shutdownGracefully)) {
        final ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(parentGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(ServerChannelInitializationConfigurer.channelInitializer())
                .option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
        log.info("server start");
        final ChannelFuture channelFuture = bootstrap.bind(port).sync();
        channelFuture.channel().closeFuture().sync();
    }/*from w  w w.jav a  2  s. com*/
}

From source file:com.example.spring.boot.netty.TcpClient.java

License:Apache License

public void connectServer() {
    for (int i = 0; i < connNum; i++) {
        EventLoopGroup group = new NioEventLoopGroup();
        try {/*from  w w  w.j  av  a  2  s  .  co  m*/
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            //p.addLast(new LoggingHandler(LogLevel.INFO));
                            p.addLast(new LineBasedFrameDecoder(1024));
                            p.addLast(new StringDecoder());
                            p.addLast(new TcpClientHandler(TcpClient.this));
                        }
                    });

            // Start the client.
            ChannelFuture f = b.connect(address.split(":")[0], Integer.parseInt(address.split(":")[1])).sync();

            // Wait until the connection is closed.
            //            f.channel().closeFuture().sync();
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            // Shut down the event loop to terminate all threads.
            //            group.shutdownGracefully();
        }
    }
}

From source file:com.example.spring.boot.netty.TcpServer.java

License:Apache License

public void bind() {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//from www . j ava2 s . c om
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 65535).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 LineBasedFrameDecoder(1024));
                        p.addLast(new StringDecoder());
                        p.addLast(TCP_SERVER_HANDLER);
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(port).sync();

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } catch (Throwable e) {
        e.printStackTrace();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.fanavard.challenge.client.websocket.WebSocketClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    URI uri = new URI(URL);
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    final int port;
    if (uri.getPort() == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;/*from  w  ww.  ja va 2s. c om*/
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        } else {
            port = -1;
        }
    } else {
        port = uri.getPort();
    }

    if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) {
        System.err.println("Only WS(S) is supported.");
        return;
    }

    final boolean ssl = "wss".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00.
        // If you change it to V00, ping is not supported and remember to change
        // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline.
        final WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory
                .newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders()));

        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) {
                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), host, port));
                }
                p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192),
                        new WebSocketClientCompressionHandler(), handler);
            }
        });

        Channel ch = b.connect(uri.getHost(), port).sync().channel();
        handler.handshakeFuture().sync();

        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String msg = console.readLine();
            if (msg == null) {
                break;
            } else if ("bye".equals(msg.toLowerCase())) {
                ch.writeAndFlush(new CloseWebSocketFrame());
                ch.closeFuture().sync();
                break;
            } else if ("ping".equals(msg.toLowerCase())) {
                WebSocketFrame frame = new PingWebSocketFrame(
                        Unpooled.wrappedBuffer(new byte[] { 8, 1, 8, 1 }));
                ch.writeAndFlush(frame);
            } else {
                WebSocketFrame frame = new TextWebSocketFrame(msg);
                ch.writeAndFlush(frame);
            }
        }
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.farsunset.cim.sdk.client.CIMConnectorManager.java

License:Apache License

private CIMConnectorManager() {

    bootstrap = new Bootstrap();
    loopGroup = new NioEventLoopGroup();
    bootstrap.group(loopGroup);/*from  w w  w  . ja  v a2 s. c om*/
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT);

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(new ClientMessageDecoder());
            pipeline.addLast(new ClientMessageEncoder());
            pipeline.addLast(new IdleStateHandler(READ_IDLE_TIME, 0, 0));
            pipeline.addLast(CIMConnectorManager.this);

        }
    });

}