List of usage examples for io.netty.channel ChannelFuture addListener
@Override ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener);
From source file:io.vertx.core.net.impl.AsyncResolveBindConnectHelper.java
License:Open Source License
private static AsyncResolveBindConnectHelper doBindConnect(VertxInternal vertx, int port, String host, Function<InetSocketAddress, ChannelFuture> cfProducer) { checkPort(port);/*from ww w . j a v a2 s . c o m*/ AsyncResolveBindConnectHelper asyncResolveBindConnectHelper = new AsyncResolveBindConnectHelper(); vertx.resolveHostname(host, res -> { if (res.succeeded()) { // At this point the name is an IP address so there will be no resolve hit InetSocketAddress t = new InetSocketAddress(res.result(), port); ChannelFuture future = cfProducer.apply(t); future.addListener(f -> { if (f.isSuccess()) { asyncResolveBindConnectHelper.handle(future, Future.succeededFuture(future.channel())); } else { asyncResolveBindConnectHelper.handle(future, Future.failedFuture(f.cause())); } }); } else { asyncResolveBindConnectHelper.handle(null, Future.failedFuture(res.cause())); } }); return asyncResolveBindConnectHelper; }
From source file:io.vertx.core.net.impl.AsyncResolveConnectHelper.java
License:Open Source License
public static AsyncResolveConnectHelper doBind(VertxInternal vertx, int port, String host, ServerBootstrap bootstrap) {//from w w w . j a v a 2 s . co m checkPort(port); AsyncResolveConnectHelper asyncResolveConnectHelper = new AsyncResolveConnectHelper(); vertx.resolveAddress(host, res -> { if (res.succeeded()) { // At this point the name is an IP address so there will be no resolve hit InetSocketAddress t = new InetSocketAddress(res.result(), port); ChannelFuture future = bootstrap.bind(t); future.addListener(f -> { if (f.isSuccess()) { asyncResolveConnectHelper.handle(future, Future.succeededFuture(future.channel())); } else { asyncResolveConnectHelper.handle(future, Future.failedFuture(f.cause())); } }); } else { asyncResolveConnectHelper.handle(null, Future.failedFuture(res.cause())); } }); return asyncResolveConnectHelper; }
From source file:io.vertx.test.core.HostnameResolutionTest.java
License:Open Source License
@Test public void testAsyncResolveConnectIsNotifiedOnChannelEventLoop() throws Exception { CountDownLatch listenLatch = new CountDownLatch(1); NetServer s = vertx.createNetServer().connectHandler(so -> { });/*from ww w . j av a2 s. c o m*/ s.listen(1234, "localhost", onSuccess(v -> listenLatch.countDown())); awaitLatch(listenLatch); AtomicReference<Thread> channelThread = new AtomicReference<>(); CountDownLatch connectLatch = new CountDownLatch(1); Bootstrap bootstrap = new Bootstrap(); bootstrap.channel(NioSocketChannel.class); bootstrap.group(vertx.nettyEventLoopGroup()); bootstrap.resolver(((VertxInternal) vertx).nettyAddressResolverGroup()); bootstrap.handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { channelThread.set(Thread.currentThread()); connectLatch.countDown(); } }); ChannelFuture channelFut = bootstrap.connect("localhost", 1234); awaitLatch(connectLatch); channelFut.addListener(v -> { assertTrue(v.isSuccess()); assertEquals(channelThread.get(), Thread.currentThread()); testComplete(); }); await(); }
From source file:io.viewserver.network.netty.NettyNetworkAdapter.java
License:Apache License
@Override public ListenableFuture<IChannel> connect(IEndpoint endpoint) { SettableFuture<IChannel> promise = SettableFuture.create(); final INettyEndpoint.IClient client = ((INettyEndpoint) endpoint).getClient(getClientWorkerGroup(), new NettyPipelineInitialiser(networkMessageWheel)); ChannelFuture channelFuture = client.connect(); channelFuture.addListener(new ChannelFutureListener() { @Override// ww w .j av a2 s. c o m public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { NettyChannel channel = new NettyChannel(future.channel()); promise.set(channel); } else { promise.setException(future.cause()); } } }); return promise; }
From source file:io.viewserver.network.netty.websocket.WebSocketServerHandler.java
License:Apache License
private void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { if (res.getStatus().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf);/* w ww .ja v a 2 s. c o m*/ buf.release(); HttpHeaders.setContentLength(res, res.content().readableBytes()); } ChannelFuture channelFuture = ctx.channel().writeAndFlush(res); if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) { channelFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:io.werval.server.netty.WervalHttpHandler.java
License:Apache License
private ChannelFuture writeOutcome(ChannelHandlerContext nettyContext, Outcome outcome) { // == Build the Netty Response ResponseHeader responseHeader = outcome.responseHeader(); // Netty Version & Status HttpVersion responseVersion = HttpVersion.valueOf(responseHeader.version().toString()); HttpResponseStatus responseStatus = HttpResponseStatus.valueOf(responseHeader.status().code()); // Netty Headers & Body output final HttpResponse nettyResponse; final ChannelFuture writeFuture; if (outcome instanceof ChunkedInputOutcome) { ChunkedInputOutcome chunkedOutcome = (ChunkedInputOutcome) outcome; nettyResponse = new DefaultHttpResponse(responseVersion, responseStatus); // Headers applyResponseHeader(responseHeader, nettyResponse); nettyResponse.headers().set(TRANSFER_ENCODING, CHUNKED); nettyResponse.headers().set(TRAILER, X_WERVAL_CONTENT_LENGTH); // Body/* ww w . j ava2 s.co m*/ nettyContext.write(nettyResponse); writeFuture = nettyContext.writeAndFlush(new HttpChunkedBodyEncoder( new ChunkedStream(chunkedOutcome.inputStream(), chunkedOutcome.chunkSize()))); } else if (outcome instanceof InputStreamOutcome) { InputStreamOutcome streamOutcome = (InputStreamOutcome) outcome; nettyResponse = new DefaultFullHttpResponse(responseVersion, responseStatus); // Headers applyResponseHeader(responseHeader, nettyResponse); nettyResponse.headers().set(CONTENT_LENGTH, streamOutcome.contentLength()); // Body try (InputStream bodyInputStream = streamOutcome.bodyInputStream()) { ((ByteBufHolder) nettyResponse).content().writeBytes(bodyInputStream, new BigDecimal(streamOutcome.contentLength()).intValueExact()); } catch (IOException ex) { throw new UncheckedIOException(ex); } writeFuture = nettyContext.writeAndFlush(nettyResponse); } else if (outcome instanceof SimpleOutcome) { SimpleOutcome simpleOutcome = (SimpleOutcome) outcome; byte[] body = simpleOutcome.body().asBytes(); nettyResponse = new DefaultFullHttpResponse(responseVersion, responseStatus); // Headers applyResponseHeader(responseHeader, nettyResponse); nettyResponse.headers().set(CONTENT_LENGTH, body.length); // Body ((ByteBufHolder) nettyResponse).content().writeBytes(body); writeFuture = nettyContext.writeAndFlush(nettyResponse); } else { LOG.warn("{} Unhandled Outcome type '{}', no response body.", requestIdentity, outcome.getClass()); nettyResponse = new DefaultFullHttpResponse(responseVersion, responseStatus); applyResponseHeader(responseHeader, nettyResponse); writeFuture = nettyContext.writeAndFlush(nettyResponse); } if (LOG.isTraceEnabled()) { LOG.trace("{} Sent a HttpResponse:\n{}", requestIdentity, nettyResponse.toString()); } // Close the connection as soon as the response is sent if not keep alive if (!outcome.responseHeader().isKeepAlive() || nettyContext.executor().isShuttingDown()) { writeFuture.addListener(ChannelFutureListener.CLOSE); } // Done! return writeFuture; }
From source file:it.jnrpe.JNRPE.java
License:Apache License
/** * Starts a new thread that listen for requests. The method is <b>not * blocking</b>/*from w ww . jav a2 s . c om*/ * * @param address * The address to bind to * @param port * The listening port * @param useSSL * <code>true</code> if an SSL socket must be created. * @throws UnknownHostException * - */ public void listen(final String address, final int port, final boolean useSSL) throws UnknownHostException { // Bind and start to accept incoming connections. ChannelFuture cf = getServerBootstrap(useSSL).bind(address, port); cf.addListener(new ChannelFutureListener() { public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { context.getEventBus().post(new JNRPEStatusEvent(STATUS.STARTED, this, "JNRPE Server started")); LOG.info(context, "Listening on " + (useSSL ? "SSL/" : "") + address + ":" + port); } else { getExecutionContext().getEventBus() .post(new JNRPEStatusEvent(STATUS.FAILED, this, "JNRPE Server start failed")); LOG.error(context, "Unable to listen on " + (useSSL ? "SSL/" : "") + address + ":" + port, future.cause()); } } }); }
From source file:it.jnrpe.net.JNRPEServerHandler.java
License:Apache License
/** * Method channelRead.// ww w. j a v a 2 s. c o m * @param ctx ChannelHandlerContext * @param msg Object * @see io.netty.channel.ChannelInboundHandler#channelRead(ChannelHandlerContext, Object) */ @Override public final void channelRead(final ChannelHandlerContext ctx, final Object msg) { try { JNRPERequest req = (JNRPERequest) msg; ReturnValue ret = commandInvoker.invoke(req.getCommand(), req.getArguments()); JNRPEResponse res = new JNRPEResponse(); res.setPacketVersion(PacketVersion.VERSION_2); res.setResultCode(ret.getStatus().intValue()); res.setMessage(ret.getMessage()); ChannelFuture channelFuture = ctx.writeAndFlush(res); channelFuture.addListener(ChannelFutureListener.CLOSE); } finally { ReferenceCountUtil.release(msg); } }
From source file:jj.http.server.HttpServerResponseImpl.java
License:Apache License
private ChannelFuture maybeClose(final ChannelFuture f) { if (!HttpHeaders.isKeepAlive(request.request())) { f.addListener(ChannelFutureListener.CLOSE); }/*from w w w .ja v a2s . c o m*/ publisher.publish(new RequestResponded(request, this)); return f; }
From source file:lunarion.node.requester.LunarDBClient.java
License:Open Source License
public ChannelFuture connect(String host, int port) throws Exception { group = new NioEventLoopGroup(); client_handler = new ClientHandler(internal); try {// w w w .j a v a 2 s. co m Bootstrap client_bootstrap = new Bootstrap(); client_bootstrap.group(group).channel(NioSocketChannel.class) .option(ChannelOption.SO_SNDBUF, 1024 * 1024) .option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(64, 1024, 65536 * 512)) //.option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.SO_KEEPALIVE, true).handler(new ClientChannelInitializer(client_handler)); //ChannelFuture cf = client_bootstrap.connect(host, port).sync(); ChannelFuture cf = client_bootstrap.connect(host, port); channel_list.add(cf); cf.addListener(new ChannelFutureListener() { public void operationComplete(final ChannelFuture channelFuture) throws Exception { if (channelFuture.isSuccess()) { ClientHandler handler = channelFuture.channel().pipeline().get(ClientHandler.class); client_handler = handler; } } }); connected.set(true); connected_host_ip = host; connected_port = port; return cf; } finally { // group.shutdownGracefully(); } }