Example usage for io.netty.channel.nio NioEventLoopGroup NioEventLoopGroup

List of usage examples for io.netty.channel.nio NioEventLoopGroup NioEventLoopGroup

Introduction

In this page you can find the example usage for io.netty.channel.nio NioEventLoopGroup NioEventLoopGroup.

Prototype

public NioEventLoopGroup(int nThreads, Executor executor) 

Source Link

Usage

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);/*from  w ww.ja v  a2s. 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);//from ww  w.  j a v  a 2s.c om
    }
    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 w ww .  ja  v  a  2 s .  c om*/
    }
    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);
    }
}

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

License:Apache License

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

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

    try {
        DuplexTcpClientPipelineFactory clientFactory = new DuplexTcpClientPipelineFactory();
        // force the use of a local port
        // - normally you don't need this
        clientFactory.setClientInfo(client);

        ExtensionRegistry r = ExtensionRegistry.newInstance();
        PingPong.registerAllExtensions(r);
        clientFactory.setExtensionRegistry(r);

        clientFactory.setConnectResponseTimeoutMillis(10000);
        RpcServerCallExecutor rpcExecutor = new ThreadPoolCallExecutor(3, 10);
        clientFactory.setRpcServerCallExecutor(rpcExecutor);

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

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

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

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

            @Override
            public void connectionChanged(RpcClientChannel clientChannel) {
                log.info("connectionChanged " + clientChannel);
                channel = clientChannel;
            }
        };
        rpcEventNotifier.addEventListener(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();
        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);
        shutdownHandler.addResource(rpcExecutor);

        clientFactory.peerWith(server, bootstrap);

        while (true && channel != null) {

            callServerNPEinNonBlockingPingnoPong();
            callServerNPEinBlockingPingnoPong();
            callBlockingPingWithBlockingPongNPE();
            callBlockingPingWithNonBlockingPongNPE();
            Thread.sleep(10000);

        }

    } catch (Exception e) {
        log.warn("Failure.", e);
    } finally {
        System.exit(0);
    }
}

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

License:Apache License

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

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

    try {
        DuplexTcpClientPipelineFactory clientFactory = new DuplexTcpClientPipelineFactory();
        // force the use of a local port
        // - normally you don't need this
        clientFactory.setClientInfo(client);

        ExtensionRegistry r = ExtensionRegistry.newInstance();
        PingPong.registerAllExtensions(r);
        clientFactory.setExtensionRegistry(r);

        clientFactory.setConnectResponseTimeoutMillis(10000);
        RpcServerCallExecutor rpcExecutor = new ThreadPoolCallExecutor(3, 10);
        clientFactory.setRpcServerCallExecutor(rpcExecutor);

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

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

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

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

            @Override
            public void connectionChanged(RpcClientChannel clientChannel) {
                log.info("connectionChanged " + clientChannel);
                channel = clientChannel;
            }
        };
        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);
        shutdownHandler.addResource(rpcExecutor);

        clientFactory.peerWith(server, bootstrap);

        while (true && channel != null) {

            BlockingPingService.BlockingInterface blockingService = BlockingPingService
                    .newBlockingStub(channel);
            final ClientRpcController controller = channel.newRpcController();
            controller.setTimeoutMs(0);

            Ping.Builder pingBuilder = Ping.newBuilder();
            pingBuilder.setSequenceNo(1);
            pingBuilder.setPingDurationMs(1000);
            pingBuilder.setPingPayload(ByteString.copyFromUtf8("Hello World!"));
            pingBuilder.setPingPercentComplete(false);
            pingBuilder.setPongRequired(false);
            pingBuilder.setPongBlocking(true);
            pingBuilder.setPongDurationMs(1000);
            pingBuilder.setPongTimeoutMs(0);
            pingBuilder.setPongPercentComplete(false);

            // set an extension value
            pingBuilder.setExtension(ExtendedPing.extendedIntField, 111);

            Ping ping = pingBuilder.build();
            try {
                Pong pong = blockingService.ping(controller, ping);

                Integer ext = pong.getExtension(ExtendedPong.extendedIntField);
                if (ext == null || ext != 111) {
                    log.warn("Extension not parsed. Value=", ext);
                }
            } catch (ServiceException e) {
                log.warn("Call failed.", e);
            }

            Thread.sleep(10000);

        }

    } catch (Exception e) {
        log.warn("Failure.", e);
    } finally {
        System.exit(0);
    }
}

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

