Example usage for io.netty.channel ChannelOption TCP_NODELAY

List of usage examples for io.netty.channel ChannelOption TCP_NODELAY

Introduction

In this page you can find the example usage for io.netty.channel ChannelOption TCP_NODELAY.

Prototype

ChannelOption TCP_NODELAY

To view the source code for io.netty.channel ChannelOption TCP_NODELAY.

Click Source Link

Usage

From source file:com.github.sparkfy.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<TransportClient>();
    final AtomicReference<Channel> channelRef = new AtomicReference<Channel>();

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override// w  w  w . j a  va2 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.debug("Successfully created connection to {} after {} ms ({} ms spent in bootstraps)", address,
            (postBootstrap - preConnect) / 1000000, (postBootstrap - preBootstrap) / 1000000);

    return client;
}

From source file:com.github.wangshuwei5.client.NettyClient.java

License:Apache License

public void connect(int port, String host) throws Exception {

    // ?NIO/*from   w w w. j  a v a  2s  . com*/

    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new NettyClientInitializer(SSLMODE.CSA.toString()));
        // ??
        ChannelFuture future = b.connect(new InetSocketAddress(host, port),
                new InetSocketAddress(NettyConstant.LOCALIP, NettyConstant.LOCAL_PORT)).sync();
        future.channel().closeFuture().sync();
    } finally {
        // ????????
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(1);
                    try {
                        connect(NettyConstant.PORT, NettyConstant.REMOTEIP);// ???
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

From source file:com.github.wolf480pl.ircd.netty.NettyServer.java

License:Open Source License

public ChannelFuture start() {
    if (!started.compareAndSet(false, true)) {
        return null;
    }/*from   ww  w . ja v  a2 s  .  co  m*/

    ServerBootstrap bootstrap = new ServerBootstrap();
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();

    IRCChannelInitializer initializer = new IRCChannelInitializer(handler);

    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(initializer)
            .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true);

    ChannelFuture future = bootstrap.bind(bindAddress);
    this.channel = future.channel();
    return future;
}

From source file:com.github.zk1931.jzab.NettyTransport.java

License:Apache License

/**
 * Constructs a NettyTransport object.//from www  . j  a  va2s .c om
 *
 * @param hostPort "hostname:port" string. The netty transport binds to the
 *                 port specified in the string.
 * @param receiver receiver callback.
 * @param sslParam Ssl parameters.
 * @param dir the directory used to store the received file.
 */
public NettyTransport(String hostPort, final Receiver receiver, ZabConfig.SslParameters sslParam,
        final File dir) throws InterruptedException, GeneralSecurityException, IOException {
    super(receiver);
    this.keyStore = sslParam.getKeyStore();
    this.trustStore = sslParam.getTrustStore();
    this.keyStorePassword = sslParam.getKeyStorePassword() != null
            ? sslParam.getKeyStorePassword().toCharArray()
            : null;
    this.trustStorePassword = sslParam.getTrustStorePassword() != null
            ? sslParam.getTrustStorePassword().toCharArray()
            : null;
    this.dir = dir;
    if (isSslEnabled()) {
        initSsl();
    }

    this.hostPort = hostPort;
    String[] address = hostPort.split(":", 2);
    int port = Integer.parseInt(address[1]);
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 128)
            .option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.TCP_NODELAY, true).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    if (isSslEnabled()) {
                        SSLEngine engine = serverContext.createSSLEngine();
                        engine.setUseClientMode(false);
                        engine.setNeedClientAuth(true);
                        ch.pipeline().addLast(new SslHandler(engine));
                    }
                    // Incoming handlers
                    ch.pipeline().addLast(new MainHandler());
                    ch.pipeline().addLast(new ServerHandshakeHandler());
                    ch.pipeline().addLast(new NotifyHandler());
                    ch.pipeline().addLast(new ServerErrorHandler());
                }
            });

    // Travis build fails once in a while because it fails to bind to a port.
    // This is most likely a transient failure. Retry binding for 5 times with
    // 1 second sleep in between before giving up.
    int bindRetryCount = 5;
    for (int i = 0;; i++) {
        try {
            channel = b.bind(port).sync().channel();
            LOG.info("Server started: {}", hostPort);
            return;
        } catch (Exception ex) {
            if (i >= bindRetryCount) {
                throw ex;
            }
            LOG.debug("Failed to bind to {}. Retrying after 1 second.", hostPort);
            Thread.sleep(1000);
        }
    }
}

