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:org.scache.network.client.TransportClientFactory.java

License:Apache License

/** Create a completely new {@link TransportClient} to the remote address. */
private TransportClient createClient(InetSocketAddress address) throws IOException {
    logger.debug("Creating new connection to " + address);

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup).channel(socketChannelClass)
            // Disable Nagle's Algorithm since we don't want packets to wait
            .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, conf.connectionTimeoutMs())
            .option(ChannelOption.ALLOCATOR, pooledAllocator);

    final AtomicReference<TransportClient> clientRef = new AtomicReference<>();
    final AtomicReference<Channel> channelRef = new AtomicReference<>();

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override/*from  w  ww . ja va 2  s.  c om*/
        public void initChannel(SocketChannel ch) {
            TransportChannelHandler clientHandler = context.initializePipeline(ch);
            clientRef.set(clientHandler.getClient());
            channelRef.set(ch);
        }
    });

    // Connect to the remote server
    long preConnect = System.nanoTime();
    ChannelFuture cf = bootstrap.connect(address);
    if (!cf.awaitUninterruptibly(conf.connectionTimeoutMs())) {
        throw new IOException(
                String.format("Connecting to %s timed out (%s ms)", address, conf.connectionTimeoutMs()));
    } else if (cf.cause() != null) {
        throw new IOException(String.format("Failed to connect to %s", address), cf.cause());
    }

    TransportClient client = clientRef.get();
    Channel channel = channelRef.get();
    assert client != null : "Channel future completed successfully with null client";

    // Execute any client bootstraps synchronously before marking the Client as successful.
    long preBootstrap = System.nanoTime();
    logger.debug("Connection to {} successful, running bootstraps...", address);
    try {
        for (TransportClientBootstrap clientBootstrap : clientBootstraps) {
            clientBootstrap.doBootstrap(client, channel);
        }
    } catch (Exception e) { // catch non-RuntimeExceptions too as bootstrap may be written in Scala
        long bootstrapTimeMs = (System.nanoTime() - preBootstrap) / 1000000;
        logger.error("Exception while bootstrapping client after " + bootstrapTimeMs + " ms", e);
        client.close();
        throw Throwables.propagate(e);
    }
    long postBootstrap = System.nanoTime();

    logger.info("Successfully created connection to {} after {} ms ({} ms spent in bootstraps)", address,
            (postBootstrap - preConnect) / 1000000, (postBootstrap - preBootstrap) / 1000000);

    return client;
}

From source file:org.spongepowered.clean.network.NetworkManager.java

License:MIT License

public void startListening(int port) {
    try {/*from   ww w.  j  av a2 s .co  m*/
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(1024);
        this.serverkeys = generator.generateKeyPair();
    } catch (NoSuchAlgorithmException e) {
        CoreScheduler.emergencyShutdown(e);
    }

    this.bossGroup = new NioEventLoopGroup();
    this.workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(this.bossGroup, this.workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {

                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast("splitter", new PacketSplitter());
                    ch.pipeline().addLast("decoder", new PacketDecoder());
                    ch.pipeline().addLast("length_appender", new PacketLengthAppender());
                    ch.pipeline().addLast("encoder", new PacketEncoder());
                    NetworkConnection conn = new NetworkConnection();
                    NetworkManager.this.activeConnections.add(conn);
                    ch.pipeline().addLast("handler", new PacketHandler(conn));
                }
            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

    this.channel = b.bind(port).syncUninterruptibly();
    SGame.getLogger().info("Now listening on port " + port);
}

From source file:org.spout.engine.SpoutServer.java

License:Open Source License

@Override
public void init(SpoutApplication args) {
    super.init(args);
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new CommonChannelInitializer()).childOption(ChannelOption.TCP_NODELAY, true)
            .childOption(ChannelOption.SO_KEEPALIVE, true);

    accessManager.load();//  ww  w  .  j av  a  2 s  . c o m
    accessManager.setWhitelistEnabled(SpoutConfiguration.WHITELIST_ENABLED.getBoolean());
}

From source file:org.starnub.utilities.connectivity.client.TCPClient.java

License:Open Source License

