List of usage examples for io.netty.channel ChannelFuture addListener
@Override ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener);
From source file:Netty4.book.http.file.HttpStaticFileServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.decoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);// w w w . j ava2 s. c om return; } if (request.method() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return; } final String uri = request.uri(); final String path = sanitizeUri(uri); if (path == null) { sendError(ctx, FORBIDDEN); return; } File file = new File(path); if (file.isHidden() || !file.exists()) { sendError(ctx, NOT_FOUND); return; } if (file.isDirectory()) { if (uri.endsWith("/")) { sendListing(ctx, file); } else { sendRedirect(ctx, uri + '/'); } return; } if (!file.isFile()) { sendError(ctx, FORBIDDEN); return; } // Cache Validation String ifModifiedSince = request.headers().get(HttpHeaderNames.IF_MODIFIED_SINCE); if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince); // Only compare up to the second because the datetime format we send to the client // does not have milliseconds long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000; long fileLastModifiedSeconds = file.lastModified() / 1000; if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) { sendNotModified(ctx); return; } } RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException ignore) { sendError(ctx, NOT_FOUND); return; } long fileLength = raf.length(); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); HttpHeaders.setContentLength(response, fileLength); setContentTypeHeader(response, file); setDateAndCacheHeaders(response, file); if (HttpHeaders.isKeepAlive(request)) { response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } // Write the initial line and the header. ctx.write(response); // Write the content. ChannelFuture sendFileFuture; ChannelFuture lastContentFuture; if (ctx.pipeline().get(SslHandler.class) == null) { sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise()); // Write the end marker. lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } else { sendFileFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise()); // HttpChunkedInput will write the end marker (LastHttpContent) for us. lastContentFuture = sendFileFuture; } sendFileFuture.addListener(new ChannelProgressiveFutureListener() { public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) { if (total < 0) { // total unknown System.err.println(future.channel() + " Transfer progress: " + progress); } else { System.err.println(future.channel() + " Transfer progress: " + progress + " / " + total); } } public void operationComplete(ChannelProgressiveFuture future) throws Exception { System.err.println(future.channel() + " Transfer complete."); } } ); // Decide whether to close the connection or not. if (!HttpUtil.isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:netty4.protocol.http.HttpFileServerHandler.java
License:Apache License
@Override protected void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest request) throws Exception { System.out.println("channelRead thread: " + Thread.currentThread()); TaskRunner.getInstance().submitTask(new Runnable() { @Override/* www .j a v a 2s. co m*/ public void run() { try { if (!request.getDecoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST); return; } if (request.getMethod() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return; } final String uri = request.getUri(); final String path = sanitizeUri(uri); if (path == null) { sendError(ctx, FORBIDDEN); return; } File file = new File(path); if (file.isHidden() || !file.exists()) { sendError(ctx, NOT_FOUND); return; } if (file.isDirectory()) { if (uri.endsWith("/")) { sendListing(ctx, file); } else { sendRedirect(ctx, uri + '/'); } return; } if (!file.isFile()) { sendError(ctx, FORBIDDEN); return; } RandomAccessFile randomAccessFile = null; try { randomAccessFile = new RandomAccessFile(file, "r");// ?? } catch (FileNotFoundException fnfe) { sendError(ctx, NOT_FOUND); return; } long fileLength; fileLength = randomAccessFile.length(); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); setContentLength(response, fileLength); setContentTypeHeader(response, file); if (isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } System.out.println("TaskRunner thread: " + Thread.currentThread()); ctx.write(response); ChannelFuture sendFileFuture; sendFileFuture = ctx.write(new ChunkedFile(randomAccessFile, 0, fileLength, 8192), 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.out.println("Transfer complete."); } }); ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); if (!isKeepAlive(request)) { lastContentFuture.addListener(ChannelFutureListener.CLOSE); } } catch (IOException e) { e.printStackTrace(); } } }); }
From source file:NettyDefinitiveGuide.ch10.ch10_1.HttpFileServerHandler2.java
License:Apache License
@Override public void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.getDecoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);// w w w . j a v a 2 s .c om return; } if (request.getMethod() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return; } final String uri = request.getUri(); final String path = sanitizeUri(uri); if (path == null) { sendError(ctx, FORBIDDEN); return; } File file = new File(path); if (file.isHidden() || !file.exists()) { sendError(ctx, NOT_FOUND); return; } if (file.isDirectory()) { if (uri.endsWith("/")) { sendListing(ctx, file); } else { sendRedirect(ctx, uri + '/'); } return; } if (!file.isFile()) { sendError(ctx, FORBIDDEN); return; } RandomAccessFile randomAccessFile = null; try { randomAccessFile = new RandomAccessFile(file, "r");// ?? } catch (FileNotFoundException fnfe) { sendError(ctx, NOT_FOUND); return; } long fileLength = randomAccessFile.length(); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); setContentLength(response, fileLength); setContentTypeHeader(response, file); if (isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } ctx.write(response); ChannelFuture sendFileFuture; sendFileFuture = ctx.write(new ChunkedFile(randomAccessFile, 0, fileLength, 8192), 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.out.println("Transfer complete."); } }); ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); }
From source file:nettyhttpfileserverdemo.HttpFileServerHandler.java
@Override protected void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.getDecoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);/*from w w w.j ava 2 s .c o m*/ return; } if (request.getMethod() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return; } final String uri = request.getUri(); final String path = sanitizeUri(uri); if (path == null) { sendError(ctx, FORBIDDEN); return; } File file = new File(path); if (file.isHidden() || !file.exists()) { sendError(ctx, NOT_FOUND); return; } if (file.isDirectory()) { if (uri.endsWith("/")) { sendListing(ctx, file); } else { sendRedirect(ctx, uri + '/'); } return; } if (!file.isFile()) { sendError(ctx, FORBIDDEN); return; } RandomAccessFile randomAccessFile = null; try { randomAccessFile = new RandomAccessFile(file, "r"); } catch (FileNotFoundException fnfe) { sendError(ctx, NOT_FOUND); } //try-catch long fileLength = randomAccessFile.length(); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); setContentLength(response, fileLength); setContentTypeHeader(response, file); if (isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } ctx.write(response); ChannelFuture sendFileFuture = ctx.write(new ChunkedFile(randomAccessFile, 0, fileLength, 8192), ctx.newProgressivePromise()); sendFileFuture.addListener(new ChannelProgressiveFutureListener() { @Override public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) throws Exception { if (total < 0) { System.err.println("Transfer progress: " + progress); } else { System.err.println("Transfer progress: " + progress + "/" + total); } } //operationProgressed() @Override public void operationComplete(ChannelProgressiveFuture future) throws Exception { System.out.println("Transfer Complete"); } //operationComplete() }); ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); if (!isKeepAlive(request)) { lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:netty_client.TimeClientHandler.java
@Override public void channelActive(final ChannelHandlerContext ctx) { // (1) final ByteBuf time = ctx.alloc().buffer(4); // (2) time.writeInt((int) (System.currentTimeMillis() / 1000L + 2208988800L)); final ChannelFuture f = ctx.writeAndFlush(time); // (3) f.addListener(new ChannelFutureListener() { @Override/*from ww w. j av a2 s . c om*/ public void operationComplete(ChannelFuture future) { assert f == future; ctx.close(); } }); // (4) }
From source file:nikoladasm.aspark.ResponseImpl.java
License:Open Source License
private ChannelFuture writeObjectToChannel(Object object) { ChannelFuture lastContentFuture = ctx.channel().writeAndFlush(object); if (!keepAlive || HTTP_1_0.equals(version)) lastContentFuture.addListener(ChannelFutureListener.CLOSE); return lastContentFuture; }
From source file:nikoladasm.aspark.server.ServerHandler.java
License:Open Source License
private void sendResponse(ChannelHandlerContext ctx, HttpVersion version, HttpResponseStatus status, boolean keepAlive, String body) { FullHttpResponse response = new DefaultFullHttpResponse((version == null) ? HTTP_1_1 : version, status, Unpooled.copiedBuffer((body == null) ? "" : body, CharsetUtil.UTF_8)); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); if (keepAlive) response.headers().set(CONNECTION, KEEP_ALIVE); ChannelFuture lastContentFuture = ctx.channel().writeAndFlush(response); if (!keepAlive || HTTP_1_0.equals(version)) lastContentFuture.addListener(ChannelFutureListener.CLOSE); }
From source file:nikoladasm.aspark.server.ServerHandler.java
License:Open Source License
private boolean WebSocketHandshake(HttpMethod method, String path, FullHttpRequest req, ChannelHandlerContext ctx) {/*from w w w . j a v a 2 s. co m*/ if (method.equals(GET)) { final WebSocketHandler wsHandler = webSockets.handler(path); if (wsHandler == null) return false; Channel channel = ctx.channel(); final WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( getWebSocketLocation(channel.pipeline(), req, path), null, true); final WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(channel); } else { final ChannelFuture handshakeFuture = handshaker.handshake(channel, req); handshakeFuture.addListener((future) -> { if (!future.isSuccess()) { ctx.fireExceptionCaught(future.cause()); } else { channel.attr(WEBSOCKET_HANDLER_ATTR_KEY).set(wsHandler); channel.attr(HANDSHAKER_ATTR_KEY).set(handshaker); WebSocketContextImpl wsContext = new WebSocketContextImpl(channel); channel.attr(WEBSOCKET_CONTEXT_ATTR_KEY).set(wsContext); wsHandler.onConnect(wsContext); } }); } return true; } return false; }
From source file:object.client.ext.ObjectClient.java
private Channel connect() { try {/*from w w w .j a va2s. co m*/ //System.out.println("[connectioState] " + connectioState.name()); //System.out.println("Try to Connect on : " + remotehost + ":" + port); CompletableFuture<Channel> futureResult = new CompletableFuture<>(); ChannelFuture future = bootstrap.connect(remotehost, port); future.addListener((ChannelFutureListener) (ChannelFuture future1) -> { if (future1.isSuccess()) { futureResult.complete(future1.channel()); } else { futureResult.completeExceptionally(new TryConnectException(remotehost, port)); } }); future.awaitUninterruptibly(); return futureResult.join(); } catch (Exception ex) { return null; } }