io.netty.util.concurrent.Future Java Examples

The following examples show how to use io.netty.util.concurrent.Future. 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: DefaultDnsClient.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
private void doQuery0() {
    assertInEventloop();

    if (closed) {
        // best effort check to cleanup state after close.
        handleTerminalError0(new ClosedServiceDiscovererException(DefaultDnsClient.this +
                " has been closed!"));
    } else {
        final DnsResolutionObserver resolutionObserver = newResolutionObserver();
        LOGGER.trace("DnsClient {}, querying DNS for {}", DefaultDnsClient.this, AbstractDnsPublisher.this);
        final Future<DnsAnswer<T>> addressFuture = doDnsQuery();
        cancellableForQuery = () -> addressFuture.cancel(true);
        if (addressFuture.isDone()) {
            handleResolveDone0(addressFuture, resolutionObserver);
        } else {
            addressFuture.addListener((FutureListener<DnsAnswer<T>>) f ->
                    handleResolveDone0(f, resolutionObserver));
        }
    }
}
 
Example #2
Source File: ChannelWriter.java    From openzaly with Apache License 2.0 6 votes vote down vote up
public static void writeAndClose(final Channel channel, CommandResponse response) {
	CoreProto.TransportPackageData.Builder packageDataBuilder = CoreProto.TransportPackageData.newBuilder();
	CoreProto.ErrorInfo errorInfo = CoreProto.ErrorInfo.newBuilder().setCode(response.getErrCode())
			.setInfo(String.valueOf(response.getErrInfo())).build();
	packageDataBuilder.setErr(errorInfo);

	Map<Integer, String> header = new HashMap<Integer, String>();
	header.put(CoreProto.HeaderKey.SITE_SERVER_VERSION_VALUE, CommandConst.SITE_VERSION);
	packageDataBuilder.putAllHeader(header);

	if (response.getParams() != null) {
		packageDataBuilder.setData(ByteString.copyFrom(response.getParams()));
	}
	channel.writeAndFlush(new RedisCommand().add(response.getVersion()).add(response.getAction())
			.add(packageDataBuilder.build().toByteArray()))
			.addListener(new GenericFutureListener<Future<? super Void>>() {

				@Override
				public void operationComplete(Future<? super Void> future) throws Exception {
					channel.close();
				}
			});
}
 
Example #3
Source File: VirtualClientConnection.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private void finishPeerRead0(VirtualChannel peer) {
    Future<?> peerFinishReadFuture = peer.finishReadFuture;
    if (peerFinishReadFuture != null) {
        if (!peerFinishReadFuture.isDone()) {
            runFinishPeerReadTask(peer);
            return;
        } else {
            // Lazy unset to make sure we don't prematurely unset it while scheduling a new task.
            VirtualChannel.FINISH_READ_FUTURE_UPDATER.compareAndSet(peer, peerFinishReadFuture, null);
        }
    }
    // We should only set readInProgress to false if there is any data that was read as otherwise we may miss to
    // forward data later on.
    if (peer.readInProgress && !peer.inboundBuffer.isEmpty()) {
        peer.readInProgress = false;
        peer.readInbound();
    }
}
 
Example #4
Source File: NettyChannel.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public void writeAndFlush(final Object obj) {
    Future future = channel.writeAndFlush(obj);
    future.addListener(new FutureListener() {
        @Override
        public void operationComplete(Future future1) throws Exception {
            if (!future1.isSuccess()) {
                Throwable throwable = future1.cause();
                LOGGER.error("Failed to send to "
                    + NetUtils.channelToString(localAddress(), remoteAddress())
                    + " for msg : " + obj
                    + ", Cause by:", throwable);
            }
        }
    });
}
 
