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.kuujo.copycat.netty.protocol.impl.TcpProtocolClient.java

License:Apache License

@Override
public CompletableFuture<Void> connect() {
    final CompletableFuture<Void> future = new CompletableFuture<>();
    if (channel != null) {
        future.complete(null);//w  w  w  .j  a  va2  s  . c  om
        return future;
    }

    final SslContext sslContext;
    if (protocol.isSsl()) {
        try {
            sslContext = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
        } catch (SSLException e) {
            future.completeExceptionally(e);
            return future;
        }
    } else {
        sslContext = null;
    }

    final EventLoopGroup group = new NioEventLoopGroup(protocol.getThreads());
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            if (sslContext != null) {
                pipeline.addLast(
                        sslContext.newHandler(channel.alloc(), protocol.getHost(), protocol.getPort()));
            }
            pipeline.addLast(new ObjectEncoder(),
                    new ObjectDecoder(
                            ClassResolvers.softCachingConcurrentResolver(getClass().getClassLoader())),
                    new TcpProtocolClientHandler(TcpProtocolClient.this));
        }
    });

    if (protocol.getSendBufferSize() > -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, protocol.getSendBufferSize());
    }

    if (protocol.getReceiveBufferSize() > -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, protocol.getReceiveBufferSize());
    }

    if (protocol.getTrafficClass() > -1) {
        bootstrap.option(ChannelOption.IP_TOS, protocol.getTrafficClass());
    }

    bootstrap.option(ChannelOption.TCP_NODELAY, protocol.isNoDelay());
    bootstrap.option(ChannelOption.SO_LINGER, protocol.getSoLinger());
    bootstrap.option(ChannelOption.SO_KEEPALIVE, protocol.isKeepAlive());
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, protocol.getConnectTimeout());

    bootstrap.connect(protocol.getHost(), protocol.getPort()).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            if (channelFuture.isSuccess()) {
                channel = channelFuture.channel();
                future.complete(null);
            } else {
                future.completeExceptionally(channelFuture.cause());
            }
        }
    });
    return future;
}

From source file:net.kuujo.copycat.netty.protocol.impl.TcpProtocolServer.java

License:Apache License

@Override
public CompletableFuture<Void> start() {
    final CompletableFuture<Void> future = new CompletableFuture<>();

    // TODO: Configure proper SSL trust store.
    final SslContext sslContext;
    if (protocol.isSsl()) {
        try {//from  w w w .  j a va  2  s.  c o m
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslContext = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
        } catch (SSLException | CertificateException e) {
            future.completeExceptionally(e);
            return future;
        }
    } else {
        sslContext = null;
    }

    final EventLoopGroup serverGroup = new NioEventLoopGroup();
    final EventLoopGroup workerGroup = new NioEventLoopGroup(protocol.getThreads());

    final ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(serverGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    if (sslContext != null) {
                        pipeline.addLast(sslContext.newHandler(channel.alloc()));
                    }
                    pipeline.addLast(new ObjectEncoder(),
                            new ObjectDecoder(
                                    ClassResolvers.softCachingConcurrentResolver(getClass().getClassLoader())),
                            new TcpProtocolServerHandler(TcpProtocolServer.this));
                }
            }).option(ChannelOption.SO_BACKLOG, 128);

    if (protocol.getSendBufferSize() > -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, protocol.getSendBufferSize());
    }

    if (protocol.getReceiveBufferSize() > -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, protocol.getReceiveBufferSize());
    }

    bootstrap.option(ChannelOption.TCP_NODELAY, protocol.isNoDelay());
    bootstrap.option(ChannelOption.SO_REUSEADDR, protocol.isReuseAddress());
    bootstrap.option(ChannelOption.SO_KEEPALIVE, protocol.isKeepAlive());
    bootstrap.option(ChannelOption.SO_BACKLOG, protocol.getAcceptBacklog());

    if (protocol.getTrafficClass() > -1) {
        bootstrap.option(ChannelOption.IP_TOS, protocol.getTrafficClass());
    }

    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

    // Bind and start to accept incoming connections.
    bootstrap.bind(protocol.getHost(), protocol.getPort()).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            channelFuture.channel().closeFuture().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    workerGroup.shutdownGracefully();
                }
            });

            if (channelFuture.isSuccess()) {
                channel = channelFuture.channel();
                future.complete(null);
            } else {
                future.completeExceptionally(channelFuture.cause());
            }
        }
    });
    return future;
}

