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.yeetor.androidcontrol.server.LocalServer.java

License:Open Source License

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

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.SO_KEEPALIVE, true)
            .childHandler(new ChildChannel(new LocalServerWebsocketEventImp()));
    System.out.println("LocalServer will start at port: " + port);
    System.out.println("--------\r\n");
    ChannelFuture future = bootstrap.bind(port).sync();
    future.channel().closeFuture().sync();
}

From source file:com.yeetor.androidcontrol.server.RemoteServer.java

License:Open Source License

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

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.SO_KEEPALIVE, true)
            .childHandler(new ChildChannel(new RemoteServerWebsocketEventImp()));
    System.out.println("RemoteServer will start at port: " + port);
    System.out.println("--------\r\n");
    ChannelFuture future = bootstrap.bind(port).sync();
    future.channel().closeFuture().sync();
}

From source file:com.yeetor.console.Console.java

License:Open Source License

/**
 * Console??//from  www  .ja v  a2 s. co  m
 * @param port
 */
public void listenOnTCP(int port) {
    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 Adapter());
                    }
                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

        ChannelFuture f = b.bind(port);

        f.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}

From source file:com.yeetor.server.AndroidControlServer.java

License:Open Source License

public void listen(int port) throws InterruptedException {
    try {//from ww w  .j  a va 2  s. co m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast("tcp", new TCPHandler());
                        ch.pipeline().addLast("http-codec", new HttpServerCodec());
                        ch.pipeline().addLast("aggregator", new HttpObjectAggregator(65536));
                        ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
                        ch.pipeline().addLast("websocket", new WSHandler(new WSServer()));
                        ch.pipeline().addLast("http", new HTTPHandler(new HttpServer()));
                    }
                });
        ChannelFuture f = b.bind(port).sync();
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}

From source file:com.zaradai.distributor.messaging.netty.NettyClient.java

License:Apache License

private void configure(Bootstrap b) {
    b.option(ChannelOption.TCP_NODELAY, config.getTcpNoDelay());
    b.option(ChannelOption.SO_KEEPALIVE, config.getKeepAlive());
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectionTimeout());
}

From source file:com.zaradai.distributor.messaging.netty.NettyServer.java

License:Apache License

private void configure(ServerBootstrap b) {
    b.option(ChannelOption.SO_BACKLOG, config.getAcceptBacklog());
    b.option(ChannelOption.SO_REUSEADDR, config.getReuseAddress());
    b.childOption(ChannelOption.TCP_NODELAY, config.getTcpNoDelay());
    b.childOption(ChannelOption.SO_KEEPALIVE, config.getKeepAlive());
}

From source file:com.zextras.modules.chat.server.xmpp.netty.ChatXmppService.java

License:Open Source License

private ServerBootstrap buildBoostrap(EventLoopGroup acceptorGroup, EventLoopGroup workerGroup,
        final SSLContext zimbraSSLContext, final boolean oldSSL) {

    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(acceptorGroup, workerGroup);

    serverBootstrap.channel(NioServerSocketChannel.class);

    ChannelHandler handler = new ChannelInitializer<SocketChannel>() {
        @Override/*from   w w  w. j  av  a2s .co m*/
        public void initChannel(SocketChannel ch) throws Exception {
            try {
                if (oldSSL) {
                    final SSLEngine engine = zimbraSSLContext.createSSLEngine();
                    engine.setUseClientMode(false);
                    ch.pipeline().addFirst(null, "SSL", new SslHandler(engine, false));
                }

                ch.pipeline().addLast(null, "SubTagTokenizer", new XmlSubTagTokenizer());
                FirstTags firstTagsHandler = new FirstTags(mXmppHandlerFactory, mEventManager, ch,
                        mSchemaProvider, zimbraSSLContext, oldSSL, mChatProperties, mNettyService,
                        mProxyAuthRequestEncoder, mXmppEventFilter, mXmppFilterOut);
                ch.pipeline().addAfter("SubTagTokenizer", "FirstTags", firstTagsHandler);
            } catch (Throwable ex) {
                ChatLog.log.warn("Unable to initialize XMPP connection: " + Utils.exceptionToString(ex));
                ch.close();
            }
        }
    };

    serverBootstrap.childHandler(handler).option(ChannelOption.SO_BACKLOG, 128)
            .childOption(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 0);

    return serverBootstrap;
}

From source file:com.zextras.modules.chat.services.LocalXmppService.java

License:Open Source License