Example #5
Source File: PlatformClient.java    From openzaly with Apache License 2.0 6 votes vote down vote up
public static byte[] syncWrite(String action, byte[] byteData) {
	try {
		CoreProto.TransportPackageData.Builder packageDataBuilder = CoreProto.TransportPackageData.newBuilder();
		Map<Integer, String> header = new HashMap<Integer, String>();
		header.put(CoreProto.HeaderKey.SITE_SERVER_VERSION_VALUE, CommandConst.SITE_VERSION);
		packageDataBuilder.putAllHeader(header);
		packageDataBuilder.setData(ByteString.copyFrom(byteData));
		PlatformSSLClient nettyClient = new PlatformSSLClient();
		nettyClient.connect(AKAXIN_PLATFROM_HOST, AKAXIN_PLATFROM_PORT);
		Future<IRedisCommandResponse> future = nettyClient.sendRedisCommand(new RedisCommand()
				.add(CommandConst.PROTOCOL_VERSION).add(action).add(packageDataBuilder.build().toByteArray()));
		IRedisCommandResponse response = future.get(5, TimeUnit.SECONDS);
		nettyClient.disconnect();
		if (response != null && response.isSuccess()) {
			return getResponseBytes(response.getRedisCommand());
		}
		logger.debug("sync write data to platform with response={}", response);
	} catch (Exception e) {
		logger.error("sync send package error ", e);
	}
	return null;
}
 
Example #6
Source File: SecureChatServerHandler.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@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 #7
Source File: AbstractExecutor.java    From bitchat with Apache License 2.0 6 votes vote down vote up
@Override
public Future<T> asyncExecute(Promise<T> promise, Object... request) {
    if (promise == null) {
        throw new IllegalArgumentException("promise should not be null");
    }
    // async execute
    eventExecutor.execute(new Runnable() {
        @Override
        public void run() {
            try {
                T response = doExecute(request);
                promise.setSuccess(response);
            } catch (Exception e) {
                promise.setFailure(e);
            }
        }
    });
    // return the promise back
    return promise;
}
 
Example #8
Source File: PlatformSSLClient.java    From openzaly with Apache License 2.0 6 votes vote down vote up
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 #9
Source File: PlatformSSLClient.java    From openzaly with Apache License 2.0 6 votes vote down vote up
public Future<Void> connect(String address, int port) {
	final Future<Void> connectionFuture;
	this.peerHost = address;
	this.peerPort = port;
	
	synchronized (clientBoot) {
		if (this.channelPromise == null) {
			try {
				final ChannelFuture connectFuture = this.clientBoot.connect(address, port).sync();
				this.channelPromise = connectFuture.channel().newPromise();

			} catch (Exception e) {
				logger.error("connect to akaxin platform error.", e);
			}

		}
		connectionFuture = this.channelPromise;
	}
	// logger.info("connect to server connectionFuture={}", connectionFuture);
	return connectionFuture;
}
 
Example #10
Source File: PushClient.java    From openzaly with Apache License 2.0 6 votes vote down vote up
public static void asyncWrite(String action, byte[] byteData) {
	try {
		CoreProto.TransportPackageData.Builder packageDataBuilder = CoreProto.TransportPackageData.newBuilder();
		Map<Integer, String> header = new HashMap<Integer, String>();
		header.put(CoreProto.HeaderKey.SITE_SERVER_VERSION_VALUE, CommandConst.SITE_VERSION);
		packageDataBuilder.putAllHeader(header);
		packageDataBuilder.setData(ByteString.copyFrom(byteData));
		PlatformSSLClient nettyClient = new PlatformSSLClient();
		nettyClient.connect(AKAXIN_PUSH_ADDRESS, AKAXIN_PUSH_PORT);
		Future<IRedisCommandResponse> future = nettyClient.sendRedisCommand(new RedisCommand()
				.add(CommandConst.PROTOCOL_VERSION).add(action).add(packageDataBuilder.build().toByteArray()));
		IRedisCommandResponse response = future.get(5, TimeUnit.SECONDS);
		logger.debug("write push to platform finish response={}", response);
		nettyClient.disconnect();
	} catch (Exception e) {
		logger.error("async send package to platform error", e);
	}
}
 
