List of usage examples for io.netty.channel ChannelFutureListener CLOSE
ChannelFutureListener CLOSE
To view the source code for io.netty.channel ChannelFutureListener CLOSE.
Click Source Link
From source file:io.termd.core.http.netty.HttpRequestHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (wsUri.equalsIgnoreCase(request.getUri())) { ctx.fireChannelRead(request.retain()); } else {//from www.j ava2s .c o m if (HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx); } HttpResponse response = new DefaultHttpResponse(request.getProtocolVersion(), HttpResponseStatus.INTERNAL_SERVER_ERROR); String path = request.getUri(); if ("/".equals(path)) { path = "/index.html"; } URL res = HttpTtyConnection.class.getResource("/io/termd/core/http" + path); try { if (res != null) { DefaultFullHttpResponse fullResp = new DefaultFullHttpResponse(request.getProtocolVersion(), HttpResponseStatus.OK); InputStream in = res.openStream(); byte[] tmp = new byte[256]; for (int l = 0; l != -1; l = in.read(tmp)) { fullResp.content().writeBytes(tmp, 0, l); } int li = path.lastIndexOf('.'); if (li != -1 && li != path.length() - 1) { String ext = path.substring(li + 1, path.length()); String contentType; switch (ext) { case "html": contentType = "text/html"; break; case "js": contentType = "application/javascript"; break; default: contentType = null; break; } if (contentType != null) { fullResp.headers().set(HttpHeaders.Names.CONTENT_TYPE, contentType); } } response = fullResp; } else { response.setStatus(HttpResponseStatus.NOT_FOUND); } } catch (Exception e) { e.printStackTrace(); } finally { ctx.write(response); ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); future.addListener(ChannelFutureListener.CLOSE); } } }
From source file:io.termd.core.ssh.netty.NettyIoSession.java
License:Apache License
@Override protected CloseFuture doCloseGracefully() { context.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE).addListener(fut -> { closeFuture.setClosed();//from ww w . j av a2 s.c o m }); return closeFuture; }
From source file:io.termd.core.telnet.netty.NettyTelnetConnection.java
License:Apache License
@Override public void close() { context.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); }
From source file:io.tetrapod.core.flashpolicy.FlashPolicyServerHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Boolean msg) throws Exception { assert msg == Boolean.TRUE; POLICY_FILE.retain();// w ww. j av a 2s . co m ctx.writeAndFlush(POLICY_FILE).addListener(ChannelFutureListener.CLOSE); }
From source file:io.urmia.proxy.HttpProxyFrontendHandler.java
License:Open Source License
private static void closeOnFlush(Channel ch) { if (ch.isActive()) { log.info("closeOnFlush active ch: {}", ch); ch.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } else {/* w w w .ja v a2 s . c o m*/ log.info("closeOnFlush inactive ch: {}", ch); ch.closeFuture(); } }
From source file:io.urmia.st.StorageServerHandler.java
License:Open Source License
private void listDirectory(ChannelHandlerContext ctx, File file) throws IOException { log.info("listDirectory: {}", file); File[] files = file.listFiles(); if (files == null) { ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); return;/*from w w w.j av a 2 s . co m*/ } List<String> jsons = new ArrayList<String>(files.length); for (File f : files) { log.debug("found: {}", f); jsons.add(toJson(f)); } String result = LINE_JOINER.join(jsons); log.info("writing back: {}", result); HttpResponseStatus status = HttpResponseStatus.OK; FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, Unpooled.copiedBuffer(result, CharsetUtil.UTF_8)); response.headers().set(CONTENT_TYPE, "application/x-json-stream; type=directory"); response.headers().set(CONTENT_LENGTH, result.length()); response.headers().set("result-set-size", files.length); // Write the end marker ChannelFuture lastContentFuture = ctx.writeAndFlush(response); // Decide whether to close the connection or not. if (!isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } access.success(ctx, "LIST", file.getAbsolutePath(), requestStartMS); }
From source file:io.urmia.st.StorageServerHandler.java
License:Open Source License
private void downloadFile(ChannelHandlerContext ctx, File file) throws IOException { final RandomAccessFile raf; try {/* w w w. j a v a 2 s . c om*/ raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException fnfe) { log.warn("no file at: {}", file.getPath()); access.fail(ctx, "GET", file.getAbsolutePath(), requestStartMS); sendError(ctx, NOT_FOUND); return; } final long fileLength = raf.length(); log.info("downloading file: {} of len: {}", file, fileLength); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); setContentLength(response, fileLength); setContentTypeHeader(response, file); //setDateAndCacheHeaders(response, file); if (isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } // Write the initial line and the header. ctx.write(response); final ChannelFuture sendFileFuture; sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise()); sendFileFuture.addListener(new ChannelProgressiveFutureListener() { @Override public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) { if (total < 0) { // total unknown System.err.println("Transfer progress: " + progress); } else { System.err.println("Transfer progress: " + progress + " / " + total); } } @Override public void operationComplete(ChannelProgressiveFuture future) throws Exception { System.err.println("Transfer complete."); } }); // Write the end marker ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); access.success(ctx, "GET", file.getAbsolutePath(), requestStartMS); // Decide whether to close the connection or not. if (!isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:io.urmia.st.StorageServerHandler.java
License:Open Source License
private void writeResponse(ChannelHandlerContext ctx, FullHttpResponse response, boolean forceClose) { // Decide whether to close the connection or not. boolean close = forceClose || HttpHeaders.Values.CLOSE.equalsIgnoreCase(request.headers().get(HttpHeaders.Names.CONNECTION)) || request.getProtocolVersion().equals(HttpVersion.HTTP_1_0) && !HttpHeaders.Values.KEEP_ALIVE .equalsIgnoreCase(request.headers().get(HttpHeaders.Names.CONNECTION)); log.debug("writeResponse close: {}, data: {}", close, response); ChannelFuture future = ctx.writeAndFlush(response); // Close the connection after the write operation is done if necessary. if (close) {/* w ww. jav a 2 s.com*/ future.addListener(ChannelFutureListener.CLOSE); } }
From source file:io.vertx.core.EventLoopGroupTest.java
License:Open Source License
@Test public void testNettyServerUsesContextEventLoop() throws Exception { ContextInternal context = (ContextInternal) vertx.getOrCreateContext(); AtomicReference<Thread> contextThread = new AtomicReference<>(); CountDownLatch latch = new CountDownLatch(1); context.runOnContext(v -> {/*from w w w . ja va 2s .c om*/ contextThread.set(Thread.currentThread()); latch.countDown(); }); awaitLatch(latch); ServerBootstrap bs = new ServerBootstrap(); bs.group(context.nettyEventLoop()); bs.channelFactory(((VertxInternal) vertx).transport().serverChannelFactory(false)); bs.option(ChannelOption.SO_BACKLOG, 100); bs.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { assertSame(contextThread.get(), Thread.currentThread()); context.executeFromIO(v -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Vertx.currentContext()); ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { assertSame(contextThread.get(), Thread.currentThread()); context.executeFromIO(v -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Vertx.currentContext()); }); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg; assertEquals("hello", buf.toString(StandardCharsets.UTF_8)); assertSame(contextThread.get(), Thread.currentThread()); context.executeFromIO(v -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Vertx.currentContext()); }); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { assertSame(contextThread.get(), Thread.currentThread()); context.executeFromIO(v -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Vertx.currentContext()); ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); }); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { assertSame(contextThread.get(), Thread.currentThread()); context.executeFromIO(v -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Vertx.currentContext()); testComplete(); }); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { fail(cause.getMessage()); } }); }); } }); ChannelFuture fut = bs.bind("localhost", 1234); try { fut.sync(); vertx.createNetClient(new NetClientOptions()).connect(1234, "localhost", ar -> { assertTrue(ar.succeeded()); NetSocket so = ar.result(); so.write(Buffer.buffer("hello")); }); await(); } finally { fut.channel().close().sync(); } }
From source file:io.vertx.core.http.impl.ClientHandler.java
License:Open Source License
@Override protected void doMessageReceived(ClientConnection conn, ChannelHandlerContext ctx, Object msg) { if (conn == null) { return;/*from ww w . j av a 2 s . co m*/ } if (msg instanceof HttpObject) { HttpObject obj = (HttpObject) msg; DecoderResult result = obj.decoderResult(); if (result.isFailure()) { // Close the connection as Netty's HttpResponseDecoder will not try further processing // see https://github.com/netty/netty/issues/3362 conn.handleException(result.cause()); conn.close(); return; } if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) obj; conn.handleResponse(response); return; } if (msg instanceof HttpContent) { HttpContent chunk = (HttpContent) obj; if (chunk.content().isReadable()) { Buffer buff = Buffer.buffer(chunk.content().slice()); conn.handleResponseChunk(buff); } if (chunk instanceof LastHttpContent) { conn.handleResponseEnd((LastHttpContent) chunk); } return; } } else if (msg instanceof WebSocketFrameInternal) { WebSocketFrameInternal frame = (WebSocketFrameInternal) msg; switch (frame.type()) { case BINARY: case CONTINUATION: case TEXT: conn.handleWsFrame(frame); break; case PING: // Echo back the content of the PING frame as PONG frame as specified in RFC 6455 Section 5.5.2 ctx.writeAndFlush(new WebSocketFrameImpl(FrameType.PONG, frame.getBinaryData())); break; case PONG: // Just ignore it break; case CLOSE: if (!closeFrameSent) { // Echo back close frame and close the connection once it was written. // This is specified in the WebSockets RFC 6455 Section 5.4.1 ctx.writeAndFlush(frame).addListener(ChannelFutureListener.CLOSE); closeFrameSent = true; } break; default: throw new IllegalStateException("Invalid type: " + frame.type()); } return; } throw new IllegalStateException("Invalid object " + msg); }