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.newlandframework.rpc.netty.MessageRecvExecutor.java

License:Apache License

public void start() {
    try {//from  w ww .  jav a  2  s .c o  m
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(boss, worker).channel(NioServerSocketChannel.class)
                .childHandler(new MessageRecvChannelInitializer(handlerMap)
                        .buildRpcSerializeProtocol(serializeProtocol))
                .option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

        String[] ipAddr = serverAddress.split(MessageRecvExecutor.DELIMITER);

        if (ipAddr.length == 2) {
            String host = ipAddr[0];
            int port = Integer.parseInt(ipAddr[1]);
            ChannelFuture future = null;
            future = bootstrap.bind(host, port).sync();
            System.out.printf(
                    "[author tangjie] Netty RPC Server start success!\nip:%s\nport:%d\nprotocol:%s\n\n", host,
                    port, serializeProtocol);
            future.channel().closeFuture().sync();
        } else {
            System.out.printf("[author tangjie] Netty RPC Server start fail!\n");
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:com.newlandframework.rpc.netty.MessageSendInitializeTask.java

License:Apache License

public Boolean call() {
    Bootstrap b = new Bootstrap();
    b.group(eventLoopGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true);
    b.handler(new MessageSendChannelInitializer().buildRpcSerializeProtocol(protocol));

    ChannelFuture channelFuture = b.connect(serverAddress);
    channelFuture.addListener(new ChannelFutureListener() {
        public void operationComplete(final ChannelFuture channelFuture) throws Exception {
            if (channelFuture.isSuccess()) {
                MessageSendHandler handler = channelFuture.channel().pipeline().get(MessageSendHandler.class);
                RpcServerLoader.getInstance().setMessageSendHandler(handler);
            }// w  w w  .ja  v a2s.co  m
        }
    });
    return Boolean.TRUE;
}

From source file:com.openddal.server.NettyServer.java

License:Apache License

private ServerBootstrap configServer() {
    bossGroup = new NioEventLoopGroup(args.bossThreads, new DefaultThreadFactory("NettyBossGroup", true));
    workerGroup = new NioEventLoopGroup(args.workerThreads, new DefaultThreadFactory("NettyWorkerGroup", true));
    userExecutor = createUserThreadExecutor();
    Authenticator authenticator = createAuthenticator();
    ProcessorFactory processorFactory = createProcessorFactory();
    RequestFactory requestFactory = createRequestFactory();
    ResponseFactory responseFactory = createResponseFactory();
    final ProtocolHandler protocolHandler = new ProtocolHandler(authenticator, processorFactory, requestFactory,
            responseFactory, userExecutor);

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.TCP_NODELAY, true);

    if (args.socketTimeoutMills > 0) {
        b.childOption(ChannelOption.SO_TIMEOUT, args.socketTimeoutMills);
    }/* w w w .java  2 s.  com*/

    if (args.recvBuff > 0) {
        b.childOption(ChannelOption.SO_RCVBUF, args.recvBuff);
    }

    if (args.sendBuff > 0) {
        b.childOption(ChannelOption.SO_SNDBUF, args.sendBuff);
    }

    b.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(createProtocolDecoder(), /* createProtocolEncoder(), */ protocolHandler);
        }
    });

    return b;
}

From source file:com.publicCaptivation.stream2me.client.communication.Connection.java

public void makeConnection() throws InterruptedException {
    group = new NioEventLoopGroup(10);

    Bootstrap bootstrap = new Bootstrap().group(group).channel(NioSocketChannel.class)
            .option(ChannelOption.SO_KEEPALIVE, true).handler(new Initialiser());
    channel = bootstrap.connect(HOST, PORT).sync().channel();

    poolThread = new Thread(new Pool());
    poolThread.start();/*from  w ww  . j  a  va  2 s.c o m*/
}

From source file:com.qc.you.socket.server.Application.java

License:Apache License

@Bean(name = "tcpChannelOptions")
public Map<ChannelOption<?>, Object> tcpChannelOptions() {
    Map<ChannelOption<?>, Object> options = new HashMap<ChannelOption<?>, Object>();
    options.put(ChannelOption.SO_KEEPALIVE, keepAlive);
    options.put(ChannelOption.SO_BACKLOG, backlog);
    return options;
}

From source file:com.relayrides.pushy.apns.ApnsClientThread.java

License:Open Source License

/**
 * Constructs a new APNs client thread. The thread connects to the APNs gateway in the given {@code PushManager}'s
 * environment and reads notifications from the {@code PushManager}'s queue.
 * //  w w  w .  j  av  a 2s . c  o  m
 * @param pushManager the {@code PushManager} from which this client thread should read environment settings and
 * notifications
 */
public ApnsClientThread(final PushManager<T> pushManager) {
    super(String.format("ApnsClientThread-%d", ApnsClientThread.threadCounter.incrementAndGet()));

    this.pushManager = pushManager;

    this.sentNotificationBuffer = new SentNotificationBuffer<T>(SENT_NOTIFICATION_BUFFER_SIZE);

    this.bootstrap = new Bootstrap();
    this.bootstrap.group(this.pushManager.getWorkerGroup());
    this.bootstrap.channel(NioSocketChannel.class);
    this.bootstrap.option(ChannelOption.SO_KEEPALIVE, true);

    final ApnsClientThread<T> clientThread = this;
    this.bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel channel) throws Exception {
            final ChannelPipeline pipeline = channel.pipeline();

            if (pushManager.getEnvironment().isTlsRequired()) {
                pipeline.addLast("ssl", SslHandlerUtil.createSslHandler(pushManager.getKeyStore(),
                        pushManager.getKeyStorePassword()));
            }

            pipeline.addLast("decoder", new RejectedNotificationDecoder());
            pipeline.addLast("encoder", new ApnsPushNotificationEncoder());
            pipeline.addLast("handler", new ApnsErrorHandler(clientThread));
        }
    });
}