License:Apache License

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

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

    try {
        DuplexTcpClientPipelineFactory clientFactory = new DuplexTcpClientPipelineFactory();
        // force the use of a local port
        // - normally you don't need this
        //clientFactory.setClientInfo(client);

        ExtensionRegistry r = ExtensionRegistry.newInstance();
        PingPong.registerAllExtensions(r);
        clientFactory.setExtensionRegistry(r);

        clientFactory.setConnectResponseTimeoutMillis(10000);
        RpcServerCallExecutor rpcExecutor = new ThreadPoolCallExecutor(3, 10);
        clientFactory.setRpcServerCallExecutor(rpcExecutor);

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

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

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

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

            @Override
            public void connectionChanged(RpcClientChannel clientChannel) {
                log.info("connectionChanged " + clientChannel);
                channel = clientChannel;
            }
        };
        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);
        watchdog.setThreadName("watchdog"); // #48
        rpcEventNotifier.addEventListener(watchdog);
        watchdog.start();

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

        clientFactory.peerWith(server, bootstrap);

        while (true && channel != null) {

            BlockingPingService.BlockingInterface blockingService = BlockingPingService
                    .newBlockingStub(channel);
            final ClientRpcController controller = channel.newRpcController();
            controller.setTimeoutMs(0);

            Ping.Builder pingBuilder = Ping.newBuilder();
            pingBuilder.setSequenceNo(1);
            pingBuilder.setPingDurationMs(1000);
            pingBuilder.setPingPayload(ByteString.copyFromUtf8("Hello World!"));
            pingBuilder.setPingPercentComplete(false);
            pingBuilder.setPongRequired(false);
            pingBuilder.setPongBlocking(true);
            pingBuilder.setPongDurationMs(1000);
            pingBuilder.setPongTimeoutMs(0);
            pingBuilder.setPongPercentComplete(false);

            // set an extension value
            pingBuilder.setExtension(ExtendedPing.extendedIntField, 111);

            Ping ping = pingBuilder.build();
            try {
                Pong pong = blockingService.ping(controller, ping);

                Integer ext = pong.getExtension(ExtendedPong.extendedIntField);
                if (ext == null || ext != 111) {
                    log.warn("Extension not parsed. Value=", ext);
                }

                channel.close();
            } catch (ServiceException e) {
                log.warn("Call failed.", e);
            }

            Thread.sleep(10000);

        }

    } catch (Exception e) {
        log.warn("Failure.", e);
    } finally {
        System.exit(0);
    }
}

From source file:com.googlecode.protobuf.pro.duplex.example.simple.SimpleServer.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   ww  w . j  a  v a 2s  .co  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);

    ExtensionRegistry r = ExtensionRegistry.newInstance();
    PingPong.registerAllExtensions(r);
    serverFactory.setExtensionRegistry(r);

    RpcServerCallExecutor rpcExecutor = new ThreadPoolCallExecutor(10, 10);
    serverFactory.setRpcServerCallExecutor(rpcExecutor);
    serverFactory.setLogger(logger);

    // 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(true, bPingService);

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

    ServerBootstrap bootstrap = new ServerBootstrap();
    EventLoopGroup boss = new NioEventLoopGroup(2,
            new RenamingThreadFactoryProxy("boss", Executors.defaultThreadFactory()));
    EventLoopGroup workers = new NioEventLoopGroup(2,
            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();
        log.info("Number of clients=" + clients.size());

        Thread.sleep(5000);
    }
}

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

License:Apache License

