Example usage for io.netty.channel ChannelOption SO_KEEPALIVE

List of usage examples for io.netty.channel ChannelOption SO_KEEPALIVE

Introduction

In this page you can find the example usage for io.netty.channel ChannelOption SO_KEEPALIVE.

Prototype

ChannelOption SO_KEEPALIVE

To view the source code for io.netty.channel ChannelOption SO_KEEPALIVE.

Click Source Link

Usage

From source file:net.smert.frameworkgl.Network.java

License:Apache License

private void createServer(int port, Supplier<ChannelHandler> channelHandlerSupplier) {

    // Are we already running?
    if (serverRunning) {
        return;//from  ww w.  ja  va2  s  . c o m
    }

    serverPort = port;

    // Create event loops
    serverAcceptGroup = new NioEventLoopGroup(1);
    serverWorkerGroup = new NioEventLoopGroup();

    // Create channel initializer
    ChannelInitializer<SocketChannel> channelInit = new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            if (debug) {
                p.addLast(new LoggingHandler(logLevel));
            }
            p.addLast(channelHandlerSupplier.get());
        }

    };

    // Bootstrap the server
    server = new ServerBootstrap();
    if (debug) {
        server.handler(new LoggingHandler(logLevel));
    }
    server.group(serverAcceptGroup, serverWorkerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, backlog).childHandler(channelInit)
            .childOption(ChannelOption.SO_KEEPALIVE, keepAlive)
            .childOption(ChannelOption.TCP_NODELAY, tcpNoDelay);

    // Start listening on the port
    server.bind(port);

    // The server is now running
    serverRunning = true;
}

From source file:netty.demo1.DiscardServer.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//from w w w .  j a va2s  .  c o m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new DiscardServerHandler());
                    }
                }).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:netty.http2.ConcurrentHttp2Client.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from  www.j a  v  a 2s  .co  m
        SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
        sslCtx = SslContextBuilder.forClient().sslProvider(provider)
                /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification.
                 * Please refer to the HTTP/2 specification for cipher requirements. */
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .trustManager(InsecureTrustManagerFactory.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                        // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectorFailureBehavior.NO_ADVERTISE,
                        // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2,
                        ApplicationProtocolNames.HTTP_1_1))
                .build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup workerGroup = new NioEventLoopGroup();
    ConcurrentHttp2ClientInitializer initializer = new ConcurrentHttp2ClientInitializer();

    try {
        // Configure the client.
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(workerGroup);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.remoteAddress(HOST, PORT);
        bootstrap.handler(initializer);

        // Start the client.
        Channel channel = bootstrap.connect().syncUninterruptibly().channel();
        System.out.println("Connected to [" + HOST + ':' + PORT + ']');

        HttpScheme scheme = SSL ? HttpScheme.HTTPS : HttpScheme.HTTP;
        AsciiString hostName = new AsciiString(HOST + ':' + PORT);
        System.err.println("Sending request(s)...");
        if (URL != null) {
            // Create a simple GET request.
            for (int i = 0; i < 1; i++) {
                StreamRequest request = new StreamRequestBuilder(new URI(URL)).setMethod("GET")
                        //.setMethod("POST")
                        .setHeader(HttpHeaderNames.HOST.toString(), hostName.toString())
                        //.build(EntityStreams.emptyStream());
                        .build(EntityStreams
                                .newEntityStream(new ByteStringWriter(ByteString.copy(new byte[0 * 1024]))));
                channel.writeAndFlush(request);
                System.err.println("Sent request #" + i);
            }
        }
        System.err.println("Finished HTTP/2 request(s)");
        long start = System.currentTimeMillis();

        // Wait until the connection is closed.
        channel.closeFuture().sync();

        long end = System.currentTimeMillis();
        System.err.println("Server Idled for: " + (end - start) + " milliseconds");
    } finally {
        workerGroup.shutdownGracefully();
    }
}

