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.ethereum.net.server.PeerServerImpl.java

License:Open Source License

public void start(int port) {
    // TODO review listening use
    listening = true;/*from   w  w  w . java2 s.com*/

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

    ethereumChannelInitializer = ctx.getBean(EthereumChannelInitializer.class, "");

    ethereumListener.trace("Listening on port " + port);

    try {
        ServerBootstrap b = new ServerBootstrap();

        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);

        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, DefaultMessageSizeEstimator.DEFAULT);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.peerConnectionTimeout());

        b.handler(new LoggingHandler());
        b.childHandler(ethereumChannelInitializer);

        // Start the client.
        logger.info("Listening for incoming connections, port: [{}] ", port);
        logger.info("NodeId: [{}] ", Hex.toHexString(config.nodeId()));

        ChannelFuture f = b.bind(port).sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
        logger.debug("Connection is closed");

        // TODO review listening use
        listening = false;
    } catch (Exception e) {
        logger.debug("Exception: {} ({})", e.getMessage(), e.getClass().getName());
        throw new Error("Server Disconnected");
    } finally {
        workerGroup.shutdownGracefully();

    }
}

From source file:org.evilco.network.rcon.server.AbstractRconServer.java

License:Apache License

/**
 * Constructs a new AbstractRconServer instance.
 * @param eventBus The event bus.//from   w  w  w. jav  a2 s.com
 * @param registry The command registry.
 * @param password The server password.
 */
public AbstractRconServer(@NonNull EventBus eventBus, @NonNull ICommandRegistry registry,
        @NonNull String password) {
    // store arguments
    this.eventBus = eventBus;
    this.commandRegistry = registry;
    this.password = password;

    // create groups
    this.groupBoss = this.createEventLoopGroup();
    this.groupWorker = this.createEventLoopGroup();

    // create bootstrap
    this.bootstrap = new ServerBootstrap();

    // set groups
    this.bootstrap.group(this.groupBoss, this.groupWorker);

    // set properties
    this.bootstrap.channel(this.getChannelType());
    this.bootstrap.childHandler(this.createChannelInitializer());

    this.bootstrap.option(ChannelOption.SO_BACKLOG, 128);
    this.bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
}

From source file:org.fengbaoxp.netty.official.AbstractServer.java

License:Apache License

protected void run(ChannelHandler channelHandler, int port) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {//from ww  w.  j a  va2  s  .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(channelHandler);
                    }
                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

        ChannelFuture f = b.bind(port).sync();

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

From source file:org.fengbaoxp.netty.official.TimeClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    String host = "127.0.0.1";
    int port = 9000;
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {/*from   w w w  .  j a v  a 2 s. co m*/
        Bootstrap b = new Bootstrap();
        b.group(workerGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new TimeClientHandler());
                    }
                });
        ChannelFuture f = b.connect(host, port).sync();
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
    }
}

From source file:org.freeswitch.esl.client.inbound.Client.java

License:Apache License

/**
 * Attempt to establish an authenticated connection to the nominated FreeSWITCH ESL server socket.
 * This call will block, waiting for an authentication handshake to occur, or timeout after the
 * supplied number of seconds./*from   ww  w . j a v a 2  s  .c o m*/
 *
 * @param clientAddress  a SocketAddress representing the endpoint to connect to
 * @param password       server event socket is expecting (set in event_socket_conf.xml)
 * @param timeoutSeconds number of seconds to wait for the server socket before aborting
 */
public void connect(SocketAddress clientAddress, String password, int timeoutSeconds)
        throws InboundConnectionFailure {
    // If already connected, disconnect first
    if (canSend()) {
        close();
    }

    log.info("Connecting to {} ...", clientAddress);

    EventLoopGroup workerGroup = new NioEventLoopGroup();

    // Configure this client
    Bootstrap bootstrap = new Bootstrap().group(workerGroup).channel(NioSocketChannel.class)
            .option(ChannelOption.SO_KEEPALIVE, true);

    // Add ESL handler and factory
    InboundClientHandler handler = new InboundClientHandler(password, protocolListener);
    bootstrap.handler(new InboundChannelInitializer(handler));

    // Attempt connection
    ChannelFuture future = bootstrap.connect(clientAddress);

    // Wait till attempt succeeds, fails or timeouts
    if (!future.awaitUninterruptibly(timeoutSeconds, TimeUnit.SECONDS)) {
        throw new InboundConnectionFailure("Timeout connecting to " + clientAddress);
    }
    // Did not timeout
    final Channel channel = future.channel();
    // But may have failed anyway
    if (!future.isSuccess()) {
        log.warn("Failed to connect to [{}]", clientAddress, future.cause());

        workerGroup.shutdownGracefully();

        throw new InboundConnectionFailure("Could not connect to " + clientAddress, future.cause());
    }

    log.info("Connected to {}", clientAddress);

    //  Wait for the authentication handshake to call back
    while (!authenticatorResponded.get()) {
        try {
            Thread.sleep(250);
        } catch (InterruptedException e) {
            // ignore
        }
    }

    this.clientContext = Optional.of(new Context(channel, handler));

    if (!authenticated) {
        throw new InboundConnectionFailure("Authentication failed: " + authenticationResponse.getReplyText());
    }

    log.info("Authenticated");
}