public static void main(String[] args) throws Exception {
    if (args.length != 4) {
        System.err.println("usage: <serverHostname> <serverPort> <clientHostname> <clientPort>");
        System.exit(-1);/*from   w w w  . j a  va 2  s .  c  om*/
    }
    String serverHostname = args[0];
    int serverPort = Integer.parseInt(args[1]);
    String clientHostname = args[2];
    int clientPort = Integer.parseInt(args[3]);

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

    try {
        DuplexTcpClientPipelineFactory clientFactory = new DuplexTcpClientPipelineFactory();
        // force the use of a local port
        // - normally you don't need this
        clientFactory.setClientInfo(client);

        ExtensionRegistry r = ExtensionRegistry.newInstance();
        PingPong.registerAllExtensions(r);
        clientFactory.setExtensionRegistry(r);

        clientFactory.setConnectResponseTimeoutMillis(10000);
        RpcServerCallExecutor rpcExecutor = new ThreadPoolCallExecutor(3, 10);
        clientFactory.setRpcServerCallExecutor(rpcExecutor);

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

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

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

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

            @Override
            public void connectionChanged(RpcClientChannel clientChannel) {
                log.info("connectionChanged " + clientChannel);
                channel = clientChannel;
            }
        };
        rpcEventNotifier.addEventListener(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();
        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);
        shutdownHandler.addResource(rpcExecutor);

        clientFactory.peerWith(server, bootstrap);

        while (true && channel != null) {

            callNonBlockingServerPingWithBlockingClientTimeoutBeforeFinish();

            Thread.sleep(10000);

        }

    } catch (Exception e) {
        log.warn("Failure.", e);
    } finally {
        System.exit(0);
    }
}

From source file:com.hazelcast.openshift.AbstractTunnel.java

License:Open Source License

protected AbstractTunnel(int localPort) {
    this.localPort = localPort;

    this.bossGroup = new NioEventLoopGroup(5, new DefaultThreadFactory("server-channel-"));
    this.workerGroup = new NioEventLoopGroup(5, new DefaultThreadFactory("client-channel-"));
}

From source file:com.heliosapm.shorthand.caster.broadcast.BroadcastListener.java

License:Open Source License

private BroadcastListener() {
    group = new NioEventLoopGroup(0, this);
    bootstrap = new Bootstrap();
    taskThreadPool = Executors.newFixedThreadPool(
            ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors(), new ThreadFactory() {
                final AtomicInteger serial = new AtomicInteger();

                @Override//from   w w w  .j  a  v  a2 s  .com
                public Thread newThread(Runnable r) {
                    Thread t = new Thread(r, "TaskExecutionThread#" + serial.incrementAndGet());
                    t.setDaemon(true);
                    return t;
                }
            });
    router = new BroadcastListenerRouter(taskThreadPool);
    boundChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    NetworkInterface nic = null;
    try {
        nic = NetworkInterface.getByName(ConfigurationHelper.getSystemThenEnvProperty(
                ShorthandProperties.AGENT_BROADCAST_NIC_PROP, ShorthandProperties.DEFAULT_AGENT_BROADCAST_NIC));
    } catch (Exception ex) {
        try {
            nic = NetworkInterface.getByIndex(0);
        } catch (SocketException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    String[] addresses = ConfigurationHelper.getSystemThenEnvPropertyArray(AGENT_BROADCAST_NETWORK_PROP,
            DEFAULT_AGENT_BROADCAST_NETWORK);
    int[] ports = ConfigurationHelper.getIntSystemThenEnvPropertyArray(AGENT_BROADCAST_PORT_PROP,
            "" + DEFAULT_AGENT_BROADCAST_PORT);
    if (addresses.length != ports.length) {
        throw new RuntimeException(
                "Invalid broadcast configuration. Number of addresses != Number of ports. Addresses:"
                        + Arrays.toString(addresses) + " Ports:" + Arrays.toString(ports));
    }
    for (int i = 0; i < addresses.length; i++) {
        try {
            startListener(new InetSocketAddress(addresses[i], ports[i]), nic);
        } catch (Exception ex) {
            loge("Failed to start listener on [%s:%s]", ex, addresses[i], ports[i]);
        }
    }

}