From source file:com.github.zk1931.jzab.transport.NettyTransport.java

License:Apache License

/**
 * Constructs a NettyTransport object.//from   www .j a v  a  2 s .co m
 *
 * @param hostPort "hostname:port" string. The netty transport binds to the
 *                 port specified in the string.
 * @param receiver receiver callback.
 * @param sslParam Ssl parameters.
 * @param dir the directory used to store the received file.
 */
public NettyTransport(String hostPort, final Receiver receiver, SslParameters sslParam, final File dir)
        throws InterruptedException, GeneralSecurityException, IOException {
    super(receiver);
    this.keyStore = sslParam.getKeyStore();
    this.trustStore = sslParam.getTrustStore();
    this.keyStorePassword = sslParam.getKeyStorePassword() != null
            ? sslParam.getKeyStorePassword().toCharArray()
            : null;
    this.trustStorePassword = sslParam.getTrustStorePassword() != null
            ? sslParam.getTrustStorePassword().toCharArray()
            : null;
    this.dir = dir;
    if (isSslEnabled()) {
        initSsl();
    }

    this.hostPort = hostPort;
    String[] address = hostPort.split(":", 2);
    int port = Integer.parseInt(address[1]);
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 128)
            .option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.TCP_NODELAY, true).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    if (isSslEnabled()) {
                        SSLEngine engine = serverContext.createSSLEngine();
                        engine.setUseClientMode(false);
                        engine.setNeedClientAuth(true);
                        ch.pipeline().addLast(new SslHandler(engine));
                    }
                    // Incoming handlers
                    ch.pipeline().addLast(new MainHandler());
                    ch.pipeline().addLast(new ServerHandshakeHandler());
                    ch.pipeline().addLast(new NotifyHandler());
                    ch.pipeline().addLast(new ErrorHandler());
                    // Outgoing handlers.
                    ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(4));
                }
            });

    // Travis build fails once in a while because it fails to bind to a port.
    // This is most likely a transient failure. Retry binding for 5 times with
    // 1 second sleep in between before giving up.
    int bindRetryCount = 5;
    for (int i = 0;; i++) {
        try {
            channel = b.bind(port).sync().channel();
            LOG.info("Server started: {}", hostPort);
            return;
        } catch (Exception ex) {
            if (i >= bindRetryCount) {
                throw ex;
            }
            LOG.debug("Failed to bind to {}. Retrying after 1 second.", hostPort);
            Thread.sleep(1000);
        }
    }
}

From source file:com.google.cloud.pubsub.proxy.moquette.NettyAcceptor.java

License:Open Source License

private void initFactory(String host, int port, final PipelineInitializer pipeliner) {
    ServerBootstrap bootsrap = new ServerBootstrap();
    bootsrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/* ww w .  j a v a 2 s .c  om*/
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    try {
                        pipeliner.init(pipeline);
                    } catch (Throwable th) {
                        LOG.error("Severe error during pipeline creation", th);
                        throw th;
                    }
                }
            }).option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true);
    try {
        // Bind and start to accept incoming connections.
        ChannelFuture future = bootsrap.bind(host, port);
        LOG.info("Server binded host: {}, port: {}", host, port);
        future.sync();
    } catch (InterruptedException ex) {
        LOG.error(null, ex);
    }
}