From source file:org.freeswitch.esl.client.outbound.SocketClient.java

License:Apache License

@Override
protected void doStart() {
    final ServerBootstrap bootstrap = new ServerBootstrap().group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .childHandler(new OutboundChannelInitializer(clientHandlerFactory))
            .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true);

    serverChannel = bootstrap.bind(bindAddress).syncUninterruptibly().channel();
    notifyStarted();/*w w w  .  j  a v  a  2s.c o  m*/
    log.info("SocketClient waiting for connections on [{}] ...", bindAddress);
}

From source file:org.gamejam.gc.fartroulette.WhoFartedServer.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//from w  ww.ja v  a  2s. c  o m
        final ServerBootstrap sb = new ServerBootstrap();
        sb.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(final SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new HttpRequestDecoder(), new HttpObjectAggregator(65536),
                                new HttpResponseEncoder(),
                                new HttpStaticFileServerHandler(true, "websocket", "api"),
                                new WebSocketServerProtocolHandler("/websocket"),
                                new WebSocketFrameHandler(s_allChannels, s_elevatorData));

                    }
                }).option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.SO_TIMEOUT, 100)
                .childOption(ChannelOption.SO_KEEPALIVE, true);

        //loadDummyData();

        runUpdaterThread();

        runGame();

        final Channel ch = sb.bind(port).sync().channel();
        System.out.println("Web socket server started at port " + port);

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

From source file:org.gameoss.gridcast.p2p.node.NodeClient.java

License:Apache License

public void initialize(final String host, int port, final EventLoopGroup workerGroup,
        final MessageRegistry messageRegistry, final ChannelInboundHandlerAdapter channelListener)
        throws InterruptedException {
    // prepare connection
    Bootstrap boot = new Bootstrap();
    boot.group(workerGroup);//from  w w w  .  j  a v  a2 s .  c  om
    boot.channel(NioSocketChannel.class);
    boot.option(ChannelOption.SO_KEEPALIVE, true);
    boot.option(ChannelOption.TCP_NODELAY, true);
    boot.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();

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

    // connect
    channel = boot.connect(host, port).sync().channel();
}

From source file:org.gameoss.gridcast.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  av a  2s . co m
    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();

            // 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 {
        if (host == null) {
            acceptChannel = boot.bind(port).sync().channel();
        } else {
            acceptChannel = boot.bind(host, port).sync().channel();
        }
    } catch (InterruptedException e) {
        logger.error("Binding to port {} failed", port, e);
    }

}

From source file:org.graylog2.gelfclient.transport.GelfTcpTransport.java

License:Apache License

@Override
protected void createBootstrap(final EventLoopGroup workerGroup) {
    final Bootstrap bootstrap = new Bootstrap();
    final GelfSenderThread senderThread = new GelfSenderThread(queue);

    bootstrap.group(workerGroup).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectTimeout())
            .option(ChannelOption.TCP_NODELAY, config.isTcpNoDelay())
            .option(ChannelOption.SO_KEEPALIVE, config.isTcpKeepAlive())
            .remoteAddress(config.getRemoteAddress()).handler(new ChannelInitializer<SocketChannel>() {
                @Override/*  w w  w  .  j ava  2  s .c o  m*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    if (config.isTlsEnabled()) {
                        LOG.debug("TLS enabled.");
                        final SslContext sslContext;

                        if (!config.isTlsCertVerificationEnabled()) {
                            // If the cert should not be verified just use an insecure trust manager.
                            LOG.debug("TLS certificate verification disabled!");
                            sslContext = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
                        } else if (config.getTlsTrustCertChainFile() != null) {
                            // If a cert chain file is set, use it.
                            LOG.debug("TLS certificate chain file: {}", config.getTlsTrustCertChainFile());
                            sslContext = SslContext.newClientContext(config.getTlsTrustCertChainFile());
                        } else {
                            // Otherwise use the JVM default cert chain.
                            sslContext = SslContext.newClientContext();
                        }

                        ch.pipeline().addLast(sslContext.newHandler(ch.alloc()));
                    }

                    // We cannot use GZIP encoding for TCP because the headers contain '\0'-bytes then.
                    // The graylog2-server uses '\0'-bytes as delimiter for TCP frames.
                    ch.pipeline().addLast(new GelfMessageJsonEncoder());
                    ch.pipeline().addLast(new SimpleChannelInboundHandler<ByteBuf>() {
                        @Override
                        protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
                            // We do not receive data.
                        }

                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            senderThread.start(ctx.channel());
                        }

                        @Override
                        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                            LOG.info("Channel disconnected!");
                            senderThread.stop();
                            scheduleReconnect(ctx.channel().eventLoop());
                        }

                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
                                throws Exception {
                            LOG.error("Exception caught", cause);
                        }
                    });
                }
            });

    if (config.getSendBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, config.getSendBufferSize());
    }

    bootstrap.connect().addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                LOG.debug("Connected!");
            } else {
                LOG.error("Connection failed: {}", future.cause().getMessage());
                scheduleReconnect(future.channel().eventLoop());
            }
        }
    });
}