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:com.kixeye.kixmpp.p2p.node.NodeServer.java

License:Apache License

public void initialize(final String host, final int port, final EventLoopGroup bossGroup,
        final EventLoopGroup workerGroup, final MessageRegistry messageRegistry,
        final ChannelInboundHandlerAdapter channelListener) {
    ServerBootstrap boot = new ServerBootstrap();
    boot.group(bossGroup, workerGroup);// w w  w.  j  a va2 s  . com
    boot.channel(NioServerSocketChannel.class);
    boot.option(ChannelOption.SO_BACKLOG, 32);
    boot.childOption(ChannelOption.SO_KEEPALIVE, true);
    boot.childOption(ChannelOption.TCP_NODELAY, true);
    boot.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();

            //p.addLast(new LoggingHandler());

            // encoders
            p.addLast(new LengthFieldPrepender(4));
            p.addLast(new ProtostuffEncoder(messageRegistry));

            // decoders
            p.addLast(new LengthFieldBasedFrameDecoder(0x100000, 0, 4, 0, 4));
            p.addLast(new ProtostuffDecoder(messageRegistry));
            p.addLast(channelListener);
        }
    });

    // start accepting connection
    try {
        logger.info("Starting NodeServer on [{}]...", port);

        if (host == null) {
            acceptChannel = boot.bind(port).sync().channel();
        } else {
            acceptChannel = boot.bind(host, port).sync().channel();
        }

        logger.info("NodeServer listening on [{}]...", port);
    } catch (InterruptedException e) {
        logger.error("Binding to port {} failed", port, e);
    }

}

From source file:com.l2jmobius.gameserver.network.loginserver.LoginServerNetworkManager.java

License:Open Source License

public LoginServerNetworkManager() {
    //@formatter:off
    _bootstrap = new Bootstrap().group(EventLoopGroupManager.getInstance().getWorkerGroup())
            .channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new LoginServerInitializer());
    //@formatter:on
}

From source file:com.l2jmobius.gameserver.network.telnet.TelnetServer.java

License:Open Source License

public void init() {
    addHandler(new ITelnetCommand() {
        @Override//from  ww  w.  j  a v  a 2s  . c o  m
        public String getCommand() {
            return "help";
        }

        @Override
        public String getUsage() {
            return "help [command]";
        }

        @Override
        public String handle(ChannelHandlerContext ctx, String[] args) {
            if (args.length == 0) {
                final StringBuilder sb = new StringBuilder("Available commands:" + Config.EOL);
                for (ITelnetCommand cmd : TelnetServer.getInstance().getCommands()) {
                    sb.append(cmd.getCommand() + Config.EOL);
                }
                return sb.toString();
            }
            final ITelnetCommand cmd = TelnetServer.getInstance().getCommand(args[0]);
            if (cmd == null) {
                return "Unknown command." + Config.EOL;
            }
            return "Usage:" + Config.EOL + cmd.getUsage() + Config.EOL;
        }
    });

    try {
        final InetSocketAddress socket = Config.TELNET_HOSTNAME.equals("*")
                ? new InetSocketAddress(Config.TELNET_PORT)
                : new InetSocketAddress(Config.TELNET_HOSTNAME, Config.TELNET_PORT);
        //@formatter:off
        new ServerBootstrap().group(_workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true).childHandler(new TelnetServerInitializer())
                .bind(socket);
        //@formatter:on
        LOGGER.info(getClass().getSimpleName() + ": Listening on " + Config.TELNET_HOSTNAME + ":"
                + Config.TELNET_PORT);
    } catch (Exception e) {
        LOGGER.log(Level.WARNING, e.getMessage(), e);
    }
}

From source file:com.lambdaworks.redis.AbstractRedisClient.java

License:Apache License

/**
 * Populate connection builder with necessary resources.
 *
 * @param handler instance of a CommandHandler for writing redis commands
 * @param connection implementation of a RedisConnection
 * @param socketAddressSupplier address supplier for initial connect and re-connect
 * @param connectionBuilder connection builder to configure the connection
 * @param redisURI URI of the redis instance
 */// ww w. ja v a  2 s . com