From source file:com.googlecode.protobuf.pro.duplex.example.DuplexPingPongClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    if (args.length != 8) {
        System.err.println(//from  w  ww. j a v  a2s.  c  om
                "usage: <serverHostname> <serverPort> <clientHostname> <clientPort> <ssl=Y/N> <nodelay=Y/N> <compress=Y/N> <payloadSizeBytes>");
        System.exit(-1);
    }
    String serverHostname = args[0];
    int serverPort = Integer.parseInt(args[1]);
    String clientHostname = args[2];
    int clientPort = Integer.parseInt(args[3]);
    boolean secure = "Y".equals(args[4]);
    boolean nodelay = "Y".equals(args[5]);
    boolean compress = "Y".equals(args[6]);
    int payloadSize = Integer.parseInt(args[7]);

    log.info("DuplexPingPongClient port=" + clientPort + " ssl=" + (secure ? "Y" : "N") + " nodelay="
            + (nodelay ? "Y" : "N") + " compress=" + (compress ? "Y" : "N") + " payloadSizeBytes="
            + payloadSize);

    PeerInfo client = new PeerInfo(clientHostname, clientPort);
    PeerInfo server = new PeerInfo(serverHostname, serverPort);

    RpcServerCallExecutor executor = new ThreadPoolCallExecutor(3, 100);

    DuplexTcpClientPipelineFactory clientFactory = new DuplexTcpClientPipelineFactory();
    clientFactory.setClientInfo(client); // forces a local port nr.

    clientFactory.setConnectResponseTimeoutMillis(10000);
    clientFactory.setRpcServerCallExecutor(executor);
    clientFactory.setCompression(compress);
    if (secure) {
        RpcSSLContext sslCtx = new RpcSSLContext();
        sslCtx.setKeystorePassword("changeme");
        sslCtx.setKeystorePath("./lib/client.keystore");
        sslCtx.setTruststorePassword("changeme");
        sslCtx.setTruststorePath("./lib/truststore");
        sslCtx.init();

        clientFactory.setSslContext(sslCtx);
    }

    NullLogger logger = new NullLogger();
    clientFactory.setRpcLogger(logger);

    RpcTimeoutExecutor timeoutExecutor = new TimeoutExecutor(1, 5);
    RpcTimeoutChecker checker = new TimeoutChecker();
    checker.setTimeoutExecutor(timeoutExecutor);
    checker.startChecking(clientFactory.getRpcClientRegistry());

    CleanShutdownHandler shutdownHandler = new CleanShutdownHandler();
    shutdownHandler.addResource(executor);
    shutdownHandler.addResource(checker);
    shutdownHandler.addResource(timeoutExecutor);

    // setup a RPC event listener - it just logs what happens
    RpcConnectionEventNotifier rpcEventNotifier = new RpcConnectionEventNotifier();
    RpcConnectionEventListener listener = new RpcConnectionEventListener() {

        @Override
        public void connectionReestablished(RpcClientChannel clientChannel) {
            log.info("connectionReestablished " + clientChannel);
        }

        @Override
        public void connectionOpened(RpcClientChannel clientChannel) {
            log.info("connectionOpened " + clientChannel);
        }

        @Override
        public void connectionLost(RpcClientChannel clientChannel) {
            log.info("connectionLost " + clientChannel);
        }

        @Override
        public void connectionChanged(RpcClientChannel clientChannel) {
            log.info("connectionChanged " + clientChannel);
        }
    };
    rpcEventNotifier.setEventListener(listener);
    clientFactory.registerConnectionEventListener(rpcEventNotifier);

    // Configure the client to provide a Pong Service in both blocking an non blocking varieties
    BlockingService bPongService = BlockingPongService
            .newReflectiveBlockingService(new PingPongServiceFactory.BlockingPongServer());
    clientFactory.getRpcServiceRegistry().registerService(bPongService);

    Service nbPongService = NonBlockingPongService
            .newReflectiveService(new PingPongServiceFactory.NonBlockingPongServer());
    clientFactory.getRpcServiceRegistry().registerService(nbPongService);

    // we give the client a blocking and non blocking (pong capable) Ping Service
    BlockingService bPingService = BlockingPingService
            .newReflectiveBlockingService(new PingPongServiceFactory.BlockingPongingPingServer());
    clientFactory.getRpcServiceRegistry().registerService(bPingService);

    Service nbPingService = NonBlockingPingService
            .newReflectiveService(new PingPongServiceFactory.NonBlockingPongingPingServer());
    clientFactory.getRpcServiceRegistry().registerService(nbPingService);

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(new NioEventLoopGroup());
    bootstrap.handler(clientFactory);
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.option(ChannelOption.TCP_NODELAY, nodelay);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
    bootstrap.option(ChannelOption.SO_SNDBUF, 1048576);
    bootstrap.option(ChannelOption.SO_RCVBUF, 1048576);

    shutdownHandler.addResource(bootstrap.group());

    try {
        clientFactory.peerWith(server, bootstrap);

        while (true) {

            new ShortTests().execute(clientFactory.getRpcClientRegistry());

            new AllClientTests().execute(clientFactory.getRpcClientRegistry());

            new ClientPerformanceTests().execute(clientFactory.getRpcClientRegistry());

            Thread.sleep(60000);
        }
    } catch (Throwable e) {
        log.error("Throwable.", e);
    } finally {
        System.exit(0);
    }
}