public ChannelFuture connect(String ipAddress, int port, ChannelInitializer<SocketChannel> channelInitializer) {
    Bootstrap b = new Bootstrap().group(workerGroup).channel(NioSocketChannel.class)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.SO_KEEPALIVE, true).handler(channelInitializer);
    return b.connect(ipAddress, port);
}

From source file:org.starnub.utilities.connectivity.server.TCPServer.java

License:Open Source License

public Channel start(int port, ChannelInitializer<SocketChannel> channelInitializer) {
    ServerBootstrap sb = new ServerBootstrap();
    sb.group(connectionBossGroup, connectionWorkerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.SO_KEEPALIVE, true).childHandler(channelInitializer);
    return sb.bind(port).channel();

}

From source file:org.stem.client.old.StorageNodeClient.java

License:Apache License

private void initBootstrap() {
    bootstrap = new Bootstrap();

    EventLoopGroup workerGroup = new NioEventLoopGroup();

    bootstrap.group(workerGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.TCP_NODELAY, true)
            //.option(ChannelOption.SO_TIMEOUT, 100)

            .handler(new ChannelFactory());
}

From source file:org.stem.net.Server.java

License:Apache License

public void start() {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 100).childOption(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.TCP_NODELAY, true).handler(new LoggingHandler(LogLevel.TRACE))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override//from  ww w. jav  a  2s. com
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new PacketDecoder()).addLast(new PacketEncoder())

                            .addLast(new MessageDecoder()).addLast(new MessageEncoder())

                            .addLast(new MessageDispatcher());
                }
            });

    try {
        future = bootstrap.bind(socket).sync();
        logger.info("Starting listening for clients on {}...", socket);
        channel = future.channel();

        // Wait until server socket is closed.
        // channel.closeFuture().sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
        throw new RuntimeException("Can't start server: ", e);
    }

}

From source file:org.teiid.transport.SocketListener.java

License:Apache License

public SocketListener(final InetSocketAddress address, final int inputBufferSize, final int outputBufferSize,
        int maxWorkers, final SSLConfiguration config, final ClientServiceRegistryImpl csr,
        final StorageManager storageManager) {

    if (config != null) {
        this.isClientEncryptionEnabled = config.isClientEncryptionEnabled();
    }/*w w w . ja v  a 2s .  c  o m*/
    this.csr = csr;

    NamedThreadFactory nettyPool = new NamedThreadFactory("NIO"); //$NON-NLS-1$
    if (LogManager.isMessageToBeRecorded(LogConstants.CTX_TRANSPORT, MessageLevel.DETAIL)) {
        LogManager.logDetail(LogConstants.CTX_TRANSPORT,
                "server = " + address.getAddress() + "binding to port:" + address.getPort()); //$NON-NLS-1$ //$NON-NLS-2$
    }

    if (maxWorkers == 0) {
        maxWorkers = Math.max(4, PropertiesUtils.getIntProperty(System.getProperties(),
                "io.netty.eventLoopThreads", 2 * Runtime.getRuntime().availableProcessors())); //$NON-NLS-1$
    }
    EventLoopGroup workers = new NioEventLoopGroup(maxWorkers, nettyPool);

    bootstrap = new ServerBootstrap();
    bootstrap.group(workers).channel(NioServerSocketChannel.class);
    this.channelHandler = createChannelHandler();
    bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            configureChannelPipeline(pipeline, config, storageManager);
        }
    });
    if (inputBufferSize != 0) {
        bootstrap.childOption(ChannelOption.SO_RCVBUF, new Integer(inputBufferSize));
    }
    if (outputBufferSize != 0) {
        bootstrap.childOption(ChannelOption.SO_SNDBUF, new Integer(outputBufferSize));
    }
    bootstrap.childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE);
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);
    ChannelFuture future = bootstrap.bind(address);
    future.syncUninterruptibly();
    this.serverChannel = future.channel();
}

From source file:org.telegram.server.TelegramServer.java

License:Open Source License

public void run() throws Exception {
    HazelcastConnection.getInstance();//from www  . ja v  a  2s . c  o m
    DatabaseConnection.getInstance();
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new MTProtoDecoder(), new MTProtoEncoder(),
                                new TelegramServerHandler());
                    }
                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

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

        // 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();
    }
}