protected void connectionBuilder(CommandHandler<?, ?> handler, RedisChannelHandler<?, ?> connection,
        Supplier<SocketAddress> socketAddressSupplier, ConnectionBuilder connectionBuilder, RedisURI redisURI) {

    Bootstrap redisBootstrap = new Bootstrap();
    redisBootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
    redisBootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
    redisBootstrap.option(ChannelOption.ALLOCATOR, BUF_ALLOCATOR);

    SocketOptions socketOptions = getOptions().getSocketOptions();

    redisBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
            (int) socketOptions.getConnectTimeoutUnit().toMillis(socketOptions.getConnectTimeout()));

    if (LettuceStrings.isEmpty(redisURI.getSocket())) {
        redisBootstrap.option(ChannelOption.SO_KEEPALIVE, socketOptions.isKeepAlive());
        redisBootstrap.option(ChannelOption.TCP_NODELAY, socketOptions.isTcpNoDelay());
    }

    connectionBuilder.timeout(redisURI.getTimeout(), redisURI.getUnit());
    connectionBuilder.password(redisURI.getPassword());

    connectionBuilder.bootstrap(redisBootstrap);
    connectionBuilder.channelGroup(channels).connectionEvents(connectionEvents).timer(timer);
    connectionBuilder.commandHandler(handler).socketAddressSupplier(socketAddressSupplier)
            .connection(connection);
    connectionBuilder.workerPool(genericWorkerPool);
}

From source file:com.liferay.nativity.control.findersync.FSNativityControlImpl.java

License:Open Source License

@Override
public boolean connect() {
    if (_connected) {
        return true;
    }//  ww w.ja v  a 2  s. c  om

    _childEventLoopGroup = new NioEventLoopGroup();
    _parentEventLoopGroup = new NioEventLoopGroup();

    try {
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        serverBootstrap.group(_parentEventLoopGroup, _childEventLoopGroup);

        serverBootstrap.channel(NioServerSocketChannel.class);

        ChannelInitializer channelInitializer = new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {

                DelimiterBasedFrameDecoder messageDecoder = new DelimiterBasedFrameDecoder(Integer.MAX_VALUE,
                        Delimiters.lineDelimiter());

                FinderSyncChannelHandler finderSyncChannelHandler = new FinderSyncChannelHandler();

                socketChannel.pipeline().addLast(messageDecoder, finderSyncChannelHandler);
            }
        };

        serverBootstrap.childHandler(channelInitializer);

        serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

        ChannelFuture channelFuture = serverBootstrap.bind(0).sync();

        InetSocketAddress inetSocketAddress = (InetSocketAddress) channelFuture.channel().localAddress();

        _writePortToFile(inetSocketAddress.getPort());
    } catch (Exception e) {
        _logger.error(e.getMessage(), e);

        _connected = false;

        return false;
    }

    _connected = true;

    return true;
}

From source file:com.liferay.sync.engine.lan.server.file.LanFileServer.java

License:Open Source License

public void start() throws Exception {
    _childEventLoopGroup = new NioEventLoopGroup();
    _parentEventLoopGroup = new NioEventLoopGroup(1);

    ServerBootstrap serverBootstrap = new ServerBootstrap();

    serverBootstrap.group(_parentEventLoopGroup, _childEventLoopGroup);
    serverBootstrap.channel(NioServerSocketChannel.class);

    _syncTrafficShapingHandler = new SyncTrafficShapingHandler(_childEventLoopGroup);

    _lanFileServerInitializer = new LanFileServerInitializer(_syncTrafficShapingHandler);

    serverBootstrap.childHandler(_lanFileServerInitializer);

    serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

    ChannelFuture channelFuture = serverBootstrap.bind(PropsValues.SYNC_LAN_SERVER_PORT);

    try {/*from   www . ja v  a2 s  .c  o m*/
        channelFuture.sync();
    } catch (Exception e) {

        // Compiling fails when directly catching BindException. Netty seems
        // to throw an undeclared exception.

        if (e instanceof BindException) {
            channelFuture = serverBootstrap.bind(0);

            channelFuture.sync();
        } else {
            throw e;
        }
    }

    Channel channel = channelFuture.channel();

    InetSocketAddress inetSocketAddress = (InetSocketAddress) channel.localAddress();

    _port = inetSocketAddress.getPort();

    channelFuture.sync();

    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            long count = SyncFileService.getSyncFilesCount(SyncFile.UI_EVENT_DOWNLOADING,
                    SyncFile.UI_EVENT_UPLOADING);

            long writeDelay = 0;

            if (count > 0) {
                _syncTrafficShapingHandler.setWriteDelay(PropsValues.SYNC_LAN_SERVER_WRITE_DELAY);
            }

            _syncTrafficShapingHandler.setWriteDelay(writeDelay);
        }

    };

    ScheduledExecutorService scheduledExecutorService = LanEngine.getScheduledExecutorService();

    scheduledExecutorService.scheduleWithFixedDelay(runnable, 0, 500, TimeUnit.MILLISECONDS);
}

