List of usage examples for io.netty.channel ChannelFutureListener ChannelFutureListener
ChannelFutureListener
From source file:com.github.sinsinpub.pero.backend.ConnectBackendHandler.java
License:Apache License
@Override public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception { final Channel inboundChannel = ctx.channel(); final Promise<Channel> outboundPromise = newOutboundPromise(ctx, request); final int maxProxies = AppProps.PROPS.getInteger("upstream.socks5.count", 1); final AtomicBoolean isFinalSuccess = new AtomicBoolean(false); final AtomicBoolean isRetryOccured = new AtomicBoolean(false); for (int i = 1; i <= maxProxies; i++) { final boolean isFirstOne = (i == 1); final boolean isFinalOne = (i == maxProxies); if (!isFirstOne) { isRetryOccured.set(true);/* w w w . ja v a 2 s . c om*/ } try { final ProxyHandler upstreamProxyHandler = newUpstreamProxyHandler(i); final Bootstrap b = newConnectionBootstrap(inboundChannel, outboundPromise, upstreamProxyHandler); logger.info(String.format("Connecting backend %s:%s via %s", request.host(), request.port(), upstreamProxyHandler != null ? upstreamProxyHandler.proxyAddress() : "direct")); ChannelFuture connFuture = b.connect(request.host(), request.port()); connFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Connection established use handler provided results if (upstreamProxyHandler == null) { logger.info("Backend connected directly"); } else { logger.info("Backend connected via: " + upstreamProxyHandler.proxyAddress()); } } else { // Close the connection if the connection attempt has failed. if (isFinalOne) { logger.error("Backend connection failed: " + future.cause(), future.cause()); ctx.channel().writeAndFlush( new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); NettyChannelUtils.closeOnFlush(ctx.channel()); } else { logger.warn("Backend connection failed: {}", future.cause().toString()); } } } }); connFuture.await(getConnectTimeoutMillis(), TimeUnit.MILLISECONDS); if (connFuture.isSuccess()) { isFinalSuccess.set(true); break; } } catch (Exception e) { logger.error("Connecting exception {} caught:", e); } } if (isFinalSuccess.get() && isRetryOccured.get()) { logger.warn("Protected from Error-Neko: {} times", nekoKilled.incrementAndGet()); } }
From source file:com.github.sinsinpub.pero.backend.ConnectBackendHandler.java
License:Apache License
/** * Create new promised callback on outbound channel operation complete. * //from ww w . j a v a 2 s.c o m * @param ctx * @param request * @return Promise */ protected Promise<Channel> newOutboundPromise(final ChannelHandlerContext ctx, final SocksCmdRequest request) { final Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType())) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) { ctx.pipeline().remove(ConnectBackendHandler.this); outboundChannel.pipeline().addLast(new RelayTrafficHandler(ctx.channel())); ctx.pipeline().addLast(new RelayTrafficHandler(outboundChannel)); } }); } else { ctx.channel() .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); NettyChannelUtils.closeOnFlush(ctx.channel()); } } }); return promise; }
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 w w w .java 2 s.co m*/ * 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.// w w w . j a v a2 s.c o m * @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.// ww w .j ava 2 s. com * @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.// www . ja v a 2 s.com * @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. *//*from ww w.jav a2 s. c om*/ 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.github.wolf480pl.ircd.netty.NettyServer.java
License:Open Source License
public ChannelFuture stop() { if (!started.get()) { return null; //TODO: Failed future? }/*from ww w. ja v a 2s. c om*/ if (!stopped.compareAndSet(false, true)) { return null; //TODO: Failed future? } return channel.close().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } }); }
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// w ww. j a v a 2 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/*from w ww. jav a2 s. c om*/ public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { ctx.channel().read(); } else { future.channel().close(); } } }); }