From source file:com.googlecode.protobuf.pro.duplex.example.DuplexPingPongServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    if (args.length < 4) {
        System.err.println("usage: <serverHostname> <serverPort> <ssl=Y/N> <nodelay=Y/N>");
        System.exit(-1);/*  w  ww .  java 2s.c o  m*/
    }
    String serverHostname = args[0];
    int serverPort = Integer.parseInt(args[1]);
    boolean secure = "Y".equals(args[2]);
    boolean nodelay = "Y".equals(args[3]);
    long runDuration = 0;
    if (args.length > 4) {
        runDuration = Long.parseLong(args[4]);
    }

    log.info("DuplexPingPongServer " + serverHostname + ":" + serverPort + " ssl=" + (secure ? "Y" : "N")
            + " nodelay=" + (nodelay ? "Y" : "N"));

    PeerInfo serverInfo = new PeerInfo(serverHostname, serverPort);

    RpcServerCallExecutor executor = new ThreadPoolCallExecutor(3, 200);

    DuplexTcpServerPipelineFactory serverFactory = new DuplexTcpServerPipelineFactory(serverInfo);
    serverFactory.setRpcServerCallExecutor(executor);
    if (secure) {
        RpcSSLContext sslCtx = new RpcSSLContext();
        sslCtx.setKeystorePassword("changeme");
        sslCtx.setKeystorePath("./lib/server.keystore");
        sslCtx.setTruststorePassword("changeme");
        sslCtx.setTruststorePath("./lib/truststore");
        sslCtx.init();

        serverFactory.setSslContext(sslCtx);
    }

    NullLogger logger = new NullLogger();
    serverFactory.setLogger(logger);

    RpcTimeoutExecutor timeoutExecutor = new TimeoutExecutor(1, 5);
    RpcTimeoutChecker timeoutChecker = new TimeoutChecker();
    timeoutChecker.setTimeoutExecutor(timeoutExecutor);
    timeoutChecker.startChecking(serverFactory.getRpcClientRegistry());

    // setup a RPC event listener - it just logs what happens
    RpcConnectionEventNotifier rpcEventNotifier = new RpcConnectionEventNotifier();
    RpcConnectionEventListener listener = new RpcConnectionEventListener() {

        @Override
        public void connectionReestablished(RpcClientChannel clientChannel) {
            log.info("connectionReestablished " + clientChannel);
        }

        @Override
        public void connectionOpened(RpcClientChannel clientChannel) {
            log.info("connectionOpened " + clientChannel);
        }

        @Override
        public void connectionLost(RpcClientChannel clientChannel) {
            log.info("connectionLost " + clientChannel);
        }

        @Override
        public void connectionChanged(RpcClientChannel clientChannel) {
            log.info("connectionChanged " + clientChannel);
        }
    };
    rpcEventNotifier.setEventListener(listener);
    serverFactory.registerConnectionEventListener(rpcEventNotifier);

    // we give the server a blocking and non blocking (pong capable) Ping Service
    BlockingService bPingService = BlockingPingService
            .newReflectiveBlockingService(new PingPongServiceFactory.BlockingPongingPingServer());
    serverFactory.getRpcServiceRegistry().registerService(bPingService);

    Service nbPingService = NonBlockingPingService
            .newReflectiveService(new PingPongServiceFactory.NonBlockingPongingPingServer());
    serverFactory.getRpcServiceRegistry().registerService(nbPingService);

    // Configure the server to provide a Pong Service in both blocking an non blocking varieties
    BlockingService bPongService = BlockingPongService
            .newReflectiveBlockingService(new PingPongServiceFactory.BlockingPongServer());
    serverFactory.getRpcServiceRegistry().registerService(bPongService);

    Service nbPongService = NonBlockingPongService
            .newReflectiveService(new PingPongServiceFactory.NonBlockingPongServer());
    serverFactory.getRpcServiceRegistry().registerService(nbPongService);

    // Configure the server.
    ServerBootstrap bootstrap = new ServerBootstrap();
    NioEventLoopGroup boss = new NioEventLoopGroup(2,
            new RenamingThreadFactoryProxy("boss", Executors.defaultThreadFactory()));
    NioEventLoopGroup workers = new NioEventLoopGroup(16,
            new RenamingThreadFactoryProxy("worker", Executors.defaultThreadFactory()));
    bootstrap.group(boss, workers);
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.option(ChannelOption.SO_SNDBUF, 1048576);
    bootstrap.option(ChannelOption.SO_RCVBUF, 1048576);
    bootstrap.childOption(ChannelOption.SO_RCVBUF, 1048576);
    bootstrap.childOption(ChannelOption.SO_SNDBUF, 1048576);
    bootstrap.option(ChannelOption.TCP_NODELAY, nodelay);
    bootstrap.childHandler(serverFactory);
    bootstrap.localAddress(serverInfo.getPort());

    // Bind and start to accept incoming connections.
    CleanShutdownHandler shutdownHandler = new CleanShutdownHandler();
    shutdownHandler.addResource(boss);
    shutdownHandler.addResource(workers);
    shutdownHandler.addResource(executor);
    shutdownHandler.addResource(timeoutChecker);
    shutdownHandler.addResource(timeoutExecutor);

    bootstrap.bind();

    log.info("Serving " + serverInfo);

    if (runDuration > 0) {
        Thread.sleep(runDuration);
        System.exit(0);
    } else {
        while (true) {
            try {
                log.info("Sleeping 60s before retesting clients.");
                Thread.sleep(60000);
                new ShortTests().execute(serverFactory.getRpcClientRegistry());
            } catch (Throwable e) {
                log.warn("Throwable.", e);
            }
        }
    }
}

