List of usage examples for io.netty.channel ChannelFutureListener ChannelFutureListener
ChannelFutureListener
From source file:org.asciidoctor.maven.http.AsciidoctorHttpServer.java
License:Apache License
public void start() { final AtomicInteger threadId = new AtomicInteger(1); workerGroup = new NioEventLoopGroup(THREAD_NUMBER, new ThreadFactory() { @Override/*from w w w .j a v a 2s.com*/ public Thread newThread(final Runnable r) { final Thread t = new Thread(r, THREAD_PREFIX + threadId.getAndIncrement()); if (t.getPriority() != Thread.NORM_PRIORITY) { t.setPriority(Thread.NORM_PRIORITY); } if (t.isDaemon()) { t.setDaemon(false); } return t; } }); try { bootstrap = new ServerBootstrap(); bootstrap.option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_SNDBUF, 1024) .option(ChannelOption.TCP_NODELAY, true).group(workerGroup) .channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(final SocketChannel ch) throws Exception { ch.pipeline().addLast("decoder", new HttpRequestDecoder()) .addLast("aggregator", new HttpObjectAggregator(Integer.MAX_VALUE)) .addLast("encoder", new HttpResponseEncoder()) .addLast("chunked-writer", new ChunkedWriteHandler()) .addLast("asciidoctor", new AsciidoctorHandler(workDir, defaultPage)); } }).bind(port).addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (!future.isSuccess()) { logger.error("Can't start HTTP server"); } else { logger.info(String.format("Server started on http://%s:%s", HOST, port)); } } }).sync(); } catch (final InterruptedException e) { logger.error(e.getMessage(), e); } }
From source file:org.asynchttpclient.netty.handler.NettyReactiveStreamsTest.java
License:Open Source License
@Test(groups = "standalone") public void testRetryingOnFailingStream() throws Exception { try (AsyncHttpClient client = asyncHttpClient()) { final CountDownLatch streamStarted = new CountDownLatch(1); // allows us to wait until subscriber has received the first body chunk final CountDownLatch streamOnHold = new CountDownLatch(1); // allows us to hold the subscriber from processing further body chunks final CountDownLatch replayingRequest = new CountDownLatch(1); // allows us to block until the request is being replayed ( this is what we want to test here!) // a ref to the publisher is needed to get a hold on the channel (if there is a better way, this should be changed) final AtomicReference<StreamedResponsePublisher> publisherRef = new AtomicReference<>(null); // executing the request client.preparePost(getTargetUrl()).setBody(LARGE_IMAGE_BYTES).execute(new ReplayedSimpleAsyncHandler( replayingRequest, new BlockedStreamSubscriber(streamStarted, streamOnHold)) { @Override//from www .j a v a 2 s .c o m public State onStream(Publisher<HttpResponseBodyPart> publisher) { if (!(publisher instanceof StreamedResponsePublisher)) { throw new IllegalStateException( String.format("publisher %s is expected to be an instance of %s", publisher, StreamedResponsePublisher.class)); } else if (!publisherRef.compareAndSet(null, (StreamedResponsePublisher) publisher)) { // abort on retry return State.ABORT; } return super.onStream(publisher); } }); // before proceeding, wait for the subscriber to receive at least one body chunk streamStarted.await(); // The stream has started, hence `StreamedAsyncHandler.onStream(publisher)` was called, and `publisherRef` was initialized with the `publisher` passed to `onStream` assertTrue(publisherRef.get() != null, "Expected a not null publisher."); // close the channel to emulate a connection crash while the response body chunks were being received. StreamedResponsePublisher publisher = publisherRef.get(); final CountDownLatch channelClosed = new CountDownLatch(1); getChannel(publisher).close().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { channelClosed.countDown(); } }); streamOnHold.countDown(); // the subscriber is set free to process new incoming body chunks. channelClosed.await(); // the channel is confirmed to be closed // now we expect a new connection to be created and AHC retry logic to kick-in automatically replayingRequest.await(); // wait until we are notified the request is being replayed // Change this if there is a better way of stating the test succeeded assertTrue(true); } }
From source file:org.atmosphere.nettosphere.BridgeRuntime.java
License:Apache License
private void handleWebSocketHandshake(final ChannelHandlerContext ctx, Object messageEvent) throws IOException, URISyntaxException { final HttpRequest request = (HttpRequest) messageEvent; // Allow only GET methods. if (request.getMethod() != GET) { sendHttpResponse(ctx, request, new DefaultHttpResponse(HTTP_1_1, FORBIDDEN)); return;/* ww w . ja v a 2s. c o m*/ } ctx.pipeline().addBefore(BridgeRuntime.class.getName(), "encoder", new HttpResponseEncoder()); WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( getWebSocketLocation(request), config.subProtocols(), false, maxWebSocketFrameSize); WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(request); if (handshaker == null) { wsFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { final NettyWebSocket webSocket = new NettyWebSocket(ctx.channel(), framework.getAtmosphereConfig(), config.noInternalAlloc(), config.binaryWrite()); final AtmosphereRequest atmosphereRequest = createAtmosphereRequest(ctx, request, EMPTY); if (!webSocketProcessor.handshake(atmosphereRequest)) { sendError(ctx, HttpResponseStatus.BAD_REQUEST, null); return; } webSocketProcessor.notifyListener(webSocket, new WebSocketEventListener.WebSocketEvent("", HANDSHAKE, webSocket)); handshaker.handshake(ctx.channel(), (FullHttpRequest) request).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { future.channel().close(); } else { websocketChannels.add(ctx.channel()); ctx.channel().attr(ATTACHMENT).set(webSocket); if (config.noInternalAlloc()) { webSocket.resource(proxiedResource); } AtmosphereResponse response = config.noInternalAlloc() ? proxiedResponse : AtmosphereResponseImpl.newInstance(framework.getAtmosphereConfig(), atmosphereRequest, webSocket); webSocketProcessor.open(webSocket, atmosphereRequest, response); if (webSocketTimeout > 0) { webSocket.closeFuture(suspendTimer.scheduleAtFixedRate(new Runnable() { @Override public void run() { if (webSocket.lastWriteTimeStampInMilliseconds() != 0 && (System.currentTimeMillis() - webSocket .lastWriteTimeStampInMilliseconds() > webSocketTimeout)) { logger.debug("Timing out {}", webSocket); webSocket.close(); } } }, webSocketTimeout, webSocketTimeout, TimeUnit.MILLISECONDS)); } } } }); } }
From source file:org.atmosphere.nettosphere.ChunkedWriter.java
License:Apache License
@Override public void close(final AtmosphereResponse response) throws IOException { if (!channel.isOpen() || doneProcessing.get()) return;// w ww . j av a 2 s. com ByteBuf writeBuffer = writeHeadersForHttp(response); if (writeBuffer.capacity() > 0 && response != null) { try { lock.writeLock().lock(); channel.writeAndFlush(writeBuffer).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { prepareForClose(response); } }); channel.flush(); } finally { lock.writeLock().unlock(); } } else { try { lock.writeLock().lock(); prepareForClose(response); } finally { lock.writeLock().unlock(); } } }
From source file:org.atmosphere.nettosphere.ChunkedWriter.java
License:Apache License
void _close(AtmosphereResponse response) throws UnsupportedEncodingException { if (!doneProcessing.getAndSet(true) && channel.isOpen()) { ByteBuf writeBuffer = writeHeaders(response); if (writeBuffer.capacity() != 0) { writeBuffer = Unpooled.wrappedBuffer(writeBuffer, END); } else {//from w w w . j ava 2s . co m writeBuffer = Unpooled.buffer(ENDCHUNK.length).writeBytes(ENDCHUNK); } channel.writeAndFlush(writeBuffer).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { logger.trace("Async Closing Done {}", channel); if (!keepAlive) { channel.close().awaitUninterruptibly(); } } }); } }
From source file:org.atmosphere.nettosphere.StreamWriter.java
License:Apache License
@Override public void close(AtmosphereResponse response) throws IOException { // Once we initiate the flush, we discard anything coming after for whatever reason. if (!doneProcessing.getAndSet(true) && channel.isOpen()) { logger.trace("About to flush to {} for {}", channel, response.uuid()); ByteBuf statusAndHeadersBuffer = writeHeader ? Unpooled.wrappedBuffer( constructStatusAndHeaders(response, chainedBodyBuffer.readableBytes()).getBytes("UTF-8")) : Unpooled.EMPTY_BUFFER; ByteBuf drain = Unpooled.wrappedBuffer(statusAndHeadersBuffer, chainedBodyBuffer); channel.writeAndFlush(drain).addListener(new ChannelFutureListener() { @Override// w w w.j a v a 2 s.com public void operationComplete(ChannelFuture channelFuture) throws Exception { chainedBodyBuffer = null; if (!keepAlive) { channel.close().awaitUninterruptibly(); } } }); } else { throw Utils.ioExceptionForChannel(channel, response.uuid()); } }
From source file:org.beaconmc.network.socket.handler.login.LoginHandler.java
License:Open Source License
@Override public void disconnect(ChatElement reason) { this.clientConnection.sendPacket(new PacketLoginOutDisconnect(reason)) .addListeners(new ChannelFutureListener() { @Override/*from ww w. j a v a 2s . c o m*/ public void operationComplete(ChannelFuture channelFuture) throws Exception { channelFuture.channel().close(); } }); }
From source file:org.beaconmc.network.socket.handler.play.PlayHandler.java
License:Open Source License
public void invokePing() { if (lastPingPacket != -1) { invokedPing = true;/* w w w.j a v a2s.c o m*/ return; } lastPingPacket = 0; invokedPing = false; this.clientConnection.sendPacket(new PacketPlayOutKeepAlive(MathUtils.getRandom().nextInt())) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { PlayHandler.this.lastPingPacket = System.currentTimeMillis(); } }); }
From source file:org.columbia.parikshan.duplicator.DuplicatorFrontendHandler.java
License:Apache License
@Override public void channelActive(ChannelHandlerContext ctx) { final Channel inboundChannel = ctx.channel(); // Start the connection attempt to SERVER 2 Bootstrap server2Bootstrap = new Bootstrap(); server2Bootstrap.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass()) .handler(new DuplicatorBackendHandler(inboundChannel)).option(ChannelOption.AUTO_READ, false); ChannelFuture server2Future = server2Bootstrap.connect(remoteHost, remotePort); server2OutboundChannel = server2Future.channel(); server2Future.addListener(new ChannelFutureListener() { @Override/*from w w w. java 2 s . c om*/ public void operationComplete(ChannelFuture future) { if (future.isSuccess()) { // connection complete start to read first data inboundChannel.read(); } else { // Close the connection if the connection attempt has failed. inboundChannel.close(); } } }); // Start the connection attempt to SERVER 3 Bootstrap server3Bootstrap = new Bootstrap(); server3Bootstrap.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass()) // You are only writing traffic to server 3 so you do not need to have a handler for the inbound traffic .handler(new DiscardServerHandler()) // EDIT .option(ChannelOption.AUTO_READ, false); ChannelFuture server3Future = server3Bootstrap.connect(remoteHost2, remotePort2); server3OutboundChannel = server3Future.channel(); //System.out.println("High Water Mark" + server3OutboundChannel.config().getWriteBufferHighWaterMark()); // Here we are going to add channels to channel group to save bytebuf work //channels.add(server2OutboundChannel); //channels.add(server3OutboundChannel); }
From source file:org.columbia.parikshan.duplicator.DuplicatorFrontendHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext ctx, Object buf) { // You need to reference count the message +1 ByteBuf msg = (ByteBuf) buf;/*from w w w.j ava2 s . com*/ msg.retain(); if (server2OutboundChannel.isActive()) { server2OutboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { if (future.isSuccess()) { // was able to flush out data, start to read the next chunk ctx.channel().read(); } else { future.channel().close(); } } }); } if (server3OutboundChannel.isActive()) { //if(server3OutboundChannel.isWritable()) { //System.out.println("Writing and Flushing"); server3OutboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { if (future.isSuccess()) { // was able to flush out data, start to read the next chunk //System.out.println(server3OutboundChannel.bytesBeforeUnwritable()); ctx.channel().read(); } else { future.channel().close(); } } }); //}else //System.out.println("Loop 1: Channel is no longer writeable"); } // Optional to the above code instead channel writing automatically cares for reference counting for you // channels.writeAndFlush(msg).addListeners(new ChannelFutureListener() { // // @Override // public void operationComplete(ChannelFuture future) throws Exception { // if (future.isSuccess()) { // // was able to flush out data, start to read the next chunk // ctx.channel().read(); // } else { // future.channel().close(); // } // } // }); }