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.dinstone.rpc.netty.server.NettyServer.java

License:Apache License

public void start() {
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();
    try {// w  ww .j a  v a2  s  . c  o m
        ServerBootstrap boot = new ServerBootstrap();
        boot.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new RpcProtocolDecoder(true));
                        ch.pipeline().addLast(new RpcProtocolEncoder(true));
                        ch.pipeline().addLast(new NettyServerHandler(handler));
                    }
                });
        boot.option(ChannelOption.SO_BACKLOG, 128);
        boot.childOption(ChannelOption.SO_KEEPALIVE, true);

        int port = config.getInt(Constants.SERVICE_PORT, Constants.DEFAULT_SERVICE_PORT);
        InetSocketAddress localAddress = new InetSocketAddress(port);
        String host = config.get(Constants.SERVICE_HOST);
        if (host != null) {
            localAddress = new InetSocketAddress(host, port);
        }
        LOG.info("RPC service works on " + localAddress);

        boot.bind(localAddress).sync();
    } catch (InterruptedException e) {
        throw new RpcException(500, "Server can't bind to the specified local address ", e);
    }
}

From source file:com.diozero.internal.provider.remote.voodoospark.VoodooSparkProtocolHandler.java

License:Open Source License

private void connect(String host, int port) throws InterruptedException {
    workerGroup = new NioEventLoopGroup();

    ResponseHandler rh = new ResponseHandler(this::messageReceived);

    Bootstrap b1 = new Bootstrap();
    b1.group(workerGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
        @Override/* w  w  w  .j  a va  2  s  . c o m*/
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new ResponseDecoder(), new MessageEncoder(), rh);
        }
    });

    // Connect
    messageChannel = b1.connect(host, port).sync().channel();
}

From source file:com.doctor.netty5.ebook.netty_the_definitive_guide.Chapter4ForTimerClient.java

License:Apache License

public void connect(String host, int port) throws InterruptedException {
    EventLoopGroup group = new NioEventLoopGroup();
    try {// ww  w.  j  a  va2 s.c  o m
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LineBasedFrameDecoder(2014));
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new TimeClientHander());

                    }
                });

        ChannelFuture f = b.connect(host, port).sync();
        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }

}

From source file:com.doctor.netty5.ebook.netty_the_definitive_guide.Chapter4ForTimerServer.java

License:Apache License

public void bind(int port) throws InterruptedException {
    // ??NIO//from w w w .  j  a  va 2s  .  co m
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024).childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new TimeServerHander());

                    }
                });

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

From source file:com.doctor.netty5.ebook.netty_the_definitive_guide.TimerClient.java

License:Apache License

public void connect(String host, int port) throws InterruptedException {
    EventLoopGroup group = new NioEventLoopGroup();
    try {/*w w w  .j  a  v  a2s  .c  om*/
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new TimeClientHander());

                    }
                });

        ChannelFuture f = b.connect(host, port).sync();
        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }

}

From source file:com.doctor.netty5.ebook.netty_the_definitive_guide.TimeServer.java

License:Apache License

public void bind(int port) throws InterruptedException {
    // ??NIO//from w  ww .j a va  2  s.c  om
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024).childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new TimeServerHander());

                    }
                });

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

From source file:com.dwarf.netty.guide.factorial.FactorialClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*w ww .j  a v a 2s .  c  om*/
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new FactorialClientInitializer(sslCtx));

        // Make a new connection.
        ChannelFuture f = b.connect(HOST, PORT).sync();

        // Get the handler instance to retrieve the answer.
        FactorialClientHandler handler = (FactorialClientHandler) f.channel().pipeline().last();

        // Print out the answer.
        System.err.format("Factorial of %,d is: %,d", COUNT, handler.getFactorial());
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.dwarf.netty.guide.http.snoop.HttpSnoopClient.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();
    String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;/*from   ww  w  . j  a  v  a2 s  .c  o  m*/
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }

    if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
        System.err.println("Only HTTP(S) is supported.");
        return;
    }

    // Configure SSL context if necessary.
    final boolean ssl = "https".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new HttpSnoopClientInitializer(sslCtx));

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

        // Prepare the HTTP request.
        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
                uri.getRawPath());
        request.headers().set(HttpHeaderNames.HOST, host);
        request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
        request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);

        // Set some example cookies.
        request.headers().set(HttpHeaderNames.COOKIE, ClientCookieEncoder
                .encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar")));

        // Send the HTTP request.
        ch.writeAndFlush(request);

        // Wait for the server to close the connection.
        ch.closeFuture().sync();
    } finally {
        // Shut down executor threads to exit.
        group.shutdownGracefully();
    }
}

From source file:com.dwarf.netty.guide.securechat.SecureChatClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);

    EventLoopGroup group = new NioEventLoopGroup();
    try {//from  ww  w  . ja  v  a  2s.com
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new SecureChatClientInitializer(sslCtx));

        // 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 {
        // The connection is closed automatically on shutdown.
        group.shutdownGracefully();
    }
}

From source file:com.dwarf.netty.guide.worldclock.WorldClockClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*w w w  .ja  v a 2  s  .c om*/
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new WorldClockClientInitializer(sslCtx));

        // Make a new connection.
        Channel ch = b.connect(HOST, PORT).sync().channel();

        // Get the handler instance to initiate the request.
        WorldClockClientHandler handler = ch.pipeline().get(WorldClockClientHandler.class);

        // Request and get the response.
        List<String> response = handler.getLocalTimes(CITIES);

        // Close the connection.
        ch.close();

        // Print the response at last but not least.
        for (int i = 0; i < CITIES.size(); i++) {
            System.out.format("%28s: %s%n", CITIES.get(i), response.get(i));
        }
    } finally {
        group.shutdownGracefully();
    }
}