From source file:com.googlecode.protobuf.pro.duplex.example.nonrpc.StatusClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        System.err.println("usage: <serverHostname> <serverPort>");
        System.exit(-1);//w  ww.j a  v  a 2s.c o m
    }
    String serverHostname = args[0];
    int serverPort = Integer.parseInt(args[1]);

    PeerInfo server = new PeerInfo(serverHostname, serverPort);

    try {
        DuplexTcpClientPipelineFactory clientFactory = new DuplexTcpClientPipelineFactory();
        clientFactory.setConnectResponseTimeoutMillis(10000);
        clientFactory.setRpcServerCallExecutor(new ThreadPoolCallExecutor(3, 10));

        // RPC payloads are uncompressed when logged - so reduce logging
        CategoryPerServiceLogger logger = new CategoryPerServiceLogger();
        logger.setLogRequestProto(false);
        logger.setLogResponseProto(false);
        clientFactory.setRpcLogger(logger);

        final RpcCallback<PingPong.Status> serverStatusCallback = new RpcCallback<PingPong.Status>() {

            @Override
            public void run(PingPong.Status parameter) {
                log.info("Received " + parameter);
            }

        };

        // Set up the event pipeline factory.
        // setup a RPC event listener - it just logs what happens
        RpcConnectionEventNotifier rpcEventNotifier = new RpcConnectionEventNotifier();

        final RpcConnectionEventListener listener = new RpcConnectionEventListener() {

            @Override
            public void connectionReestablished(RpcClientChannel clientChannel) {
                log.info("connectionReestablished " + clientChannel);
                channel = clientChannel;
                channel.setOobMessageCallback(PingPong.Status.getDefaultInstance(), serverStatusCallback);
            }

            @Override
            public void connectionOpened(RpcClientChannel clientChannel) {
                log.info("connectionOpened " + clientChannel);
                channel = clientChannel;
                channel.setOobMessageCallback(PingPong.Status.getDefaultInstance(), serverStatusCallback);
            }

            @Override
            public void connectionLost(RpcClientChannel clientChannel) {
                log.info("connectionLost " + clientChannel);
            }

            @Override
            public void connectionChanged(RpcClientChannel clientChannel) {
                log.info("connectionChanged " + clientChannel);
                channel = clientChannel;
                channel.setOobMessageCallback(PingPong.Status.getDefaultInstance(), serverStatusCallback);
            }
        };
        rpcEventNotifier.addEventListener(listener);
        clientFactory.registerConnectionEventListener(rpcEventNotifier);

        Bootstrap bootstrap = new Bootstrap();
        EventLoopGroup workers = new NioEventLoopGroup(16,
                new RenamingThreadFactoryProxy("workers", Executors.defaultThreadFactory()));
        bootstrap.group(workers);
        bootstrap.handler(clientFactory);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.TCP_NODELAY, true);
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
        bootstrap.option(ChannelOption.SO_SNDBUF, 1048576);
        bootstrap.option(ChannelOption.SO_RCVBUF, 1048576);

        RpcClientConnectionWatchdog watchdog = new RpcClientConnectionWatchdog(clientFactory, bootstrap);
        rpcEventNotifier.addEventListener(watchdog);
        watchdog.start();

        CleanShutdownHandler shutdownHandler = new CleanShutdownHandler();
        shutdownHandler.addResource(workers);

        clientFactory.peerWith(server, bootstrap);

        while (true && channel != null) {

            PingPong.Status clientStatus = PingPong.Status.newBuilder()
                    .setMessage("Client " + channel + " OK@" + System.currentTimeMillis()).build();

            ChannelFuture oobSend = channel.sendOobMessage(clientStatus);
            if (!oobSend.isDone()) {
                log.info("Waiting for completion.");
                oobSend.syncUninterruptibly();
            }
            if (!oobSend.isSuccess()) {
                log.warn("OobMessage send failed.", oobSend.cause());
            }

            Thread.sleep(1000);

        }

    } finally {
        System.exit(0);
    }
}