From source file:netty.mmb.http2.Client.Http2Client.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from  w w w  . j  av a2  s.  c o  m*/
        SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
        sslCtx = SslContext.newClientContext(provider, null, InsecureTrustManagerFactory.INSTANCE,
                Http2SecurityUtil.CIPHERS,
                /* NOTE: the following filter may not include all ciphers required by the HTTP/2 specification
                 * Please refer to the HTTP/2 specification for cipher requirements. */
                SupportedCipherSuiteFilter.INSTANCE,
                new ApplicationProtocolConfig(Protocol.ALPN, SelectorFailureBehavior.CHOOSE_MY_LAST_PROTOCOL,
                        SelectedListenerFailureBehavior.CHOOSE_MY_LAST_PROTOCOL,
                        SelectedProtocol.HTTP_2.protocolName(), SelectedProtocol.HTTP_1_1.protocolName()),
                0, 0);
    } else {
        sslCtx = null;
    }

    EventLoopGroup workerGroup = new NioEventLoopGroup();
    Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE);

    try {
        // Configure the client.
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(HOST, PORT);
        b.handler(initializer);

        // Start the client.
        Channel channel = b.connect().syncUninterruptibly().channel();
        System.out.println("Connected to [" + HOST + ':' + PORT + ']');

        // Wait for the HTTP/2 upgrade to occur.
        Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler();
        http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS);

        HttpResponseHandler responseHandler = initializer.responseHandler();
        int streamId = 3;
        URI hostName = URI.create((SSL ? "https" : "http") + "://" + HOST + ':' + PORT);
        System.err.println("Sending request(s)...");
        if (URL != null) {
            // Create a simple GET request.
            FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, URL);
            request.headers().add(HttpHeaderNames.HOST, hostName);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
            channel.writeAndFlush(request);
            responseHandler.put(streamId, channel.newPromise());
            streamId += 2;
        }
        if (URL2 != null) {
            // Create a simple POST request with a body.
            FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, URL2,
                    Unpooled.copiedBuffer(URL2DATA.getBytes(CharsetUtil.UTF_8)));
            request.headers().add(HttpHeaderNames.HOST, hostName);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
            channel.writeAndFlush(request);
            responseHandler.put(streamId, channel.newPromise());
            streamId += 2;
        }
        responseHandler.awaitResponses(5, TimeUnit.SECONDS);
        System.out.println("Finished HTTP/2 request(s)");

        // Wait until the connection is closed.
        channel.close().syncUninterruptibly();
    } finally {
        workerGroup.shutdownGracefully();
    }
}

From source file:netty.server.Server.java

License:Apache License

public void run() throws CertificateException, SSLException, UnknownHostException {

    final BlockingQueue<String> qq = new LinkedBlockingQueue<>(1);

    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();
    try {//from w  w  w.j  ava  2  s . c o  m
        final ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_KEEPALIVE, true).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(final SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        //                            p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new WebSocketServerInitializer(qq));
                    }
                });

        try {
            //                channelFuture = b.bind(port).sync().await();
            //                System.out.println(Server.class.getName() +
            //                        " started and listen on " + channelFuture.channel().localAddress());
            //                InetAddress address = InetAddress.getByName("192.168.1.152");
            channelFuture = b.bind(port).sync().await();
            System.out.println(Server.class.getName() + " started and listen on "
                    + channelFuture.channel().localAddress());
            System.out.println("Web socket server started at port " + port + '.');
            //                System.out.println("Open your browser and navigate to http " + port + '/');
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
            logger.error("InterruptedException " + ex.getLocalizedMessage());
        }

        // Wait until the server socket is closed.
        try {
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }

    } finally {
        close();
    }
}

From source file:netty5.http.client.Http2Client.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from   w ww.j  a v  a  2 s.  c o  m
        SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
        sslCtx = SslContextBuilder.forClient().sslProvider(provider)
                /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification.
                 * Please refer to the HTTP/2 specification for cipher requirements. */
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .trustManager(InsecureTrustManagerFactory.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                        // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectorFailureBehavior.NO_ADVERTISE,
                        // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2,
                        ApplicationProtocolNames.HTTP_1_1))
                .build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup workerGroup = new NioEventLoopGroup();
    Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE);

    try {
        // Configure the client.
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(HOST, PORT);
        b.handler(initializer);

        // Start the client.
        Channel channel = b.connect().syncUninterruptibly().channel();
        System.out.println("Connected to [" + HOST + ':' + PORT + ']');

        // Wait for the HTTP/2 upgrade to occur.
        Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler();
        http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS);

        HttpResponseHandler responseHandler = initializer.responseHandler();
        int streamId = 3;
        URI hostName = URI.create((SSL ? "https" : "http") + "://" + HOST + ':' + PORT);
        System.err.println("Sending request(s)...");
        if (URL != null) {
            // Create a simple GET request.
            FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, URL);
            request.headers().addObject(HttpHeaderNames.HOST, hostName);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
            channel.writeAndFlush(request);
            responseHandler.put(streamId, channel.newPromise());
            streamId += 2;
        }
        if (URL2 != null) {
            // Create a simple POST request with a body.
            FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, URL2,
                    Unpooled.copiedBuffer(URL2DATA.getBytes(CharsetUtil.UTF_8)));
            request.headers().addObject(HttpHeaderNames.HOST, hostName);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
            channel.writeAndFlush(request);
            responseHandler.put(streamId, channel.newPromise());
            streamId += 2;
        }
        responseHandler.awaitResponses(5, TimeUnit.SECONDS);
        System.out.println("Finished HTTP/2 request(s)");

        // Wait until the connection is closed.
        channel.close().syncUninterruptibly();
    } finally {
        workerGroup.shutdownGracefully();
    }
}

From source file:nettyClient4.clientImpl.java

License:Apache License

