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.grillecube.client.network.ClientNetwork.java

public void start(String host, int port) throws Exception {
    this.workerGroup = new NioEventLoopGroup();
    this.bootstrap = new Bootstrap(); // (1)
    this.bootstrap.group(this.workerGroup); // (2)
    this.bootstrap.channel(NioSocketChannel.class); // (3)
    this.bootstrap.option(ChannelOption.SO_KEEPALIVE, true); // (4)
    this.bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override/*  w w w .j  a v a2  s.  co  m*/
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new TimeClientHandler());
        }
    });

    // Start the client.
    try {
        this.channel = this.bootstrap.connect(host, port).sync(); // (5)
    } catch (Exception exception) {
        // args are: quiettime, timeout, time unit
        this.workerGroup.shutdownGracefully(0, 10, TimeUnit.SECONDS);
        Logger.get().log(Level.ERROR, "Couldnt connect to host: " + host + ":" + port);
        exception.printStackTrace(Logger.get().getPrintStream());

        this.bootstrap = null;
        this.channel = null;
        this.workerGroup = null;
    }
}

From source file:com.grillecube.engine.network.client.ClientNetwork.java

public void start(String host, int port) throws Exception {
    this._workergroup = new NioEventLoopGroup();
    this._bootstrap = new Bootstrap(); // (1)
    this._bootstrap.group(this._workergroup); // (2)
    this._bootstrap.channel(NioSocketChannel.class); // (3)
    this._bootstrap.option(ChannelOption.SO_KEEPALIVE, true); // (4)
    this._bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override/*from   w ww.j a  v  a 2 s .  co  m*/
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new TimeClientHandler());
        }
    });

    // Start the client.
    try {
        this._channel = this._bootstrap.connect(host, port).sync(); // (5)
    } catch (Exception exception) {
        // args are: quiettime, timeout, time unit
        this._workergroup.shutdownGracefully(0, 10, TimeUnit.SECONDS);
        Logger.get().log(Level.ERROR, "Couldnt connect to host: " + host + ":" + port);
        exception.printStackTrace(Logger.get().getPrintStream());

        this._bootstrap = null;
        this._channel = null;
        this._workergroup = null;
    }
}

From source file:com.grillecube.engine.network.server.ServerNetwork.java

public void start() throws Exception {
    this._bossgroup = new NioEventLoopGroup();
    this._workergroup = new NioEventLoopGroup();
    this._bootstrap = new ServerBootstrap();
    this._bootstrap.group(this._bossgroup, this._workergroup);
    this._bootstrap.channel(NioServerSocketChannel.class);
    this._bootstrap.childHandler(this);
    this._bootstrap.option(ChannelOption.SO_BACKLOG, 128);
    this._bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

    // Bind and start to accept incoming connections.
    this._channel = this._bootstrap.bind(this._port).sync(); // (7)
    Logger.get().log(Level.FINE, "Listening on " + this._port);
    this.stop();//w w w .j  a va  2s. c  o  m
}

From source file:com.grillecube.server.network.ServerNetwork.java

public void start() throws Exception {
    this.bossgroup = new NioEventLoopGroup();
    this.workergroup = new NioEventLoopGroup();
    this.bootstrap = new ServerBootstrap();
    this.bootstrap.group(this.bossgroup, this.workergroup);
    this.bootstrap.channel(NioServerSocketChannel.class);
    this.bootstrap.childHandler(this);
    this.bootstrap.option(ChannelOption.SO_BACKLOG, 128);
    this.bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

    // Bind and start to accept incoming connections.
    this.channel = this.bootstrap.bind(this.port).sync(); // (7)
    Logger.get().log(Level.FINE, "Listening on " + this.port);
    this.stop();/*from w  w w  .  j a v  a 2  s .c  o m*/
}

