io.netty.util.concurrent.GenericFutureListener Java Examples
The following examples show how to use
io.netty.util.concurrent.GenericFutureListener.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Listener.java From plog with Apache License 2.0 | 6 votes |
@Override protected void doStop() { //noinspection unchecked eventLoopGroup.shutdownGracefully().addListener(new GenericFutureListener() { @Override public void operationComplete(Future future) throws Exception { if (future.isSuccess()) { notifyStopped(); } else { Throwable failure = new Exception("Netty event loop did not shutdown properly", future.cause()); log.error("Shutdown failed", failure); notifyFailed(failure); } } }); }
Example #2
Source File: ProxyConnection.java From yfs with Apache License 2.0 | 6 votes |
/** * Disconnects. This will wait for pending writes to be flushed before * disconnecting. * * @return Future<Void> for when we're done disconnecting. If we weren't * connected, this returns null. */ Future<Void> disconnect() { if (channel == null) { return null; } else { final Promise<Void> promise = channel.newPromise(); writeToChannel(Unpooled.EMPTY_BUFFER).addListener( new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete( Future<? super Void> future) throws Exception { closeChannel(promise); } }); return promise; } }
Example #3
Source File: NettyClient2.java From wind-im with Apache License 2.0 | 6 votes |
public void disconnect() { // logger.info("close tcp socket, Disconnecting."); synchronized (this.clientBoot) { this.channelPromise = null; final Future<Void> channelCloseFuture; if (this.channelPromise != null) { channelCloseFuture = this.channelPromise.channel().close(); } else { channelCloseFuture = new SucceededFuture<Void>(GlobalEventExecutor.INSTANCE, null); } channelCloseFuture.addListener(new GenericFutureListener<Future<Void>>() { @Override public void operationComplete(final Future<Void> future) throws Exception { NettyClient2.this.clientBoot.config().group().shutdownGracefully(); } }); } // logger.info("close netty tcp socket connection"); }
Example #4
Source File: PlatformSSLClient.java From wind-im with Apache License 2.0 | 6 votes |
public void disconnect() { // logger.info("close tcp socket, Disconnecting."); synchronized (this.clientBoot) { this.channelPromise = null; final Future<Void> channelCloseFuture; if (this.channelPromise != null) { channelCloseFuture = this.channelPromise.channel().close(); } else { channelCloseFuture = new SucceededFuture<Void>(GlobalEventExecutor.INSTANCE, null); } channelCloseFuture.addListener(new GenericFutureListener<Future<Void>>() { @Override public void operationComplete(final Future<Void> future) throws Exception { PlatformSSLClient.this.clientBoot.config().group().shutdownGracefully(); } }); } // logger.info("close netty tcp socket connection"); }
Example #5
Source File: ReplicatorService.java From c5-replicator with Apache License 2.0 | 6 votes |
@Override protected void doStop() { fiber.execute(() -> { final AtomicInteger countDown = new AtomicInteger(1); GenericFutureListener<? extends Future<? super Void>> listener = future -> { if (countDown.decrementAndGet() == 0) { fiber.dispose(); fiber = null; notifyStopped(); } }; if (listenChannel != null) { countDown.incrementAndGet(); listenChannel.close().addListener(listener); } allChannels.close().addListener(listener); replicatorInstances.values().forEach(ReplicatorInstance::dispose); replicatorInstances.clear(); }); }
Example #6
Source File: MessageSender.java From lannister with Apache License 2.0 | 6 votes |
protected void send(MqttMessage message, GenericFutureListener<? extends Future<? super Void>> completeListener) { if (!session.isConnected(true)) { logger.error("Message is not sent - Channel is inactive or out of the node. [{}]", message); return; } ChannelHandlerContext ctx = Session.NEXUS.channelHandlerContext(session.clientId()); String log = message.toString(); ChannelFuture cf = ctx.writeAndFlush(message).addListener(f -> { if (f.isSuccess()) { logger.debug("packet outgoing [{}]", log); } else { logger.error("packet outgoing failed [{}] {}", log, f.cause()); } }); if (completeListener != null) { cf.addListener(completeListener); } }
Example #7
Source File: ConnectInterceptingHandler.java From java-dcp-client with Apache License 2.0 | 6 votes |
/** * Intercept the connect phase and store the original promise. */ @Override public void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) throws Exception { originalPromise = promise; ChannelPromise inboundPromise = ctx.newPromise(); inboundPromise.addListener(new GenericFutureListener<Future<Void>>() { @Override public void operationComplete(Future<Void> future) throws Exception { if (!future.isSuccess() && !originalPromise.isDone()) { originalPromise.setFailure(future.cause()); } } }); ctx.connect(remoteAddress, localAddress, inboundPromise); }
Example #8
Source File: WsServer.java From wind-im with Apache License 2.0 | 6 votes |
public void start(String address, int port) throws Exception { try { if (bootstrap != null) { ChannelFuture channelFuture = bootstrap.bind(address, port).sync(); channelFuture.channel().closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(Future<? super Void> future) throws Exception { closeGracefully(); } }); } else { throw new Exception(); } } catch (Exception e) { closeGracefully(); throw new Exception("start websocket server error", e); } }
Example #9
Source File: ProxyToServerConnection.java From yfs with Apache License 2.0 | 6 votes |
@Override protected Future<?> execute() { return clientConnection .encrypt(proxyServer.getMitmManager() .clientSslEngineFor(initialRequest, sslEngine.getSession()), false) .addListener( new GenericFutureListener<Future<? super Channel>>() { @Override public void operationComplete( Future<? super Channel> future) throws Exception { if (future.isSuccess()) { clientConnection.setMitming(true); } } }); }
Example #10
Source File: HttpOrHttp2ChannelPool.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
private void acquire0(Promise<Channel> promise) { if (closed) { promise.setFailure(new IllegalStateException("Channel pool is closed!")); return; } if (protocolImpl != null) { protocolImpl.acquire(promise); return; } if (protocolImplPromise == null) { initializeProtocol(); } protocolImplPromise.addListener((GenericFutureListener<Future<ChannelPool>>) future -> { if (future.isSuccess()) { future.getNow().acquire(promise); } else { // Couldn't negotiate protocol, fail this acquire. promise.setFailure(future.cause()); } }); }
Example #11
Source File: NettyWebsocketTtyBootstrap.java From termd with Apache License 2.0 | 6 votes |
public void stop(final Consumer<Throwable> doneHandler) { if (channel != null) { channel.close(); } channelGroup.close().addListener(new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(Future<? super Void> future) throws Exception { try { doneHandler.accept(future.cause()); } finally { group.shutdownGracefully(); } } }); }
Example #12
Source File: SecureChatServerHandler.java From netty4.0.27Learn with Apache License 2.0 | 6 votes |
@Override public void channelActive(final ChannelHandlerContext ctx) { // Once session is secured, send a greeting and register the channel to the global channel // list so the channel received the messages from others. ctx.pipeline().get(SslHandler.class).handshakeFuture().addListener( new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(Future<Channel> future) throws Exception { ctx.writeAndFlush( "Welcome to " + InetAddress.getLocalHost().getHostName() + " secure chat service!\n"); ctx.writeAndFlush( "Your session is protected by " + ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite() + " cipher suite.\n"); channels.add(ctx.channel()); } }); }
Example #13
Source File: WsServer.java From openzaly with Apache License 2.0 | 6 votes |
public void start(String address, int port) throws Exception { try { if (bootstrap != null) { ChannelFuture channelFuture = bootstrap.bind(address, port).sync(); channelFuture.channel().closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(Future<? super Void> future) throws Exception { closeGracefully(); } }); } else { throw new Exception(); } } catch (Exception e) { closeGracefully(); throw new Exception("start websocket server error", e); } }
Example #14
Source File: HttpServer.java From openzaly with Apache License 2.0 | 6 votes |
public void start(String address, int port) throws HttpServerException { try { ChannelFuture channelFuture = bootstrap.bind(address, port).sync(); channelFuture.channel().closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(Future<? super Void> future) throws Exception { closeGracefylly(); } }); } catch (Exception e) { closeGracefylly(); throw new HttpServerException("start openzaly http-server error", e); } }
Example #15
Source File: ProxyConnection.java From yfs with Apache License 2.0 | 6 votes |
private void closeChannel(final Promise<Void> promise) { channel.close().addListener( new GenericFutureListener<Future<? super Void>>() { public void operationComplete( Future<? super Void> future) throws Exception { if (future .isSuccess()) { promise.setSuccess(null); } else { promise.setFailure(future .cause()); } }; }); }
Example #16
Source File: NettyTransportClient.java From Sentinel-Dashboard-Nacos with Apache License 2.0 | 6 votes |
private void connect(Bootstrap b) { if (currentState.compareAndSet(ClientConstants.CLIENT_STATUS_OFF, ClientConstants.CLIENT_STATUS_PENDING)) { b.connect(host, port) .addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(ChannelFuture future) { if (future.cause() != null) { RecordLog.warn( String.format("[NettyTransportClient] Could not connect to <%s:%d> after %d times", host, port, failConnectedTime.get()), future.cause()); failConnectedTime.incrementAndGet(); channel = null; } else { failConnectedTime.set(0); channel = future.channel(); RecordLog.info( "[NettyTransportClient] Successfully connect to server <" + host + ":" + port + ">"); } } }); } }
Example #17
Source File: ChannelPipelineFinalizerHandlerTest.java From riposte with Apache License 2.0 | 6 votes |
@Test public void finalizeChannelPipeline_should_send_event_to_metricsListener_for_successful_response_and_flush_context() throws Exception { // given ChannelFuture responseWriterChannelFuture = mock(ChannelFuture.class); state.setResponseWriterFinalChunkChannelFuture(responseWriterChannelFuture); HttpProcessingState stateSpy = spy(state); doReturn(stateSpy).when(stateAttributeMock).get(); ChannelFuture responseWriteFutureResult = mock(ChannelFuture.class); doReturn(true).when(responseWriteFutureResult).isSuccess(); Assertions.assertThat(stateSpy.isRequestMetricsRecordedOrScheduled()).isFalse(); // when handler.finalizeChannelPipeline(ctxMock, null, stateSpy, null); // then ArgumentCaptor<GenericFutureListener> channelFutureListenerArgumentCaptor = ArgumentCaptor.forClass(GenericFutureListener.class); verify(responseWriterChannelFuture).addListener(channelFutureListenerArgumentCaptor.capture()); GenericFutureListener futureListener = channelFutureListenerArgumentCaptor.getValue(); assertThat(futureListener, notNullValue()); futureListener.operationComplete(responseWriteFutureResult); verify(metricsListenerMock).onEvent(eq(ServerMetricsEvent.RESPONSE_SENT), any(HttpProcessingState.class)); verify(ctxMock).flush(); Assertions.assertThat(stateSpy.isRequestMetricsRecordedOrScheduled()).isTrue(); }
Example #18
Source File: NettyWebsocketTtyBootstrap.java From arthas with Apache License 2.0 | 6 votes |
public void stop(final Consumer<Throwable> doneHandler) { if (channel != null) { channel.close(); } channelGroup.close().addListener(new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(Future<? super Void> future) throws Exception { try { doneHandler.accept(future.cause()); } finally { group.shutdownGracefully(); } } }); }
Example #19
Source File: SecureChatServerHandler.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
@Override public void channelActive(final ChannelHandlerContext ctx) { // Once session is secured, send a greeting and register the channel to the global channel // list so the channel received the messages from others. ctx.pipeline().get(SslHandler.class).handshakeFuture().addListener( new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(Future<Channel> future) throws Exception { ctx.writeAndFlush( "Welcome to " + InetAddress.getLocalHost().getHostName() + " secure chat service!\n"); ctx.writeAndFlush( "Your session is protected by " + ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite() + " cipher suite.\n"); channels.add(ctx.channel()); } }); }
Example #20
Source File: ConnectionFlow.java From g4proxy with Apache License 2.0 | 6 votes |
/** * Does the work of processing the current step, checking the result and * handling success/failure. * * @param LOG */ @SuppressWarnings("unchecked") private void doProcessCurrentStep(final ProxyConnectionLogger LOG) { currentStep.execute().addListener( new GenericFutureListener<Future<?>>() { public void operationComplete( io.netty.util.concurrent.Future<?> future) throws Exception { synchronized (connectLock) { if (future.isSuccess()) { LOG.debug("ConnectionFlowStep succeeded"); currentStep .onSuccess(ConnectionFlow.this); } else { LOG.debug("ConnectionFlowStep failed", future.cause()); fail(future.cause()); } } }; }); }
Example #21
Source File: NettyTransportClient.java From Sentinel with Apache License 2.0 | 6 votes |
private void connect(Bootstrap b) { if (currentState.compareAndSet(ClientConstants.CLIENT_STATUS_OFF, ClientConstants.CLIENT_STATUS_PENDING)) { b.connect(host, port) .addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(ChannelFuture future) { if (future.cause() != null) { RecordLog.warn( String.format("[NettyTransportClient] Could not connect to <%s:%d> after %d times", host, port, failConnectedTime.get()), future.cause()); failConnectedTime.incrementAndGet(); channel = null; } else { failConnectedTime.set(0); channel = future.channel(); RecordLog.info( "[NettyTransportClient] Successfully connect to server <" + host + ":" + port + ">"); } } }); } }
Example #22
Source File: NettyTelnetBootstrap.java From termd with Apache License 2.0 | 5 votes |
@Override public void stop(final Consumer<Throwable> doneHandler) { GenericFutureListener<Future<Object>> adapter = new GenericFutureListener<Future<Object>>() { @Override public void operationComplete(Future<Object> future) throws Exception { try { doneHandler.accept(future.cause()); } finally { group.shutdownGracefully(); } } }; channelGroup.close().addListener(adapter); }
Example #23
Source File: ClientToProxyConnection.java From g4proxy with Apache License 2.0 | 5 votes |
ClientToProxyConnection( final DefaultHttpProxyServer proxyServer, SslEngineSource sslEngineSource, boolean authenticateClients, ChannelPipeline pipeline, GlobalTrafficShapingHandler globalTrafficShapingHandler) { super(AWAITING_INITIAL, proxyServer, false); initChannelPipeline(pipeline); if (sslEngineSource != null) { LOG.debug("Enabling encryption of traffic from client to proxy"); encrypt(pipeline, sslEngineSource.newSslEngine(), authenticateClients) .addListener( new GenericFutureListener<Future<? super Channel>>() { @Override public void operationComplete( Future<? super Channel> future) throws Exception { if (future.isSuccess()) { clientSslSession = sslEngine .getSession(); recordClientSSLHandshakeSucceeded(); } } }); } this.globalTrafficShapingHandler = globalTrafficShapingHandler; LOG.debug("Created ClientToProxyConnection"); }
Example #24
Source File: NettyClient2.java From wind-im with Apache License 2.0 | 5 votes |
public Future<IRedisCommandResponse> sendRedisCommand(final RedisCommand redisCommand) { final Future<IRedisCommandResponse> responseFuture; // logger.info("send push message {} {} {}", channelPromise, // channelPromise.isSuccess(), // channelPromise.channel().isActive()); if (channelPromise != null) { final ChannelPromise readyPromise = this.channelPromise; final DefaultPromise<IRedisCommandResponse> responsePromise = new DefaultPromise<IRedisCommandResponse>( readyPromise.channel().eventLoop()); // 提交一个事件 readyPromise.channel().eventLoop().submit(new Runnable() { @Override public void run() { // 将这个结果赋值给responsePromise NettyClient2.this.responsePromise = responsePromise; } }); readyPromise.channel().writeAndFlush(redisCommand).addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (!future.isSuccess()) { // 如果失败了,直接将promise返回 responsePromise.tryFailure(future.cause()); logger.error("send push message error: {},cause={}", redisCommand, future.cause()); } else { // logger.info("write data to platform success"); } } }); responseFuture = responsePromise; } else { logger.error("send push error because client is not connected: {}", redisCommand.toString()); responseFuture = new FailedFuture<IRedisCommandResponse>(GlobalEventExecutor.INSTANCE, CONNECT_EXCEPTION); } return responseFuture; }
Example #25
Source File: NettyChannel.java From herddb with Apache License 2.0 | 5 votes |
@Override public void sendOneWayMessage(ByteBuf message, SendResultCallback callback) { io.netty.channel.Channel _socket = this.socket; if (_socket == null || !_socket.isOpen()) { callback.messageSent(new Exception(this + " connection is closed")); return; } if (LOGGER.isLoggable(Level.FINEST)) { StringBuilder dumper = new StringBuilder(); ByteBufUtil.appendPrettyHexDump(dumper, message); LOGGER.log(Level.FINEST, "Sending to {}: {}", new Object[]{_socket, dumper}); } _socket.writeAndFlush(message).addListener(new GenericFutureListener() { @Override public void operationComplete(Future future) throws Exception { if (future.isSuccess()) { callback.messageSent(null); } else { LOGGER.log(Level.SEVERE, this + ": error " + future.cause(), future.cause()); callback.messageSent(future.cause()); close(); } } }); unflushedWrites.incrementAndGet(); }
Example #26
Source File: MessageEncoder.java From openzaly with Apache License 2.0 | 5 votes |
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { promise.addListener(new GenericFutureListener<Future<? super Void>>() { public void operationComplete(Future<? super Void> future) throws Exception { if (!future.isSuccess()) { logger.error("write data to client fail ", future.cause()); } } }); super.write(ctx, msg, promise); }
Example #27
Source File: NettyClient2.java From openzaly with Apache License 2.0 | 5 votes |
public Future<IRedisCommandResponse> sendRedisCommand(final RedisCommand redisCommand) { final Future<IRedisCommandResponse> responseFuture; // logger.info("send push message {} {} {}", channelPromise, // channelPromise.isSuccess(), // channelPromise.channel().isActive()); if (channelPromise != null) { final ChannelPromise readyPromise = this.channelPromise; final DefaultPromise<IRedisCommandResponse> responsePromise = new DefaultPromise<IRedisCommandResponse>( readyPromise.channel().eventLoop()); // 提交一个事件 readyPromise.channel().eventLoop().submit(new Runnable() { @Override public void run() { // 将这个结果赋值给responsePromise NettyClient2.this.responsePromise = responsePromise; } }); readyPromise.channel().writeAndFlush(redisCommand).addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (!future.isSuccess()) { // 如果失败了,直接将promise返回 responsePromise.tryFailure(future.cause()); logger.error("send push message error: {},cause={}", redisCommand, future.cause()); } else { // logger.info("write data to platform success"); } } }); responseFuture = responsePromise; } else { logger.error("send push error because client is not connected: {}", redisCommand.toString()); responseFuture = new FailedFuture<IRedisCommandResponse>(GlobalEventExecutor.INSTANCE, CONNECT_EXCEPTION); } return responseFuture; }
Example #28
Source File: GenericClient.java From bitchat with Apache License 2.0 | 5 votes |
@Override public CompletableFuture<Packet> sendRequest(Packet request) { // create a promise CompletableFuture<Packet> promise = new CompletableFuture<>(); if (!connected) { String msg = "Not connected yet!"; log.debug(msg); Payload payload = PayloadFactory.newErrorPayload(ResultCode.BIZ_FAIL.getCode(), msg); promise.complete(PacketFactory.newResponsePacket(payload, request.getId())); return promise; } Long id = request.getId(); PendingPackets.add(id, promise); ChannelFuture future = channel.writeAndFlush(request); future.addListener(new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(Future<? super Void> f) throws Exception { if (!f.isSuccess()) { CompletableFuture<Packet> pending = PendingPackets.remove(id); if (pending != null) { pending.completeExceptionally(f.cause()); } } } }); return promise; }
Example #29
Source File: MixinClientConnection.java From bleachhack-1.14 with GNU General Public License v3.0 | 5 votes |
@Inject(method = "send(Lnet/minecraft/network/Packet;Lio/netty/util/concurrent/GenericFutureListener;)V", at = @At("HEAD"), cancellable = true) public void send(Packet<?> packet_1, GenericFutureListener<? extends Future<? super Void>> genericFutureListener_1, CallbackInfo callback) { if (packet_1 instanceof ChatMessageC2SPacket) { ChatMessageC2SPacket pack = (ChatMessageC2SPacket) packet_1; if (pack.getChatMessage().startsWith(CommandManager.prefix)) { CommandManager.callCommand(pack.getChatMessage().substring(CommandManager.prefix.length())); callback.cancel(); } } EventSendPacket event = new EventSendPacket(packet_1); BleachHack.eventBus.post(event); if (event.isCancelled()) callback.cancel(); }
Example #30
Source File: RequestContextAwareProgressivePromise.java From armeria with Apache License 2.0 | 5 votes |
@Override @SafeVarargs public final ProgressivePromise<T> addListeners( GenericFutureListener<? extends Future<? super T>>... listeners) { for (GenericFutureListener<? extends Future<? super T>> l : listeners) { delegate.addListeners(RequestContextAwareFutureListener.of(context, l)); } return this; }