From source file:net.mcsproject.daemon.network.NetClient.java

License:Open Source License

public NetClient(String ip, int port) {
    this.packetRegistry = new PacketRegistry();
    this.listenerRegistry = new ListenerRegistry();

    this.registerPackets();
    this.registerListeners();

    new Thread(() -> {
        EventLoopGroup bossGroup = new NioEventLoopGroup();

        try {//from  w ww.j  av  a2 s .  c o  m
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(bossGroup);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(new PacketDecoder(packetRegistry))
                            .addLast(new PacketEncoder(packetRegistry))
                            .addLast(new PacketMessageHandler(listenerRegistry));
                }
            });
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture future = bootstrap.connect(ip, port).sync();
            log.info("Connection established!");
            future.channel().closeFuture().sync();
            log.info("Connection closed!");
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
        }
    }).start();
}

From source file:net.mcsproject.master.network.DaemonServer.java

License:Open Source License

public DaemonServer(int port) {
    this.thread = new Thread(() -> {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {//from  w ww . j  av  a 2  s .co m
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup);
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(new PacketDecoder()).addLast(new PacketEncoder())
                            .addLast(new PacketMessageHandler());
                }
            });
            bootstrap.option(ChannelOption.SO_BACKLOG, 50);
            bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture future = bootstrap.bind(port).sync();
            log.info("Server started!");
            future.channel().closeFuture().sync();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    });

    thread.setName("DaemonServer Thread");
    thread.start();
}

From source file:net.NettyEngine4.ServerServiceImpl.java

License:Apache License

/**
 *  run netty server/*from  w w w .  ja v a  2s  .com*/
 *  NioEventLoopGroup used for NIO Selector based Channels
 *  two NioEventLoopGroup(AioEventLoopGroup) will be used. The first is
 *  used to handle the accept of new connections and the second will serve the IO of them.
 *  IoEventLoopGroupThread +1;
 *  DefaultEventExecutorGroup ?
 *
 *  bossExecutor:?SocketChannel
 *  workerExecutorSocketChannel?channel/
 *  executionLogicHandlerThread????
 *  AIO ?channelgroup?group?
 *  option() is for the NioServerSocketChannel that accepts incoming connections
 *  childOption() is for the Channels accepted by the parent ServerChannel,
 *  which is NioServerSocketChannel in this case.
 *
 *   ServerBootstrap ?? parent channel
 *   parent channel ? connections
 *  ? connection ? child channel ??
 */
@Override
public void run() throws Exception {
    NioEventLoopGroup EventLoopGroupLister = new NioEventLoopGroup(0x1,
            new PriorityThreadFactory("@+main_reactor+@", Thread.NORM_PRIORITY));
    NioEventLoopGroup IOEventLoopGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() + 1,
            new PriorityThreadFactory("@+sub_reactor+@", Thread.NORM_PRIORITY));
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    try {
        serverBootstrap.group(EventLoopGroupLister, IOEventLoopGroup).channel(NioServerSocketChannel.class)
                .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.SO_REUSEADDR, true) //??
                .childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(false))// heap buf 's better
                .childOption(ChannelOption.SO_RCVBUF, 1048576).childOption(ChannelOption.SO_SNDBUF, 1048576)
                .childHandler(new ServerChannelInitializer());//used to serve the request for the {@link Channel}'s
        // Bind and start to accept incoming connections.
        ChannelFuture channelFuture = serverBootstrap
                .bind(new InetSocketAddress(Config.DEFAULT_VALUE.SERVER_VALUE.gameserverPort)).sync();
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("server??:" + Config.DEFAULT_VALUE.SERVER_VALUE.gameserverPort);
        // Wait until the server socket is closed.
        // In this server, this does not happen, but you can do that to gracefully
        // shut down your server.
        channelFuture.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        EventLoopGroupLister.shutdownGracefully();
        IOEventLoopGroup.shutdownGracefully();
    }
}

From source file:net.NettyEngine4.ServerServiceImpl.java

License:Apache License