Example #11
Source File: PCEPSessionImpl.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Sends message to serialization.
 *
 * @param msg to be sent
 */
@Override
public Future<Void> sendMessage(final Message msg) {
    final ChannelFuture f = this.channel.writeAndFlush(msg);
    this.lastMessageSentAt = TICKER.read();
    this.sessionState.updateLastSentMsg();
    if (!(msg instanceof KeepaliveMessage)) {
        LOG.debug("PCEP Message enqueued: {}", msg);
    }
    if (msg instanceof PcerrMessage) {
        this.sessionState.setLastSentError(msg);
    }

    f.addListener((ChannelFutureListener) arg -> {
        if (arg.isSuccess()) {
            LOG.trace("Message sent to socket: {}", msg);
        } else {
            LOG.debug("Message not sent: {}", msg, arg.cause());
        }
    });

    return f;
}
 
Example #12
Source File: SecureChatServerHandler.java    From netty-learning with Apache License 2.0 6 votes vote down vote up
@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
    // 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: NettyTcpTransport.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Override
public void close() throws IOException {
   if (closed.compareAndSet(false, true)) {
      connected.set(false);
      try {
         if (channel != null) {
            channel.close().syncUninterruptibly();
         }
      } finally {
         if (group != null) {
            Future<?> fut = group.shutdownGracefully(0, SHUTDOWN_TIMEOUT, TimeUnit.MILLISECONDS);
            if (!fut.awaitUninterruptibly(2 * SHUTDOWN_TIMEOUT)) {
               LOG.trace("Channel group shutdown failed to complete in allotted time");
            }
         }
      }
   }
}
 
Example #14
Source File: ProxyConnection.java    From PowerTunnel with MIT License 6 votes vote down vote up
protected Future execute() {
    try {
        ChannelPipeline pipeline = ctx.pipeline();
        if (pipeline.get("encoder") != null) {
            pipeline.remove("encoder");
        }
        if (pipeline.get("responseWrittenMonitor") != null) {
            pipeline.remove("responseWrittenMonitor");
        }
        if (pipeline.get("decoder") != null) {
            pipeline.remove("decoder");
        }
        if (pipeline.get("requestReadMonitor") != null) {
            pipeline.remove("requestReadMonitor");
        }
        tunneling = true;
        return channel.newSucceededFuture();
    } catch (Throwable t) {
        return channel.newFailedFuture(t);
    }
}
 
Example #15
Source File: PipeTest.java    From netty-http2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testSSRR() {
    Future<Void> sendFuture1 = pipe.send(MESSAGE1);
    assertFalse(sendFuture1.isDone());

    Future<Void> sendFuture2 = pipe.send(MESSAGE2);
    assertFalse(sendFuture2.isDone());
    assertFalse(sendFuture1.isDone());

    Future<Object> recvFuture1 = pipe.receive();
    assertSame(MESSAGE1, recvFuture1.getNow());
    assertFalse(sendFuture2.isDone());
    assertTrue(sendFuture1.isSuccess());

    Future<Object> recvFuture2 = pipe.receive();
    assertSame(MESSAGE2, recvFuture2.getNow());
    assertTrue(recvFuture1.isSuccess());
    assertTrue(sendFuture2.isSuccess());
    assertTrue(sendFuture1.isSuccess());
}
 
Example #16
Source File: QueryResultHandler.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public void connectionSucceeded(final UserToBitConnection connection) {
  connection.getChannel().closeFuture().addListener(
      new GenericFutureListener<Future<? super Void>>() {
        @Override
        public void operationComplete(Future<? super Void> future)
            throws Exception {
          for (final UserResultsListener listener : queryIdToResultsListenersMap.values()) {
            listener.submissionFailed(UserException.connectionError()
                .message("Connection %s closed unexpectedly. Drillbit down?",
                    connection.getName())
                .build(logger));
            if (listener instanceof BufferingResultsListener) {
              // the appropriate listener will be failed by SubmissionListener#failed
              logger.warn("Buffering listener failed before results were transferred to the actual listener.");
            }
          }
        }
      });
  parentHandler.connectionSucceeded(connection);
}
 
