List of usage examples for io.netty.channel ChannelFutureListener ChannelFutureListener
ChannelFutureListener
From source file:com.chenyang.proxy.http.HttpUserAgentForwardHandler.java
License:Apache License
@Override public void channelInactive(ChannelHandlerContext uaChannelCtx) throws Exception { for (Map.Entry<String, Channel> entry : remoteChannelMap.entrySet()) { final Channel remoteChannel = entry.getValue(); remoteChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(new ChannelFutureListener() { @Override/*w ww . j av a 2 s. co m*/ public void operationComplete(ChannelFuture future) throws Exception { remoteChannel.close(); } }); } }
From source file:com.chenyang.proxy.http.HttpUserAgentTunnelHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext uaChannelCtx, Object msg) throws Exception { if (msg instanceof HttpRequest) { // Channel uaChannel = uaChannelCtx.channel(); // connect remote Bootstrap bootstrap = new Bootstrap(); bootstrap.group(uaChannelCtx.channel().eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.AUTO_READ, false) .handler(new HttpTunnelChannelInitializer(uaChannelCtx.channel())); final HttpRemote apnProxyRemote = uaChannelCtx.channel().attr(HttpConnectionAttribute.ATTRIBUTE_KEY) .get().getRemote();//from w ww .j a v a 2s . c om bootstrap .connect(apnProxyRemote.getInetSocketAddress(), new InetSocketAddress(NetworkUtils.getCyclicLocalIp().getHostAddress(), 0)) .addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future1) throws Exception { if (future1.isSuccess()) { HttpResponse proxyConnectSuccessResponse = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "Connection established")); uaChannelCtx.writeAndFlush(proxyConnectSuccessResponse) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future2) throws Exception { // remove handlers uaChannelCtx.pipeline().remove("codec"); uaChannelCtx.pipeline().remove(HttpPreHandler.HANDLER_NAME); uaChannelCtx.pipeline() .remove(HttpUserAgentTunnelHandler.HANDLER_NAME); uaChannelCtx.pipeline() .addLast(new HttpRelayHandler( "UA --> " + apnProxyRemote.getRemoteAddr(), future1.channel())); } }); } else { if (uaChannelCtx.channel().isActive()) { uaChannelCtx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(ChannelFutureListener.CLOSE); } } } }); } ReferenceCountUtil.release(msg); }
From source file:com.cloudera.livy.client.local.rpc.Rpc.java
License:Apache License
/** * Creates an RPC client for a server running on the given remote host and port. * * @param config RPC configuration data. * @param eloop Event loop for managing the connection. * @param host Host name or IP address to connect to. * @param port Port where server is listening. * @param clientId The client ID that identifies the connection. * @param secret Secret for authenticating the client with the server. * @param dispatcher Dispatcher used to handle RPC calls. * @return A future that can be used to monitor the creation of the RPC object. *//*from w ww. j a v a 2 s .com*/ public static Promise<Rpc> createClient(final LocalConf config, final EventLoopGroup eloop, String host, int port, final String clientId, final String secret, final RpcDispatcher dispatcher) throws Exception { int connectTimeoutMs = (int) config.getTimeAsMs(RPC_CLIENT_CONNECT_TIMEOUT); final ChannelFuture cf = new Bootstrap().group(eloop).handler(new ChannelInboundHandlerAdapter() { }).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMs).connect(host, port); final Promise<Rpc> promise = eloop.next().newPromise(); final AtomicReference<Rpc> rpc = new AtomicReference<Rpc>(); // Set up a timeout to undo everything. final Runnable timeoutTask = new Runnable() { @Override public void run() { promise.setFailure(new TimeoutException("Timed out waiting for RPC server connection.")); } }; final ScheduledFuture<?> timeoutFuture = eloop.schedule(timeoutTask, config.getTimeAsMs(RPC_CLIENT_HANDSHAKE_TIMEOUT), TimeUnit.MILLISECONDS); // The channel listener instantiates the Rpc instance when the connection is established, // and initiates the SASL handshake. cf.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture cf) throws Exception { if (cf.isSuccess()) { SaslClientHandler saslHandler = new SaslClientHandler(config, clientId, promise, timeoutFuture, secret, dispatcher); Rpc rpc = createRpc(config, saslHandler, (SocketChannel) cf.channel(), eloop); saslHandler.rpc = rpc; saslHandler.sendHello(cf.channel()); } else { promise.setFailure(cf.cause()); } } }); // Handle cancellation of the promise. promise.addListener(new GenericFutureListener<Promise<Rpc>>() { @Override public void operationComplete(Promise<Rpc> p) { if (p.isCancelled()) { cf.cancel(true); } } }); return promise; }
From source file:com.cloudera.livy.client.local.rpc.Rpc.java
License:Apache License
/** * Send an RPC call to the remote endpoint and returns a future that can be used to monitor the * operation./*from www .j av a 2 s .c o m*/ * * @param msg RPC call to send. * @param retType Type of expected reply. * @return A future used to monitor the operation. */ public <T> Future<T> call(Object msg, Class<T> retType) { Preconditions.checkArgument(msg != null); Preconditions.checkState(channel.isOpen(), "RPC channel is closed."); try { final long id = rpcId.getAndIncrement(); final Promise<T> promise = createPromise(); ChannelFutureListener listener = new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture cf) { if (!cf.isSuccess() && !promise.isDone()) { LOG.warn("Failed to send RPC, closing connection.", cf.cause()); promise.setFailure(cf.cause()); dispatcher.discardRpc(id); close(); } } }; dispatcher.registerRpc(id, promise, msg.getClass().getName()); synchronized (channelLock) { channel.write(new MessageHeader(id, Rpc.MessageType.CALL)).addListener(listener); channel.writeAndFlush(msg).addListener(listener); } return promise; } catch (Exception e) { throw Throwables.propagate(e); } }
From source file:com.cloudera.livy.rsc.rpc.Rpc.java
License:Apache License
/** * Creates an RPC client for a server running on the given remote host and port. * * @param config RPC configuration data. * @param eloop Event loop for managing the connection. * @param host Host name or IP address to connect to. * @param port Port where server is listening. * @param clientId The client ID that identifies the connection. * @param secret Secret for authenticating the client with the server. * @param dispatcher Dispatcher used to handle RPC calls. * @return A future that can be used to monitor the creation of the RPC object. *//*from w w w .j a v a2 s.c o m*/ public static Promise<Rpc> createClient(final RSCConf config, final EventLoopGroup eloop, String host, int port, final String clientId, final String secret, final RpcDispatcher dispatcher) throws Exception { int connectTimeoutMs = (int) config.getTimeAsMs(RPC_CLIENT_CONNECT_TIMEOUT); final ChannelFuture cf = new Bootstrap().group(eloop).handler(new ChannelInboundHandlerAdapter() { }).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMs).connect(host, port); final Promise<Rpc> promise = eloop.next().newPromise(); final AtomicReference<Rpc> rpc = new AtomicReference<Rpc>(); // Set up a timeout to undo everything. final Runnable timeoutTask = new Runnable() { @Override public void run() { promise.setFailure(new TimeoutException("Timed out waiting for RPC server connection.")); } }; final ScheduledFuture<?> timeoutFuture = eloop.schedule(timeoutTask, config.getTimeAsMs(RPC_CLIENT_HANDSHAKE_TIMEOUT), TimeUnit.MILLISECONDS); // The channel listener instantiates the Rpc instance when the connection is established, // and initiates the SASL handshake. cf.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture cf) throws Exception { if (cf.isSuccess()) { SaslClientHandler saslHandler = new SaslClientHandler(config, clientId, promise, timeoutFuture, secret, dispatcher); Rpc rpc = createRpc(config, saslHandler, (SocketChannel) cf.channel(), eloop); saslHandler.rpc = rpc; saslHandler.sendHello(cf.channel()); } else { promise.setFailure(cf.cause()); } } }); // Handle cancellation of the promise. promise.addListener(new GenericFutureListener<Promise<Rpc>>() { @Override public void operationComplete(Promise<Rpc> p) { if (p.isCancelled()) { cf.cancel(true); } } }); return promise; }
From source file:com.cloudera.livy.rsc.rpc.Rpc.java
License:Apache License
/** * Send an RPC call to the remote endpoint and returns a future that can be used to monitor the * operation./*from w ww .j a v a2 s . c o m*/ * * @param msg RPC call to send. * @param retType Type of expected reply. * @return A future used to monitor the operation. */ public <T> Future<T> call(Object msg, Class<T> retType) { Utils.checkArgument(msg != null); Utils.checkState(channel.isOpen(), "RPC channel is closed."); try { final long id = rpcId.getAndIncrement(); final Promise<T> promise = egroup.next().newPromise(); ChannelFutureListener listener = new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture cf) { if (!cf.isSuccess() && !promise.isDone()) { LOG.warn("Failed to send RPC, closing connection.", cf.cause()); promise.setFailure(cf.cause()); dispatcher.discardRpc(id); close(); } } }; dispatcher.registerRpc(id, promise, msg.getClass().getName()); synchronized (channelLock) { channel.write(new MessageHeader(id, Rpc.MessageType.CALL)).addListener(listener); channel.writeAndFlush(msg).addListener(listener); } return promise; } catch (Exception e) { throw Utils.propagate(e); } }
From source file:com.codebullets.external.party.simulator.connections.websocket.inbound.NettyWebSocketServerHandler.java
License:Apache License
private void handleHttpRequest(final ChannelHandlerContext ctx, final FullHttpRequest req) { if (!req.getDecoderResult().isSuccess()) { // Handle a bad request. sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); } else if (req.getMethod() != GET) { // Allow only GET methods. sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); } else if ("/".equals(req.getUri())) { ByteBuf content = WebSocketServerIndexPage.getContent(endpoint.toString()); FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content); res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8"); setContentLength(res, content.readableBytes()); sendHttpResponse(ctx, req, res); } else if ("/favicon.ico".equals(req.getUri())) { // Send the demo page and favicon.ico FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND); sendHttpResponse(ctx, req, res); } else {/* w w w .ja v a 2 s .c o m*/ // Handshake WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(endpoint.toString(), null, false); handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel()); } else { handshaker.handshake(ctx.channel(), req).addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { connectedChannels.add(ctx.channel()); connectionMonitor.connectionEstablished(getContext(ctx)); } } }); } } }
From source file:com.codebullets.external.party.simulator.connections.websocket.outbound.OutboundWebSocketConnection.java
License:Apache License
/** * Open the connection to the target web socket endpoint. *///from w w w .j a v a2 s. c o m public void openConnection() { LOG.info("Connecting to web socket server at {}", targetEndpoint); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(eventGroup).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT_MILLIS) .handler(new WebSocketClientInitializer(monitor, connectionConfig, this)); bootstrap.connect(targetEndpoint.getHost(), targetEndpoint.getPort()) .addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { connectionEstablished(future.channel()); } else { LOG.warn("Connection to {} failed: {}", targetEndpoint, future.cause().getMessage()); eventGroup.schedule(new Runnable() { @Override public void run() { openConnection(); } }, CONNECT_RETRY_DELAY_MILLIS, TimeUnit.MILLISECONDS); } } }); }
From source file:com.corundumstudio.socketio.transport.WebSocketTransport.java
License:Apache License
private void handshake(ChannelHandlerContext ctx, final UUID sessionId, String path, FullHttpRequest req) { final Channel channel = ctx.channel(); WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req), null, false, configuration.getMaxFramePayloadLength()); WebSocketServerHandshaker handshaker = factory.newHandshaker(req); if (handshaker != null) { ChannelFuture f = handshaker.handshake(channel, req); f.addListener(new ChannelFutureListener() { @Override// w w w. j av a 2 s. c o m public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { log.error("Can't handshake " + sessionId, future.cause()); return; } channel.pipeline().addBefore(SocketIOChannelInitializer.WEB_SOCKET_TRANSPORT, SocketIOChannelInitializer.WEB_SOCKET_AGGREGATOR, new WebSocketFrameAggregator(configuration.getMaxFramePayloadLength())); connectClient(channel, sessionId); } }); } else { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } }
From source file:com.corundumstudio.socketio.transport.XHRPollingTransport.java
License:Apache License
private void scheduleDisconnect(Channel channel, final UUID sessionId) { final SchedulerKey key = new SchedulerKey(Type.CLOSE_TIMEOUT, sessionId); scheduler.cancel(key);/* www . j a v a 2 s.c om*/ ChannelFuture future = channel.closeFuture(); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { scheduler.scheduleCallback(key, new Runnable() { @Override public void run() { XHRPollingClient client = sessionId2Client.get(sessionId); if (client != null) { client.onChannelDisconnect(); log.debug("Client: {} disconnected due to connection timeout", sessionId); } } }, configuration.getCloseTimeout(), TimeUnit.SECONDS); } }); }