List of usage examples for io.netty.channel ChannelOption CONNECT_TIMEOUT_MILLIS
ChannelOption CONNECT_TIMEOUT_MILLIS
To view the source code for io.netty.channel ChannelOption CONNECT_TIMEOUT_MILLIS.
Click Source Link
From source file:com.gemstone.gemfire.redis.GemFireRedisServer.java
License:Apache License
/** * Helper method to start the server listening for connections. The * server is bound to the port specified by {@link GemFireRedisServer#serverPort} * /*from ww w . jav a2 s . co m*/ * @throws IOException * @throws InterruptedException */ private void startRedisServer() throws IOException, InterruptedException { ThreadFactory selectorThreadFactory = new ThreadFactory() { private final AtomicInteger counter = new AtomicInteger(); @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("GemFireRedisServer-SelectorThread-" + counter.incrementAndGet()); t.setDaemon(true); return t; } }; ThreadFactory workerThreadFactory = new ThreadFactory() { private final AtomicInteger counter = new AtomicInteger(); @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("GemFireRedisServer-WorkerThread-" + counter.incrementAndGet()); return t; } }; bossGroup = null; workerGroup = null; Class<? extends ServerChannel> socketClass = null; if (singleThreadPerConnection) { bossGroup = new OioEventLoopGroup(Integer.MAX_VALUE, selectorThreadFactory); workerGroup = new OioEventLoopGroup(Integer.MAX_VALUE, workerThreadFactory); socketClass = OioServerSocketChannel.class; } else { bossGroup = new NioEventLoopGroup(this.numSelectorThreads, selectorThreadFactory); workerGroup = new NioEventLoopGroup(this.numWorkerThreads, workerThreadFactory); socketClass = NioServerSocketChannel.class; } InternalDistributedSystem system = (InternalDistributedSystem) cache.getDistributedSystem(); String pwd = system.getConfig().getRedisPassword(); final byte[] pwdB = Coder.stringToBytes(pwd); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(socketClass).childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { if (logger.fineEnabled()) logger.fine("GemFireRedisServer-Connection established with " + ch.remoteAddress()); ChannelPipeline p = ch.pipeline(); p.addLast(ByteToCommandDecoder.class.getSimpleName(), new ByteToCommandDecoder()); p.addLast(ExecutionHandlerContext.class.getSimpleName(), new ExecutionHandlerContext(ch, cache, regionCache, GemFireRedisServer.this, pwdB)); } }).option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_RCVBUF, getBufferSize()) .childOption(ChannelOption.SO_KEEPALIVE, true) .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, GemFireRedisServer.connectTimeoutMillis) .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); // Bind and start to accept incoming connections. ChannelFuture f = b.bind(new InetSocketAddress(getBindAddress(), serverPort)).sync(); if (this.logger.infoEnabled()) { String logMessage = "GemFireRedisServer started {" + getBindAddress() + ":" + serverPort + "}, Selector threads: " + this.numSelectorThreads; if (this.singleThreadPerConnection) logMessage += ", One worker thread per connection"; else logMessage += ", Worker threads: " + this.numWorkerThreads; this.logger.info(logMessage); } this.serverChannel = f.channel(); }
From source file:com.github.netfreer.shadowducks.client.handler.SocksServerConnectHandler.java
License:Apache License
@Override public void channelRead0(final ChannelHandlerContext ctx, final SocksMessage message) throws Exception { if (message instanceof Socks4CommandRequest) { final Socks4CommandRequest request = (Socks4CommandRequest) message; Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new FutureListener<Channel>() { @Override//from ww w . j a v a 2 s . com public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ChannelFuture responseFuture = ctx.channel() .writeAndFlush(new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS)); responseFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) { ctx.pipeline().remove(SocksServerConnectHandler.this); outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel())); ctx.pipeline().addLast(new RelayHandler(outboundChannel)); } }); } else { ctx.channel().writeAndFlush( new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED)); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); final Channel inboundChannel = ctx.channel(); b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new DirectClientHandler(promise)); b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Connection established use handler provided results } else { // Close the connection if the connection attempt has failed. ctx.channel().writeAndFlush( new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED)); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); } else if (message instanceof Socks5CommandRequest) { final Socks5CommandRequest request = (Socks5CommandRequest) message; Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new FutureListener<Channel>() { @Override public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ChannelFuture responseFuture = ctx.channel() .writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.SUCCESS, request.dstAddrType(), request.dstAddr(), request.dstPort())); responseFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) { ctx.pipeline().remove(SocksServerConnectHandler.this); outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel())); ctx.pipeline().addLast(new RelayHandler(outboundChannel)); } }); } else { ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE, request.dstAddrType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); final Channel inboundChannel = ctx.channel(); b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new DirectClientHandler(promise)); b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { Attribute<Long> beginTimeAttr = ctx.channel().attr(AttrKeys.CHANNEL_BEGIN_TIME); final long parseTime = beginTimeAttr.get(); long usedTime = System.currentTimeMillis() - parseTime; if (future.isSuccess()) { // Connection established use handler provided results logger.info("connect {}:{} success, use time {} millis.", request.dstAddr(), request.dstPort(), usedTime); } else { // Close the connection if the connection attempt has failed. ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE, request.dstAddrType())); SocksServerUtils.closeOnFlush(ctx.channel()); logger.info("connect {}:{} failure, use time {} millis.", request.dstAddr(), request.dstPort(), usedTime); } beginTimeAttr.set(null); } }); } else { ctx.close(); } }
From source file:com.github.sinsinpub.pero.backend.ConnectBackendHandler.java
License:Apache License
/** * Create new connection context to connect real back-end (may be another proxy). * /*ww w. jav a2 s . co m*/ * @param inboundChannel * @param outboundPromise * @param upstreamProxyHandler * @return Bootstrap */ protected Bootstrap newConnectionBootstrap(final Channel inboundChannel, final Promise<Channel> outboundPromise, final ProxyHandler upstreamProxyHandler) { final Bootstrap b = new Bootstrap(); b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getConnectTimeoutMillis()) .option(ChannelOption.SO_KEEPALIVE, true) .handler(new ProxyChannelInitializer(outboundPromise, upstreamProxyHandler)); return b; }
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 ww. j a v a 2 s.c o m 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.google.devtools.build.lib.remote.blobstore.http.HttpBlobStore.java
License:Open Source License
public HttpBlobStore(URI uri, int timeoutMillis, @Nullable final Credentials creds) throws Exception { boolean useTls = uri.getScheme().equals("https"); if (uri.getPort() == -1) { int port = useTls ? 443 : 80; uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), port, uri.getPath(), uri.getQuery(), uri.getFragment());//www.j a v a2 s. co m } this.uri = uri; final SslContext sslCtx; if (useTls) { // OpenSsl gives us a > 2x speed improvement on fast networks, but requires netty tcnative // to be there which is not available on all platforms and environments. SslProvider sslProvider = OpenSsl.isAvailable() ? SslProvider.OPENSSL : SslProvider.JDK; sslCtx = SslContextBuilder.forClient().sslProvider(sslProvider).build(); } else { sslCtx = null; } Bootstrap clientBootstrap = new Bootstrap().channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeoutMillis).group(eventLoop) .remoteAddress(uri.getHost(), uri.getPort()); downloadChannels = new SimpleChannelPool(clientBootstrap, new ChannelPoolHandler() { @Override public void channelReleased(Channel ch) { ch.pipeline().remove("read-timeout-handler"); } @Override public void channelAcquired(Channel ch) { ch.pipeline().addFirst("read-timeout-handler", new ReadTimeoutHandler(timeoutMillis)); } @Override public void channelCreated(Channel ch) { ChannelPipeline p = ch.pipeline(); p.addFirst("read-timeout-handler", new ReadTimeoutHandler(timeoutMillis)); if (sslCtx != null) { SSLEngine engine = sslCtx.newEngine(ch.alloc()); engine.setUseClientMode(true); p.addFirst(new SslHandler(engine)); } p.addLast(new HttpClientCodec()); p.addLast(new HttpDownloadHandler(creds)); } }); uploadChannels = new SimpleChannelPool(clientBootstrap, new ChannelPoolHandler() { @Override public void channelReleased(Channel ch) { } @Override public void channelAcquired(Channel ch) { } @Override public void channelCreated(Channel ch) { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { SSLEngine engine = sslCtx.newEngine(ch.alloc()); engine.setUseClientMode(true); p.addFirst(new SslHandler(engine)); } p.addLast(new HttpResponseDecoder()); // The 10KiB limit was chosen at random. We only expect HTTP servers to respond with // an error message in the body and that should always be less than 10KiB. p.addLast(new HttpObjectAggregator(10 * 1024)); p.addLast(new HttpRequestEncoder()); p.addLast(new ChunkedWriteHandler()); p.addLast(new HttpUploadHandler(creds)); } }); this.creds = creds; }
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 w w . jav a2 s .co m*/ "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.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 a2s . 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.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);// w ww . jav a 2 s . co 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); // 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);/*from ww w .j a v a 2s .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); 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);/* ww w.j ava2 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); 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); } }