Example #17
Source File: PlatformSSLClient.java    From openzaly with Apache License 2.0 6 votes vote down vote up
public Future<Void> connect(String address, int port) {
	final Future<Void> connectionFuture;
	this.peerHost = address;
	this.peerPort = port;
	
	synchronized (clientBoot) {
		if (this.channelPromise == null) {
			try {
				final ChannelFuture connectFuture = this.clientBoot.connect(address, port).sync();
				this.channelPromise = connectFuture.channel().newPromise();

			} catch (Exception e) {
				logger.error("connect to akaxin platform error.", e);
			}

		}
		connectionFuture = this.channelPromise;
	}
	// logger.info("connect to server connectionFuture={}", connectionFuture);
	return connectionFuture;
}
 
Example #18
Source File: PipeTest.java    From netty-http2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testRSCR() {
    Future<Object> recvFuture1 = pipe.receive();
    assertFalse(recvFuture1.isDone());

    Future<Void> sendFuture1 = pipe.send(MESSAGE);
    assertTrue(sendFuture1.isSuccess());
    assertSame(MESSAGE, recvFuture1.getNow());

    pipe.close();

    Future<Object> recvFuture2 = pipe.receive();
    assertNotNull(recvFuture2.cause());
    assertTrue(sendFuture1.isSuccess());
    assertTrue(recvFuture1.isSuccess());
}
 