From source file:com.relayrides.pushy.apns.ApnsConnection.java

License:Open Source License

/**
 * Asynchronously connects to the APNs gateway in this connection's environment. The outcome of the connection
 * attempt is reported via this connection's listener.
 *
 * @see ApnsConnectionListener#handleConnectionSuccess(ApnsConnection)
 * @see ApnsConnectionListener#handleConnectionFailure(ApnsConnection, Throwable)
 *//*from w  w  w .ja  v a  2 s. co m*/
@SuppressWarnings("deprecation")
public synchronized void connect() {

    final ApnsConnection<T> apnsConnection = this;

    if (this.connectFuture != null) {
        throw new IllegalStateException(String.format("%s already started a connection attempt.", this.name));
    }

    final Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(this.eventLoopGroup);
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    // TODO Remove this when Netty 5 is available
    bootstrap.option(ChannelOption.AUTO_CLOSE, false);

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel channel) {
            final ChannelPipeline pipeline = channel.pipeline();

            final SSLEngine sslEngine = apnsConnection.sslContext.createSSLEngine();
            sslEngine.setUseClientMode(true);

            pipeline.addLast("ssl", new SslHandler(sslEngine));
            pipeline.addLast("decoder", new RejectedNotificationDecoder());
            pipeline.addLast("encoder", new ApnsPushNotificationEncoder());
            pipeline.addLast("handler", new ApnsConnectionHandler(apnsConnection));
        }
    });

    log.debug("{} beginning connection process.", apnsConnection.name);
    this.connectFuture = bootstrap.connect(this.environment.getApnsGatewayHost(),
            this.environment.getApnsGatewayPort());
    this.connectFuture.addListener(new GenericFutureListener<ChannelFuture>() {

        public void operationComplete(final ChannelFuture connectFuture) {
            if (connectFuture.isSuccess()) {
                log.debug("{} connected; waiting for TLS handshake.", apnsConnection.name);

                final SslHandler sslHandler = connectFuture.channel().pipeline().get(SslHandler.class);

                try {
                    sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() {

                        public void operationComplete(final Future<Channel> handshakeFuture) {
                            if (handshakeFuture.isSuccess()) {
                                log.debug("{} successfully completed TLS handshake.", apnsConnection.name);

                                apnsConnection.handshakeCompleted = true;
                                apnsConnection.listener.handleConnectionSuccess(apnsConnection);
                            } else {
                                log.debug("{} failed to complete TLS handshake with APNs gateway.",
                                        apnsConnection.name, handshakeFuture.cause());

                                connectFuture.channel().close();
                                apnsConnection.listener.handleConnectionFailure(apnsConnection,
                                        handshakeFuture.cause());
                            }
                        }
                    });
                } catch (NullPointerException e) {
                    log.warn("{} failed to get SSL handler and could not wait for a TLS handshake.",
                            apnsConnection.name);

                    connectFuture.channel().close();
                    apnsConnection.listener.handleConnectionFailure(apnsConnection, e);
                }
            } else {
                log.debug("{} failed to connect to APNs gateway.", apnsConnection.name, connectFuture.cause());

                apnsConnection.listener.handleConnectionFailure(apnsConnection, connectFuture.cause());
            }
        }
    });
}

From source file:com.relayrides.pushy.apns.MockApnsServer.java

License:Open Source License

public synchronized void start() throws InterruptedException {
    final ServerBootstrap bootstrap = new ServerBootstrap();

    bootstrap.group(this.eventLoopGroup);
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

    final MockApnsServer server = this;

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

        @Override/*from w ww.  j  a  v a 2s .  com*/
        protected void initChannel(final SocketChannel channel) throws Exception {
            channel.pipeline().addLast("ssl", new SslHandler(SSLTestUtil.createSSLEngineForMockServer()));
            channel.pipeline().addLast("encoder", new ApnsErrorEncoder());
            channel.pipeline().addLast("decoder", new ApnsPushNotificationDecoder());
            channel.pipeline().addLast("handler", new MockApnsServerHandler(server));
        }
    });

    this.channel = bootstrap.bind(this.port).await().channel();
}

From source file:com.sample.netty.socket.client.Client.java

public static void main(String[] args) throws Exception {
    String host = "localhost";
    int port = 8080;
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from   ww  w  .  j a  v a  2s.  co m*/
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new MessageDecoder(), new ClientHandlerInbound());
                ch.pipeline().addLast(new MessageEncoder(), new ClientHandlerOutbound());
            }
        });
        ChannelFuture f = b.connect(host, port).sync();
        f.channel().writeAndFlush(
                String.format("Usurio = '%s'", System.getProperties().getProperty("user.name")));
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
    }
}

From source file:com.sample.netty.socket.server.Server.java

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*  w  ww.  j av a 2  s  . c o  m*/
        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 MessageDecoder(), new ServerHandlerInbound());
                        ch.pipeline().addLast(new MessageEncoder(), new ServerHandlerOutbound());
                    }
                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
        ChannelFuture f = b.bind(port).sync();
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}