From source file:com.googlecode.protobuf.pro.duplex.example.nonrpc.StatusServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        System.err.println("usage: <serverHostname> <serverPort>");
        System.exit(-1);/*from  www  .j av  a2 s  .c  o  m*/
    }
    String serverHostname = args[0];
    int serverPort = Integer.parseInt(args[1]);

    PeerInfo serverInfo = new PeerInfo(serverHostname, serverPort);

    // RPC payloads are uncompressed when logged - so reduce logging
    CategoryPerServiceLogger logger = new CategoryPerServiceLogger();
    logger.setLogRequestProto(false);
    logger.setLogResponseProto(false);

    // Configure the server.
    DuplexTcpServerPipelineFactory serverFactory = new DuplexTcpServerPipelineFactory(serverInfo);
    RpcServerCallExecutor rpcExecutor = new ThreadPoolCallExecutor(10, 10);
    serverFactory.setRpcServerCallExecutor(rpcExecutor);
    serverFactory.setLogger(logger);

    final RpcCallback<PingPong.Status> clientStatusCallback = new RpcCallback<PingPong.Status>() {

        @Override
        public void run(PingPong.Status parameter) {
            log.info("Received " + parameter);
        }

    };
    // setup a RPC event listener - it just logs what happens
    RpcConnectionEventNotifier rpcEventNotifier = new RpcConnectionEventNotifier();
    RpcConnectionEventListener listener = new RpcConnectionEventListener() {

        @Override
        public void connectionReestablished(RpcClientChannel clientChannel) {
            log.info("connectionReestablished " + clientChannel);

            clientChannel.setOobMessageCallback(Status.getDefaultInstance(), clientStatusCallback);
        }

        @Override
        public void connectionOpened(RpcClientChannel clientChannel) {
            log.info("connectionOpened " + clientChannel);

            clientChannel.setOobMessageCallback(Status.getDefaultInstance(), clientStatusCallback);
        }

        @Override
        public void connectionLost(RpcClientChannel clientChannel) {
            log.info("connectionLost " + clientChannel);
        }

        @Override
        public void connectionChanged(RpcClientChannel clientChannel) {
            log.info("connectionChanged " + clientChannel);
            clientChannel.setOobMessageCallback(Status.getDefaultInstance(), clientStatusCallback);
        }
    };
    rpcEventNotifier.setEventListener(listener);
    serverFactory.registerConnectionEventListener(rpcEventNotifier);

    ServerBootstrap bootstrap = new ServerBootstrap();
    EventLoopGroup boss = new NioEventLoopGroup(2,
            new RenamingThreadFactoryProxy("boss", Executors.defaultThreadFactory()));
    EventLoopGroup workers = new NioEventLoopGroup(16,
            new RenamingThreadFactoryProxy("worker", Executors.defaultThreadFactory()));
    bootstrap.group(boss, workers);
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.option(ChannelOption.SO_SNDBUF, 1048576);
    bootstrap.option(ChannelOption.SO_RCVBUF, 1048576);
    bootstrap.childOption(ChannelOption.SO_RCVBUF, 1048576);
    bootstrap.childOption(ChannelOption.SO_SNDBUF, 1048576);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.childHandler(serverFactory);
    bootstrap.localAddress(serverInfo.getPort());

    CleanShutdownHandler shutdownHandler = new CleanShutdownHandler();
    shutdownHandler.addResource(boss);
    shutdownHandler.addResource(workers);
    shutdownHandler.addResource(rpcExecutor);

    // Bind and start to accept incoming connections.
    bootstrap.bind();
    log.info("Serving " + bootstrap);

    while (true) {

        List<RpcClientChannel> clients = serverFactory.getRpcClientRegistry().getAllClients();
        for (RpcClientChannel client : clients) {

            PingPong.Status serverStatus = PingPong.Status.newBuilder()
                    .setMessage("Server " + serverFactory.getServerInfo() + " OK@" + System.currentTimeMillis())
                    .build();

            ChannelFuture oobSend = client.sendOobMessage(serverStatus);
            if (!oobSend.isDone()) {
                log.info("Waiting for completion.");
                oobSend.syncUninterruptibly();
            }
            if (!oobSend.isSuccess()) {
                log.warn("OobMessage send failed.", oobSend.cause());
            }

        }
        log.info("Sleeping 5s before sending serverStatus to all clients.");

        Thread.sleep(5000);
    }
}