@Override
public void run() {
    ChatLog.log.info("Listening on port " + DEFAULT_LOCAL_XMPP_PORT);
    EventLoopGroup acceptorGroup = new NioEventLoopGroup(4);
    EventLoopGroup channelWorkerGroup = new NioEventLoopGroup(8);

    Channel channel;/*from  w w w  .  j  av  a2 s .co  m*/
    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(acceptorGroup, channelWorkerGroup);
        bootstrap.channel(NioServerSocketChannel.class);
        ChannelHandler handler = new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                try {
                    SSLEngine sslEngine = mZimbraSSLContextProvider.get().createSSLEngine();
                    sslEngine.setUseClientMode(false);
                    SslHandler sslHandler = new SslHandler(sslEngine);
                    ch.pipeline().addFirst("ssl", sslHandler);
                    ch.pipeline().addLast(null, "SubTagTokenizer", new XmlSubTagTokenizer());
                    ch.pipeline().addLast(null, "XmlTagTokenizer", new XmlTagTokenizer());
                    ch.pipeline().addAfter("XmlTagTokenizer", "StanzaProcessor",
                            new ChannelInboundHandlerAdapter() {
                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg) {
                                    mLocalXmppReceiver.processStanza((String) msg);
                                }
                            });
                } catch (Throwable t) {
                    ChatLog.log.warn("Unable to initializer XMPP connection: " + Utils.exceptionToString(t));
                    ch.close();
                }
            }
        };

        ChannelFuture channelFuture = bootstrap.childHandler(handler).option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 0).bind(DEFAULT_LOCAL_XMPP_PORT).sync();

        if (!channelFuture.isSuccess()) {
            throw channelFuture.cause();
        }

        channel = channelFuture.channel();
        mInitializationPromise.setSuccess(null);
    } catch (Throwable e) {
        mInitializationPromise.setFailure(e);
        return;
    }

    mLock.lock();
    try {
        while (!mStopRequested) {
            try {
                mWaitStopRequest.await();
            } catch (InterruptedException ignored) {
            }
        }

        channel.close().sync();

        acceptorGroup.shutdownGracefully().sync();
        channelWorkerGroup.shutdownGracefully().sync();
    } catch (InterruptedException ignored) {
    } finally {
        mLock.unlock();
    }
}

From source file:com.zhang.pool.NettyChannelPool.java

License:Apache License

/**
 * Create a new instance of ChannelPool// w w w .j a  v a2 s. co m
 * 
 * @param maxPerRoute
 *            max number of channels per route allowed in pool
 * @param connectTimeOutInMilliSecondes
 *            max time wait for a channel return from pool
 * @param maxIdleTimeInMilliSecondes
 *            max idle time for a channel before close
 * @param forbidForceConnect
 *            value is false indicates that when there is not any channel in pool and no new
 *            channel allowed to be create based on maxPerRoute, a new channel will be forced
 *            to create.Otherwise, a <code>TimeoutException</code> will be thrown. The default
 *            value is false. 
 * @param additionalChannelInitializer
 *            user-defined initializer
 * @param options
 *            user-defined options
 * @param customGroup user defined {@link EventLoopGroup}
 */
@SuppressWarnings("unchecked")
public NettyChannelPool(Map<String, Integer> maxPerRoute, int connectTimeOutInMilliSecondes,
        int maxIdleTimeInMilliSecondes, boolean forbidForceConnect,
        AdditionalChannelInitializer additionalChannelInitializer, Map<ChannelOption, Object> options,
        EventLoopGroup customGroup) {

    this.additionalChannelInitializer = additionalChannelInitializer;
    this.maxIdleTimeInMilliSecondes = maxIdleTimeInMilliSecondes;
    this.connectTimeOutInMilliSecondes = connectTimeOutInMilliSecondes;
    this.maxPerRoute = new ConcurrentHashMap<String, Semaphore>();
    this.routeToPoolChannels = new ConcurrentHashMap<String, LinkedBlockingQueue<Channel>>();
    this.group = null == customGroup ? new NioEventLoopGroup() : customGroup;
    this.forbidForceConnect = forbidForceConnect;

    this.clientBootstrap = new Bootstrap();
    clientBootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new ChannelInitializer() {
                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ch.pipeline().addLast("log", new LoggingHandler(LogLevel.INFO));

                    ch.pipeline().addLast(HttpClientCodec.class.getSimpleName(), new HttpClientCodec());
                    if (null != NettyChannelPool.this.additionalChannelInitializer) {
                        NettyChannelPool.this.additionalChannelInitializer.initChannel(ch);
                    }

                    ch.pipeline().addLast(HttpObjectAggregator.class.getSimpleName(),
                            new HttpObjectAggregator(1048576));

                    ch.pipeline().addLast(IdleStateHandler.class.getSimpleName(), new IdleStateHandler(0, 0,
                            NettyChannelPool.this.maxIdleTimeInMilliSecondes, TimeUnit.MILLISECONDS));

                    ch.pipeline().addLast(NettyChannelPoolHandler.class.getSimpleName(),
                            new NettyChannelPoolHandler(NettyChannelPool.this));
                }

            });
    if (null != options) {
        for (Entry<ChannelOption, Object> entry : options.entrySet()) {
            clientBootstrap.option(entry.getKey(), entry.getValue());
        }
    }

    if (null != maxPerRoute) {
        for (Entry<String, Integer> entry : maxPerRoute.entrySet()) {
            this.maxPerRoute.put(entry.getKey(), new Semaphore(entry.getValue()));
        }
    }

}

From source file:com.zhucode.longio.transport.netty.NettyConnector.java

License:Open Source License

private void runOneHttpServer(int port, Dispatcher dispatcher, ProtocolType pt) {
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup);/*from   www.ja  va  2  s .  c om*/
    b.channel(NioServerSocketChannel.class);

    b.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new HttpServerCodec());
            ch.pipeline().addLast(new HttpObjectAggregator(65536));
            ch.pipeline().addLast(new IdleStateHandler(6000, 3000, 0));
            ch.pipeline().addLast(new HttpHandler(NettyConnector.this, dispatcher, callbackDispatcher,
                    getProtocolParser(pt)));
        }

    });
    b.option(ChannelOption.SO_BACKLOG, 4096);

    b.childOption(ChannelOption.SO_KEEPALIVE, true);

    ChannelFuture f;
    try {
        f = b.bind(port).sync();
        f.channel().closeFuture().sync();
    } catch (Exception e) {
        e.printStackTrace();
    }
}