From source file:com.linecorp.armeria.client.ClientFactoryBuilder.java

License:Apache License

/**
 * Creates a new instance.
 */
public ClientFactoryBuilder() {
    connectTimeoutMillis(Flags.defaultConnectTimeoutMillis());
    socketOption(ChannelOption.SO_KEEPALIVE, true);
}

From source file:com.linecorp.armeria.client.NonDecoratingClientFactory.java

License:Apache License

private NonDecoratingClientFactory(SessionOptions options,
        Function<TransportType, ThreadFactory> threadFactoryFactory) {

    requireNonNull(options, "options");
    requireNonNull(threadFactoryFactory, "threadFactoryFactory");

    final Bootstrap baseBootstrap = new Bootstrap();

    baseBootstrap.channel(channelType());
    baseBootstrap.resolver(options.addressResolverGroup().orElseGet(DnsAddressResolverGroup5657::new));

    baseBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
            ConvertUtils.safeLongToInt(options.connectTimeoutMillis()));
    baseBootstrap.option(ChannelOption.SO_KEEPALIVE, true);

    final Optional<EventLoopGroup> eventLoopOption = options.eventLoopGroup();
    if (eventLoopOption.isPresent()) {
        eventLoopGroup = eventLoopOption.get();
        closeEventLoopGroup = false;// w  w w.  ja v  a 2 s.  com
    } else {
        eventLoopGroup = createGroup(threadFactoryFactory);
        closeEventLoopGroup = true;
    }

    this.baseBootstrap = baseBootstrap;
    this.options = options;
}

From source file:com.linecorp.armeria.client.RemoteInvokerFactory.java

License:Apache License

private RemoteInvokerFactory(RemoteInvokerOptions options,
        Function<TransportType, ThreadFactory> threadFactoryFactory) {

    requireNonNull(options, "options");
    requireNonNull(threadFactoryFactory, "threadFactoryFactory");

    final Bootstrap baseBootstrap = new Bootstrap();

    baseBootstrap.channel(channelType());
    baseBootstrap.resolver(options.addressResolverGroup().orElseGet(
            () -> new DnsAddressResolverGroup(datagramChannelType(), DnsServerAddresses.defaultAddresses())));

    baseBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
            ConvertUtils.safeLongToInt(options.connectTimeoutMillis()));
    baseBootstrap.option(ChannelOption.SO_KEEPALIVE, true);

    final Optional<EventLoopGroup> eventLoopOption = options.eventLoopGroup();
    if (eventLoopOption.isPresent()) {
        eventLoopGroup = eventLoopOption.get();
        closeEventLoopGroup = false;//from w  ww. j  a  va  2 s  .co m
    } else {
        eventLoopGroup = createGroup(threadFactoryFactory);
        closeEventLoopGroup = true;
    }

    final EnumMap<SessionProtocol, RemoteInvoker> remoteInvokers = new EnumMap<>(SessionProtocol.class);
    final HttpRemoteInvoker remoteInvoker = new HttpRemoteInvoker(baseBootstrap, options);

    SessionProtocol.ofHttp().forEach(protocol -> remoteInvokers.put(protocol, remoteInvoker));

    this.remoteInvokers = Collections.unmodifiableMap(remoteInvokers);
}

From source file:com.linkedin.pinot.transport.netty.NettyTCPServer.java

License:Apache License

@Override
protected ServerBootstrap getServerBootstrap() {
    ServerBootstrap b = new ServerBootstrap();
    b.group(_bossGroup, _workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(createChannelInitializer()).option(ChannelOption.SO_BACKLOG, 128)
            .childOption(ChannelOption.SO_KEEPALIVE, true);
    return b;/* www .  j a va2 s .c o m*/
}