From source file:com.guowl.websocket.client.WebSocketClientRunner.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {/*from   www . j a  v  a  2  s .c  o m*/
        // 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()));

        final String protocol = uri.getScheme();
        int defaultPort;
        ChannelInitializer<SocketChannel> initializer;

        // Normal WebSocket
        if ("ws".equals(protocol)) {
            initializer = new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast("http-codec", new HttpClientCodec())
                            .addLast("aggregator", new HttpObjectAggregator(8192))
                            .addLast("ws-handler", handler);
                }
            };

            defaultPort = 80;
            // Secure WebSocket
        } else if ("wss".equals(protocol)) {
            initializer = new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    SSLEngine engine = WebSocketSslClientContextFactory.getContext().createSSLEngine();
                    engine.setUseClientMode(true);

                    ch.pipeline().addFirst("ssl", new SslHandler(engine))
                            .addLast("http-codec", new HttpClientCodec())
                            .addLast("aggregator", new HttpObjectAggregator(8192))
                            .addLast("ws-handler", handler);
                }
            };

            defaultPort = 443;
        } else {
            throw new IllegalArgumentException("Unsupported protocol: " + protocol);
        }

        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(initializer);

        int port = uri.getPort();
        // If no port was specified, we'll try the default port: https://tools.ietf.org/html/rfc6455#section-1.7
        if (uri.getPort() == -1) {
            port = defaultPort;
        }

        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.copiedBuffer(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.guowl.websocket.stream.client.StreamClientRunner.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {/*from w w w  .j  a v  a 2  s. com*/
        // 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 StreamClientHandler handler = new StreamClientHandler(WebSocketClientHandshakerFactory
                .newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders()));

        final String protocol = uri.getScheme();
        int defaultPort;
        ChannelInitializer<SocketChannel> initializer;

        // Normal WebSocket
        if ("ws".equals(protocol)) {
            initializer = new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast("http-codec", new HttpClientCodec())
                            .addLast("aggregator", new HttpObjectAggregator(8192))
                            .addLast("ws-handler", handler);
                }
            };

            defaultPort = 80;
            // Secure WebSocket
        } else {
            throw new IllegalArgumentException("Unsupported protocol: " + protocol);
        }

        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(initializer);

        int port = uri.getPort();
        // If no port was specified, we'll try the default port:
        if (uri.getPort() == -1) {
            port = defaultPort;
        }

        Channel ch = b.connect(uri.getHost(), port).sync().channel();
        handler.handshakeFuture().sync();
        ByteBuf dataBuf = ch.alloc().buffer();
        dataBuf.writeBytes("start".getBytes());
        ch.writeAndFlush(new BinaryWebSocketFrame(false, 0, dataBuf));
        ch.writeAndFlush(new ContinuationWebSocketFrame(true, 0, "end"));
        Thread.sleep(1000 * 60 * 60);
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.gw.monitor.alphaenvmonitor.monitor.MonitorClient.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {/*from  w  w w  .  j  av a  2s.  c o  m*/
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new MonitorClientInitializer());

        // 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.gw.monitor.alphaenvmonitor.monitor.MonitorServer.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from   ww  w. j a  v  a  2 s.c  om*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new MonitorServerInitializer());

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

From source file:com.gw.services.client.HttpsClient.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   w w  w . ja 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 = CLIENT_CONTEXT;
    } else {
        sslCtx = null;
    }

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

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

        String requestBody = "{\"productId\": 11,\"userName\": \"caiwei\",\"amount\": 1000}";
        ByteBuf content = Unpooled.copiedBuffer(requestBody.getBytes(CharsetUtil.UTF_8));
        // Prepare the HTTP request.
        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
                uri.getRawPath(), content);
        request.headers().set(HttpHeaders.Names.HOST, host);
        request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
        request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

        request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json");
        request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, content.readableBytes());
        // Set some example cookies.
        request.headers().set(HttpHeaders.Names.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.gxkj.demo.netty.discard.DiscardClient.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {//from ww  w  .  ja v  a2 s  .c  o m
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new DiscardClientHandler(firstMessageSize));

        // Make the connection attempt.
        ChannelFuture f = b.connect(host, port).sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}