/**
 * jni native Epoll/*from  w w w .  j av  a2 s. c  o m*/
 #NioEventLoopGroup  EpollEventLoopGroup   ---- EventLoopGroup ?
 #NioEventLoop  EpollEventLoop
 #NioServerSocketChannel  EpollServerSocketChannel
 #NioSocketChannel  EpollSocketChannel        ---- SocketChannel?
        
 ## RHEL/CentOS/Fedora:
 #sudo yum install autoconf automake libtool glibc-devel.i686 glibc-devel libgcc.i686 make
 ## Debian/Ubuntu:
 #sudo apt-get install autoconf automake libtool make gcc-multilib
 * @throws Exception
 */
@Override
public void runNativeEpoll() throws Exception {
    EpollEventLoopGroup BossEventLoopGroup = new EpollEventLoopGroup(0x1,
            new PriorityThreadFactory("@+?", Thread.NORM_PRIORITY)); //mainReactor    1
    EpollEventLoopGroup WorkerEventLoopGroup = new EpollEventLoopGroup(
            Runtime.getRuntime().availableProcessors() + 0x1,
            new PriorityThreadFactory("@+I/O", Thread.NORM_PRIORITY)); //subReactor       ?cpu+1
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    try {
        serverBootstrap.group(BossEventLoopGroup, WorkerEventLoopGroup).channel(EpollServerSocketChannel.class)
                .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.SO_REUSEADDR, true) //??
                .childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(false))// heap buf 's better
                .childOption(ChannelOption.SO_RCVBUF, 1048576).childOption(ChannelOption.SO_SNDBUF, 1048576)
                .childHandler(new ServerChannelInitializer());//used to serve the request for the {@link Channel}'s
        // Bind and start to accept incoming connections.
        ChannelFuture channelFuture = serverBootstrap
                .bind(new InetSocketAddress(Config.DEFAULT_VALUE.SERVER_VALUE.gameserverPort)).sync();
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("server??:" + Config.DEFAULT_VALUE.SERVER_VALUE.gameserverPort);
        // Wait until the server socket is closed.
        // In this server, this does not happen, but you can do that to gracefully
        // shut down your server.
        channelFuture.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        BossEventLoopGroup.shutdownGracefully();
        WorkerEventLoopGroup.shutdownGracefully();
    }
}

From source file:net.openhft.performance.tests.third.party.frameworks.netty.NettyEchoServer.java

License:Apache License

public void run() throws InterruptedException {
    @NotNull//from ww w .j  a v  a 2  s. co m
    EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
    @NotNull
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        @NotNull
        ServerBootstrap b = new ServerBootstrap(); // (2)
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) // (3)
                .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
                    @Override
                    public void initChannel(@NotNull SocketChannel ch) {
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            // echo server
                            @Override
                            public void channelRead(@NotNull ChannelHandlerContext ctx, Object msg) { // (2)
                                ctx.write(msg); // (1)
                                ctx.flush(); // (2)
                            }

                            @Override
                            public void exceptionCaught(@NotNull ChannelHandlerContext ctx,
                                    @NotNull Throwable cause) { // (4)
                                // Close the connection when an exception is raised.
                                cause.printStackTrace();
                                ctx.close();
                            }
                        });
                    }
                }).option(ChannelOption.SO_BACKLOG, 128) // (5)
                .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

        // Bind and start to accept incoming connections.
        ChannelFuture f = b.bind(port).sync(); // (7)

        // Wait until the server socket is closed.
        // In this example, this does not happen, but you can do that to gracefully
        // shut down your server.
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}

From source file:net.pms.network.HTTPServer.java

License:Open Source License

