List of usage examples for io.netty.channel ChannelFuture isSuccess
boolean isSuccess();
From source file:com.github.sparkfy.network.client.TransportClient.java
License:Apache License
/** * Requests a single chunk from the remote side, from the pre-negotiated streamId. * <p/>//from www.j av a2 s. c om * Chunk indices go from 0 onwards. It is valid to request the same chunk multiple times, though * some streams may not support this. * <p/> * Multiple fetchChunk requests may be outstanding simultaneously, and the chunks are guaranteed * to be returned in the same order that they were requested, assuming only a single * TransportClient is used to fetch the chunks. * * @param streamId Identifier that refers to a stream in the remote StreamManager. This should * be agreed upon by client and server beforehand. * @param chunkIndex 0-based index of the chunk to fetch * @param callback Callback invoked upon successful receipt of chunk, or upon any failure. */ public void fetchChunk(long streamId, final int chunkIndex, final ChunkReceivedCallback callback) { final String serverAddr = NettyUtils.getRemoteAddress(channel); final long startTime = System.currentTimeMillis(); logger.debug("Sending fetch chunk request {} to {}", chunkIndex, serverAddr); final StreamChunkId streamChunkId = new StreamChunkId(streamId, chunkIndex); handler.addFetchRequest(streamChunkId, callback); channel.writeAndFlush(new ChunkFetchRequest(streamChunkId)).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { long timeTaken = System.currentTimeMillis() - startTime; logger.trace("Sending request {} to {} took {} ms", streamChunkId, serverAddr, timeTaken); } else { String errorMsg = String.format("Failed to send request %s to %s: %s", streamChunkId, serverAddr, future.cause()); logger.error(errorMsg, future.cause()); handler.removeFetchRequest(streamChunkId); channel.close(); try { callback.onFailure(chunkIndex, new IOException(errorMsg, future.cause())); } catch (Exception e) { logger.error("Uncaught exception in RPC response callback handler!", e); } } } }); }
From source file:com.github.sparkfy.network.client.TransportClient.java
License:Apache License
/** * Request to stream the data with the given stream ID from the remote end. * * @param streamId The stream to fetch.//from w ww . java 2 s . com * @param callback Object to call with the stream data. */ public void stream(final String streamId, final StreamCallback callback) { final String serverAddr = NettyUtils.getRemoteAddress(channel); final long startTime = System.currentTimeMillis(); logger.debug("Sending stream request for {} to {}", streamId, serverAddr); // Need to synchronize here so that the callback is added to the queue and the RPC is // written to the socket atomically, so that callbacks are called in the right order // when responses arrive. synchronized (this) { handler.addStreamCallback(callback); channel.writeAndFlush(new StreamRequest(streamId)).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { long timeTaken = System.currentTimeMillis() - startTime; logger.trace("Sending request for {} to {} took {} ms", streamId, serverAddr, timeTaken); } else { String errorMsg = String.format("Failed to send request for %s to %s: %s", streamId, serverAddr, future.cause()); logger.error(errorMsg, future.cause()); channel.close(); try { callback.onFailure(streamId, new IOException(errorMsg, future.cause())); } catch (Exception e) { logger.error("Uncaught exception in RPC response callback handler!", e); } } } }); } }
From source file:com.github.sparkfy.network.client.TransportClient.java
License:Apache License
/** * Sends an opaque message to the RpcHandler on the server-side. The callback will be invoked * with the server's response or upon any failure. * * @param message The message to send./*from w ww. j a v a2 s . co m*/ * @return The RPC's id. */ public ByteBuffer sendRpcSyncSafely(ByteBuffer message, long timeoutMs) { final String serverAddr = NettyUtils.getRemoteAddress(channel); final long startTime = System.currentTimeMillis(); logger.trace("Sending RPC to {}", serverAddr); final long requestId = Math.abs(UUID.randomUUID().getLeastSignificantBits()); final SettableFuture<ByteBuffer> result = SettableFuture.create(); final RpcResponseCallback callback = new RpcResponseCallback() { @Override public void onSuccess(ByteBuffer response) { result.set(response); } @Override public void onFailure(Throwable e) { result.setException(e); } }; handler.addRpcRequest(requestId, callback); try { synchronized (this) { channel.writeAndFlush(new RpcRequest(requestId, new NioManagedBuffer(message))) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { long timeTaken = System.currentTimeMillis() - startTime; logger.trace("Sending request {} to {} took {} ms", requestId, serverAddr, timeTaken); } else { String errorMsg = String.format("Failed to send RPC %s to %s: %s", requestId, serverAddr, future.cause()); logger.error(errorMsg, future.cause()); handler.removeRpcRequest(requestId); channel.close(); try { callback.onFailure(new IOException(errorMsg, future.cause())); } catch (Exception e) { logger.error("Uncaught exception in RPC response callback handler!", e); } } } }).get(timeoutMs, TimeUnit.MILLISECONDS); } return result.get(timeoutMs - (System.currentTimeMillis() - startTime), TimeUnit.MILLISECONDS); } catch (ExecutionException e) { channel.close(); throw Throwables.propagate(e.getCause()); } catch (Exception e) { channel.close(); throw Throwables.propagate(e); } }
From source file:com.github.sparkfy.network.client.TransportClient.java
License:Apache License
/** * Sends an opaque message to the RpcHandler on the server-side. The callback will be invoked * with the server's response or upon any failure. * * @param message The message to send.// ww w . ja va 2 s.c o m * @param callback Callback to handle the RPC's reply. * @return The RPC's id. */ public long sendRpc(ByteBuffer message, final RpcResponseCallback callback) { final String serverAddr = NettyUtils.getRemoteAddress(channel); final long startTime = System.currentTimeMillis(); logger.trace("Sending RPC to {}", serverAddr); final long requestId = Math.abs(UUID.randomUUID().getLeastSignificantBits()); handler.addRpcRequest(requestId, callback); channel.writeAndFlush(new RpcRequest(requestId, new NioManagedBuffer(message))) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { long timeTaken = System.currentTimeMillis() - startTime; logger.trace("Sending request {} to {} took {} ms", requestId, serverAddr, timeTaken); } else { String errorMsg = String.format("Failed to send RPC %s to %s: %s", requestId, serverAddr, future.cause()); logger.error(errorMsg, future.cause()); handler.removeRpcRequest(requestId); channel.close(); try { callback.onFailure(new IOException(errorMsg, future.cause())); } catch (Exception e) { logger.error("Uncaught exception in RPC response callback handler!", e); } } } }); return requestId; }
From source file:com.github.sparkfy.network.server.TransportRequestHandler.java
License:Apache License
/** * Responds to a single message with some Encodable object. If a failure occurs while sending, * it will be logged and the channel closed. *//* w w w .j a va 2s .c o m*/ private void respond(final Encodable result) { final String remoteAddress = channel.remoteAddress().toString(); channel.writeAndFlush(result).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { logger.trace(String.format("Sent result %s to client %s", result, remoteAddress)); } else { logger.error(String.format("Error sending result %s to %s; closing connection", result, remoteAddress), future.cause()); channel.close(); } } }); }
From source file:com.googlecode.protobuf.pro.duplex.client.DuplexTcpClientPipelineFactory.java
License:Apache License
/** * Creates a new client with the provided channel attributes to the remoteAddress. * @param remoteAddress// ww w .j ava2 s.co m * @param bootstrap * @param attributes * @return * @throws IOException */ public RpcClient peerWith(InetSocketAddress remoteAddress, Bootstrap bootstrap, Map<String, Object> attributes) throws IOException { if (remoteAddress == null) { throw new NullPointerException("remotedAddress"); } InetSocketAddress localAddress = null; if (clientInfo.getHostName() != null) { localAddress = new InetSocketAddress(clientInfo.getHostName(), clientInfo.getPort()); } ChannelFuture connectFuture = bootstrap.connect(remoteAddress, localAddress).awaitUninterruptibly(); if (!connectFuture.isSuccess()) { throw new IOException("Failed to connect to " + remoteAddress, connectFuture.cause()); } Channel channel = connectFuture.channel(); InetSocketAddress connectedAddress = (InetSocketAddress) channel.localAddress(); PeerInfo effectiveClientInfo = new PeerInfo( clientInfo.getHostName() == null ? connectedAddress.getHostName() : clientInfo.getHostName(), connectedAddress.getPort(), clientInfo.getPid()); ConnectRequest connectRequest = ConnectRequest.newBuilder() .setClientHostName(effectiveClientInfo.getHostName()).setClientPort(effectiveClientInfo.getPort()) .setClientPID(effectiveClientInfo.getPid()).setCorrelationId(correlationId.incrementAndGet()) .setCompress(isCompression()).build(); WirePayload payload = WirePayload.newBuilder().setConnectRequest(connectRequest).build(); if (log.isDebugEnabled()) { log.debug("Sending [" + connectRequest.getCorrelationId() + "]ConnectRequest."); } channel.writeAndFlush(payload); ClientConnectResponseHandler connectResponseHandler = (ClientConnectResponseHandler) channel.pipeline() .get(Handler.CLIENT_CONNECT); if (connectResponseHandler == null) { throw new IllegalStateException("No connectReponse handler in channel pipeline."); } ConnectResponse connectResponse = connectResponseHandler.getConnectResponse(connectResponseTimeoutMillis); if (connectResponse == null) { connectFuture.channel().close().awaitUninterruptibly(); throw new IOException( "No Channel response received before " + connectResponseTimeoutMillis + " millis timeout."); } if (connectResponse.hasErrorCode()) { connectFuture.channel().close().awaitUninterruptibly(); throw new IOException( "DuplexTcpServer CONNECT_RESPONSE indicated error " + connectResponse.getErrorCode()); } if (!connectResponse.hasCorrelationId()) { connectFuture.channel().close().awaitUninterruptibly(); throw new IOException("DuplexTcpServer CONNECT_RESPONSE missing correlationId."); } if (connectResponse.getCorrelationId() != connectRequest.getCorrelationId()) { connectFuture.channel().close().awaitUninterruptibly(); throw new IOException("DuplexTcpServer CONNECT_RESPONSE correlationId mismatch. TcpClient sent " + connectRequest.getCorrelationId() + " received " + connectResponse.getCorrelationId() + " from TcpServer."); } PeerInfo serverInfo = null; if (connectResponse.hasServerPID()) { serverInfo = new PeerInfo(remoteAddress.getHostName(), remoteAddress.getPort(), connectResponse.getServerPID()); } else { serverInfo = new PeerInfo(remoteAddress.getHostName(), remoteAddress.getPort()); } RpcClient rpcClient = new RpcClient(channel, effectiveClientInfo, serverInfo, connectResponse.getCompress(), getRpcLogger(), getExtensionRegistry()); if (attributes != null) { // transfer the input attributes to the channel before we state it's opened. for (Entry<String, Object> attr : attributes.entrySet()) { rpcClient.setAttribute(attr.getKey(), attr.getValue()); } } RpcClientHandler rpcClientHandler = completePipeline(rpcClient); rpcClientHandler.notifyOpened(); // register the rpcClient in the RpcClientRegistry if (!getRpcClientRegistry().registerRpcClient(rpcClient)) { log.warn("Client RpcClient already registered. Bug??"); } // channels remove themselves when closed. return rpcClient; }
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 w w w . ja v a 2 s . 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 w ww. ja v a 2s .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); } }
From source file:com.graylog.splunk.output.senders.TCPSender.java
License:Open Source License
protected void createBootstrap(final EventLoopGroup workerGroup) { final Bootstrap bootstrap = new Bootstrap(); final SplunkSenderThread senderThread = new SplunkSenderThread(queue); bootstrap.group(workerGroup).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000) .remoteAddress(new InetSocketAddress(hostname, port)) .handler(new ChannelInitializer<SocketChannel>() { @Override//from w w w .j a va2 s .co m protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new StringEncoder()); ch.pipeline().addLast(new SimpleChannelInboundHandler<ByteBuf>() { @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception { // we only send data, never read on the socket } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { senderThread.start(ctx.channel()); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { LOG.info("Channel disconnected."); senderThread.stop(); scheduleReconnect(ctx.channel().eventLoop()); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { LOG.error("Exception caught", cause); } }); } }); bootstrap.connect().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { LOG.info("Connected."); } else { LOG.error("Connection failed: {}", future.cause().getMessage()); scheduleReconnect(future.channel().eventLoop()); } } }); }
From source file:com.gxkj.demo.netty.proxy.HexDumpProxyBackendHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception { inboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() { @Override/* w ww.j av a2 s .co m*/ public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { ctx.channel().read(); } else { future.channel().close(); } } }); }