Example #19
Source File: SecureChatServerHandler.java    From julongchain with Apache License 2.0 6 votes vote down vote up
@Override
public void channelActive(final ChannelHandlerContext ctx) {
    // 一旦session处于安全状态, 发送一个标记将但前channel注册到全局channel列表
    // 可以接收其他channel的消息.
    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: RefreshingAddressResolverTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void removedWhenNoCacheHit() throws Exception {
    try (TestDnsServer server = new TestDnsServer(ImmutableMap.of(
            new DefaultDnsQuestion("foo.com.", A),
            new DefaultDnsResponse(0).addRecord(ANSWER, newAddressRecord("foo.com.", "1.1.1.1", 1))))
    ) {
        final EventLoop eventLoop = eventLoopExtension.get();
        final DnsResolverGroupBuilder builder = builder(server);
        try (RefreshingAddressResolverGroup group = builder.build(eventLoop)) {
            final AddressResolver<InetSocketAddress> resolver = group.getResolver(eventLoop);

            final long start = System.nanoTime();

            final Future<InetSocketAddress> foo = resolver.resolve(
                    InetSocketAddress.createUnresolved("foo.com", 36462));
            await().untilAsserted(() -> assertThat(foo.isSuccess()).isTrue());
            assertThat(foo.getNow().getAddress().getHostAddress()).isEqualTo("1.1.1.1");

            final ConcurrentMap<String, CompletableFuture<CacheEntry>> cache = group.cache();
            await().until(cache::isEmpty);

            assertThat(System.nanoTime() - start).isGreaterThanOrEqualTo(
                    (long) (TimeUnit.SECONDS.toNanos(1) * 0.9));
        }
    }
}
 
Example #21
Source File: NettyRequestExecutor.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private void makeRequestListener(Future<Channel> channelFuture) {
    if (channelFuture.isSuccess()) {
        channel = channelFuture.getNow();
        configureChannel();
        if (tryConfigurePipeline()) {
            makeRequest();
        }
    } else {
        handleFailure(() -> "Failed to create connection to " + endpoint(), channelFuture.cause());
    }
}
 
Example #22
Source File: DefaultDnsClient.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
@Override
protected AbstractDnsSubscription newSubscription(
        final Subscriber<? super Iterable<ServiceDiscovererEvent<InetAddress>>> subscriber) {
    return new AbstractDnsSubscription(cancelClearsSubscription, subscriber) {
        @Override
        protected Future<DnsAnswer<InetAddress>> doDnsQuery() {
            ttlCache.prepareForResolution(name);
            Promise<DnsAnswer<InetAddress>> dnsAnswerPromise = ImmediateEventExecutor.INSTANCE.newPromise();
            resolver.resolveAll(name).addListener(completedFuture -> {
                Throwable cause = completedFuture.cause();
                if (cause != null) {
                    dnsAnswerPromise.setFailure(cause);
                } else {
                    final DnsAnswer<InetAddress> dnsAnswer;
                    try {
                        @SuppressWarnings("unchecked")
                        final List<InetAddress> addresses = (List<InetAddress>) completedFuture.getNow();
                        dnsAnswer = new DnsAnswer<>(addresses, SECONDS.toNanos(ttlCache.minTtl(name)));
                    } catch (Throwable cause2) {
                        dnsAnswerPromise.setFailure(cause2);
                        return;
                    }
                    dnsAnswerPromise.setSuccess(dnsAnswer);
                }
            });
            return dnsAnswerPromise;
        }

        @Override
        protected Comparator<InetAddress> comparator() {
            return INET_ADDRESS_COMPARATOR;
        }
    };
}
 
Example #23
Source File: FastdfsExecutor.java    From fastdfs-client with Apache License 2.0 5 votes vote down vote up
@Override
public void operationComplete(Future<Channel> cf) throws Exception {

    if (cf.isCancelled()) {
        promise.cancel(true);
        return;
    }

    if (!cf.isSuccess()) {
        promise.completeExceptionally(cf.cause());
        return;
    }

    Channel channel = cf.getNow();
    promise.whenComplete((result, error) -> {
        if (null != error) {
            channel.close().addListener(ignore -> pool.release(channel));
            return;
        }

        pool.release(channel);
    });

    try {

        FastdfsOperation<T> fastdfsOperation = new FastdfsOperation<>(channel, requestor, replier, promise);
        if (LOG.isDebugEnabled()) {
            LOG.debug("execute {}", fastdfsOperation);
        }

        fastdfsOperation.execute();
    } catch (Exception e) {
        promise.completeExceptionally(e);
    }
}
 
Example #24
Source File: SimpleChannelPool.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private void doHealthCheckOnRelease(final Channel channel, final Promise<Void> promise) throws Exception {
    final Future<Boolean> f = healthCheck.isHealthy(channel);
    if (f.isDone()) {
        releaseAndOfferIfHealthy(channel, promise, f);
    } else {
        f.addListener(new FutureListener<Boolean>() {
            @Override
            public void operationComplete(Future<Boolean> future) throws Exception {
                releaseAndOfferIfHealthy(channel, promise, f);
            }
        });
    }
}
 
Example #25
Source File: NettyAspect.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@OnBefore
public static @Nullable TraceEntry onBefore(final OptionalThreadContext context,
        @BindReceiver ChannelHandlerContext channelHandlerContext,
        @BindParameter @Nullable Object msg) {
    Channel channel = channelHandlerContext.channel();
    if (channel == null) {
        return null;
    }
    final ChannelMixin channelMixin = (ChannelMixin) channel;
    AuxThreadContext auxContext = channelMixin.glowroot$getAuxContext();
    if (auxContext != null) {
        return auxContext.start();
    }
    if (!(msg instanceof HttpRequestShim)) {
        return null;
    }
    HttpRequestShim request = (HttpRequestShim) msg;
    HttpMethodShim method = request.glowroot$getMethod();
    String methodName = method == null ? null : method.name();
    TraceEntry traceEntry =
            Util.startAsyncTransaction(context, methodName, request.getUri(), timerName);
    channelMixin.glowroot$setThreadContextToComplete(context);
    // IMPORTANT the close future gets called if client disconnects, but does not get called
    // when transaction ends and Keep-Alive is used (so still need to capture write
    // LastHttpContent below)
    channel.closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {
        @Override
        public void operationComplete(Future<? super Void> future) {
            endTransaction(channelMixin);
        }
    });
    if (!(msg instanceof LastHttpContentShim)) {
        channelMixin.glowroot$setAuxContext(context.createAuxThreadContext());
    }
    return traceEntry;
}
 