public boolean start() throws IOException {
    hostname = configuration.getServerHostname();
    InetSocketAddress address;//from ww w. j a  v a  2s.c  o  m

    if (StringUtils.isNotBlank(hostname)) {
        LOGGER.info("Using forced address " + hostname);
        InetAddress tempIA = InetAddress.getByName(hostname);

        if (tempIA != null && networkInterface != null
                && networkInterface.equals(NetworkInterface.getByInetAddress(tempIA))) {
            address = new InetSocketAddress(tempIA, port);
        } else {
            address = new InetSocketAddress(hostname, port);
        }
    } else if (isAddressFromInterfaceFound(configuration.getNetworkInterface())) { // XXX sets iafinal and networkInterface
        LOGGER.info("Using address {} found on network interface: {}", iafinal,
                networkInterface.toString().trim().replace('\n', ' '));
        address = new InetSocketAddress(iafinal, port);
    } else {
        LOGGER.info("Using localhost address");
        address = new InetSocketAddress(port);
    }

    LOGGER.info("Created socket: " + address);

    if (configuration.isHTTPEngineV2()) { // HTTP Engine V2
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.SO_REUSEADDR, true)
                .childOption(ChannelOption.SO_SNDBUF, 65536).childOption(ChannelOption.SO_RCVBUF, 65536);
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).localAddress(address)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast("HttpHandler", new HttpServerCodec())
                                // eliminate the need to decode http chunks from the client
                                .addLast("aggregator", new HttpObjectAggregator(64 * 1024))
                                .addLast("chunkedWriter", new ChunkedWriteHandler())
                                .addLast("handler", new RequestHandlerV2());
                    }
                });

        try {
            channel = bootstrap.bind().channel();
        } catch (Exception e) {
            LOGGER.error("Another program is using port " + port + ", which UMS needs.");
            LOGGER.error("You can change the port UMS uses on the General Configuration tab.");
            LOGGER.trace("The error was: " + e);
            PMS.get().getFrame().setStatusCode(0, Messages.getString("PMS.141"), "icon-status-warning.png");
        }

        if (hostname == null && iafinal != null) {
            hostname = iafinal.getHostAddress();
        } else if (hostname == null) {
            hostname = InetAddress.getLocalHost().getHostAddress();
        }
    } else { // HTTP Engine V1
        serverSocketChannel = ServerSocketChannel.open();

        serverSocket = serverSocketChannel.socket();
        serverSocket.setReuseAddress(true);
        serverSocket.bind(address);

        if (hostname == null && iafinal != null) {
            hostname = iafinal.getHostAddress();
        } else if (hostname == null) {
            hostname = InetAddress.getLocalHost().getHostAddress();
        }

        runnable = new Thread(this, "HTTP Server");
        runnable.setDaemon(false);
        runnable.start();
    }

    return true;
}

From source file:net.qing.sms.simulator.NettySmsSimulatorServer.java

License:Apache License

protected void applyConnectionOptions(ServerBootstrap bootstrap) {
    SocketConfig config = configuration.getSocketConfig();
    bootstrap.childOption(ChannelOption.TCP_NODELAY, config.isTcpNoDelay());
    if (config.getTcpSendBufferSize() != -1) {
        bootstrap.childOption(ChannelOption.SO_SNDBUF, config.getTcpSendBufferSize());
    }//from  w  w w. ja  va 2 s  .  c o m
    if (config.getTcpReceiveBufferSize() != -1) {
        bootstrap.childOption(ChannelOption.SO_RCVBUF, config.getTcpReceiveBufferSize());
    }
    // bootstrap.option(ChannelOption.ALLOCATOR,
    // PooledByteBufAllocator.DEFAULT);
    bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    // bootstrap.childOption(ChannelOption.ALLOCATOR,
    // PooledByteBufAllocator.DEFAULT);
    bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, config.isTcpKeepAlive());
    bootstrap.option(ChannelOption.SO_LINGER, config.getSoLinger());
    bootstrap.option(ChannelOption.SO_REUSEADDR, config.isReuseAddress());
    bootstrap.option(ChannelOption.SO_BACKLOG, config.getAcceptBackLog());
}

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

License:Apache License

private void createClient(String host, int port, Supplier<ChannelHandler> channelHandlerSupplier) {

    // Create event loops
    clientWorkerGroup = new NioEventLoopGroup();

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

        @Override/*from   ww  w . j  a v a  2 s .  c  o m*/
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            if (debug) {
                p.addLast(new LoggingHandler(logLevel));
            }
            p.addLast(channelHandlerSupplier.get());
        }

    };

    // Bootstrap the client
    client = new Bootstrap();
    if (debug) {
        client.handler(new LoggingHandler(logLevel));
    }
    client.group(clientWorkerGroup).channel(NioSocketChannel.class)
            .option(ChannelOption.SO_KEEPALIVE, keepAlive).option(ChannelOption.TCP_NODELAY, tcpNoDelay)
            .handler(channelInit);

    // Connect to the host and port
    client.connect(host, port);
}