public void start() throws Exception {
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*  www  .  j  av a 2s . co  m*/
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(workerGroup).channel(NioSocketChannel.class); // NioSocketChannel is being used to create a client-side Channel.
        //Note that we do not use childOption() here unlike we did with
        // ServerBootstrap because the client-side SocketChannel does not have a parent.
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.handler(new ClientChannelInitializer());

        // Bind and start to accept incoming connections.
        ChannelFuture channelFuture = bootstrap.connect(this.host, this.port);
        // Wait until the server socket is closed.
        // In this server, this does not happen, but you can do that to gracefully
        // shut down your CLIENT.

        //            while (true){
        //                ByteBuf buffer= PooledByteBufAllocator.DEFAULT.heapBuffer(8);
        //                buffer.writeInt(0);//?4
        //                buffer.writeByte(1);
        //                buffer.writeByte(1);
        //                buffer.writeByte(1);
        //                buffer.setInt(0, buffer.writerIndex() - 4);
        //                channel.writeAndFlush(buffer) ;
        //                Thread.sleep(100);
        //            }
        /**
         * ??pb?
         */

        Channel channel = channelFuture.channel();
        //            while (true){
        //                LoginRequest.Builder builder=LoginRequest.newBuilder();
        //                builder.setUsername("dc1");
        //                builder.setPassword("123");
        //
        //                playerIdRequest.Builder b=playerIdRequest.newBuilder();
        //
        //
        //                ByteBuf buffer= PooledByteBufAllocator.DEFAULT.heapBuffer(8);
        //                buffer.setIndex(0, 0x2);//?2
        //                buffer.writeInt(LoginRequest.msgID.ID_VALUE);
        //                buffer.writeBytes(builder.build().toByteArray());
        //                buffer.setShort(0, buffer.writerIndex() - 0x2);
        //                channel.writeAndFlush(buffer) ;
        //                Thread.sleep(0xa);
        //
        //            }
        //            creatRoleRequest.Builder builder=creatRoleRequest.newBuilder();
        //            builder.setRoleName("896");
        //            builder.setRoleSex(1);
        //            builder.setRoleType(1);
        //
        //            ByteBuf buffer= PooledByteBufAllocator.DEFAULT.heapBuffer(8);
        //            buffer.setIndex(0, 0x2);//?2
        //            buffer.writeInt(creatRoleRequest.msgID.ID_VALUE);
        //            buffer.writeBytes(builder.build().toByteArray());
        //            buffer.setShort(0, buffer.writerIndex() - 0x2);
        //            channel.writeAndFlush(buffer) ;
        //            Thread.sleep(0xa);
    } finally {
        workerGroup.shutdownGracefully();
    }

}

From source file:nettyone.HttpRouterServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // This is an example router, it will be used at HttpRouterServerHandler.
    ////from   w  ww  .j  a  v a 2  s.com
    // For simplicity of this example, route targets are just simple strings.
    // But you can make them classes, and at HttpRouterServerHandler once you
    // get a target class, you can create an instance of it and dispatch the
    // request to the instance etc.
    Router<String> router = new Router<String>().GET("/", "Index page").notFound("404 Not Found");
    System.out.println(router);

    NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).childOption(ChannelOption.TCP_NODELAY, java.lang.Boolean.TRUE)
                .childOption(ChannelOption.SO_KEEPALIVE, java.lang.Boolean.TRUE)
                .channel(NioServerSocketChannel.class).childHandler(new HttpRouterServerInitializer(router));

        Channel ch = b.bind(PORT).sync().channel();
        System.out.println("Server started: http://127.0.0.1:" + PORT + '/');

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

From source file:nikoladasm.aspark.server.ASparkServer.java

License:Open Source License

public void start() {
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();
    try {/*  w  w w. j  ava  2s . c  om*/
        ServerBootstrap server = new ServerBootstrap();
        server.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ServerInitializer(sslContext, maxContentLength, ipAddress, port, dispatcher,
                        exceptionMap, webSockets, serverName, pool))
                .option(ChannelOption.SO_BACKLOG, 1024).option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.TCP_NODELAY, true);
        channel = server.bind(new InetSocketAddress(ipAddress, port)).sync().channel();
        started = true;
        latch.countDown();
        LOG.info("Netty server started");
    } catch (InterruptedException e) {
        LOG.error("Unexpected exception", e);
        bossGroup.shutdownGracefully(0, 0, TimeUnit.SECONDS);
        workerGroup.shutdownGracefully(0, 0, TimeUnit.SECONDS);
        started = false;
        latch.countDown();
    }
}

From source file:org.acmsl.katas.antlr4netty.InterpreterServer.java

License:Open Source License

/**
 * Launches the server to accept incoming requests on given port.
 * @param port the port.//from w  ww . j ava 2s .c o  m
 * @return the {@link ChannelFuture} when the server stops accepting connections.
 */
@NotNull
public ChannelFuture listen(final int port) {
    @NotNull
    final ChannelFuture result;

    @NotNull
    final NioEventLoopGroup bossGroup = new NioEventLoopGroup();
    @NotNull
    final NioEventLoopGroup workerGroup = new NioEventLoopGroup();

    ServerBootstrap bootstrap = new ServerBootstrap();

    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                /**
                 * {@inheritDoc}
                 */
                @Override
                protected void initChannel(@NotNull final SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new InterpreterServerChannelHandler());
                }
            }).option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
            .childOption(ChannelOption.SO_KEEPALIVE, true);

    result = wrap(bootstrap.bind(port), bossGroup, workerGroup);

    return result;
}