Example #26
Source File: SimpleApnsClientCache.java    From aerogear-unifiedpush-server with Apache License 2.0 5 votes vote down vote up
@Override
public void operationComplete(Future<? super Void> future) throws Exception {
    if (future.isSuccess()) {
        logger.debug("Successfully disconnected connection...");
    } else {
        final Throwable t = future.cause();
        logger.warn(t.getMessage(), t);
    }

}
 
Example #27
Source File: ProxyToServerConnection.java    From PowerTunnel with MIT License 5 votes vote down vote up
@Override
protected Future<?> execute() {
    DefaultSocks5PasswordAuthRequest authRequest = new DefaultSocks5PasswordAuthRequest(
            username != null ? username : "", password != null ? password : "");

    addFirstOrReplaceHandler(SOCKS_DECODER_NAME, new Socks5PasswordAuthResponseDecoder());
    return writeToChannel(authRequest);
}
 
Example #28
Source File: NettyIoSession.java    From termd with Apache License 2.0 5 votes vote down vote up
@Override
protected CloseFuture doCloseGracefully() {
  context.
      writeAndFlush(Unpooled.EMPTY_BUFFER).
      addListener(ChannelFutureListener.CLOSE).
      addListener(new GenericFutureListener<Future<? super Void>>() {
        @Override
        public void operationComplete(Future<? super Void> future) throws Exception {
          closeFuture.setClosed();
        }
      });
  return closeFuture;
}
 
Example #29
Source File: UdpTestClient.java    From dfactor with MIT License 5 votes vote down vote up
public static void main(String[] args) {
	final EventLoopGroup ioGroup = new NioEventLoopGroup(1);
	//start listen
			Bootstrap boot = new Bootstrap();
			boot.group(ioGroup)
				.option(ChannelOption.SO_BROADCAST, false)
				.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
				.option(ChannelOption.SO_SNDBUF, 1024*10)
				.option(ChannelOption.SO_RCVBUF, 1024*10)
				.channel(NioDatagramChannel.class)
				.handler(new UdpHandlerTestClient());
			try{
				ChannelFuture future = boot.bind(0).sync(); 
				channel = future.channel();
				future.addListener(new GenericFutureListener<Future<? super Void>>() {
					@Override
					public void operationComplete(Future<? super Void> f) throws Exception {
						boolean isDone = f.isDone();
						boolean isSucc = f.isSuccess();
						boolean isCancel = f.isCancelled();
						if(isDone && isSucc){  //listen
							log.I("Init udp succ");
						}else{
							//shutdown io group
							ioGroup.shutdownGracefully();
						}
					}
				});
			}catch(Throwable e){
				e.printStackTrace();
			}
			//start loop
			ExecutorService thPool = Executors.newFixedThreadPool(1);
			thPool.submit(new UdpTestClientLoop());
}
 
Example #30
Source File: NettyServerTransport.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public ListenableFuture<SocketStats> getStats() {
  final SettableFuture<SocketStats> result = SettableFuture.create();
  if (channel.eventLoop().inEventLoop()) {
    // This is necessary, otherwise we will block forever if we get the future from inside
    // the event loop.
    result.set(getStatsHelper(channel));
    return result;
  }
  channel.eventLoop().submit(
      new Runnable() {
        @Override
        public void run() {
          result.set(getStatsHelper(channel));
        }
      })
      .addListener(
          new GenericFutureListener<Future<Object>>() {
            @Override
            public void operationComplete(Future<Object> future) throws Exception {
              if (!future.isSuccess()) {
                result.setException(future.cause());
              }
            }
          });
  return result;
}