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:com.mpush.common.message.ErrorMessage.java
License:Apache License
@Override public void close() { sendRaw(ChannelFutureListener.CLOSE); }
From source file:com.mpush.core.handler.AdminHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, String request) throws Exception { Command command = Command.help;/*from www. jav a2 s . c o m*/ String arg = null; String[] args = null; if (request != null) { String[] cmd_args = request.split(" "); command = Command.toCmd(cmd_args[0].trim()); if (cmd_args.length == 2) { arg = cmd_args[1]; } else if (cmd_args.length > 2) { args = Arrays.copyOfRange(cmd_args, 1, cmd_args.length); } } try { Object result = args != null ? command.handler(ctx, args) : command.handler(ctx, arg); ChannelFuture future = ctx.writeAndFlush(result + EOL + EOL); if (command == Command.quit) { future.addListener(ChannelFutureListener.CLOSE); } } catch (Throwable throwable) { ctx.writeAndFlush(throwable.getLocalizedMessage() + EOL + EOL); StringWriter writer = new StringWriter(1024); throwable.printStackTrace(new PrintWriter(writer)); ctx.writeAndFlush(writer.toString()); } LOGGER.info("receive admin command={}", request); }
From source file:com.mycompany.nettyweb.HttpServerHandler.java
private void sendResponse(ChannelHandlerContext ctx, HttpRequest request, HttpResponse httpResponse) { if (!isKeepAlive(request)) { ctx.write(httpResponse).addListener(ChannelFutureListener.CLOSE); } else {/* www. java 2 s . co m*/ httpResponse.headers().set(CONNECTION, KEEP_ALIVE); ctx.write(httpResponse); } }
From source file:com.netty.BaseHttpServerHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { FullHttpRequest request = (FullHttpRequest) msg; // HttpPostRequestDecoder httpPostRequestDecoder = new HttpPostRequestDecoder(request); if (HttpHeaders.is100ContinueExpected(request)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); }/*from w w w . jav a2s . com*/ boolean keepAlive = HttpHeaders.isKeepAlive(request); /////////////// FullHttpResponse response = handleRequest(request.getUri(), request.content().toString(CharsetUtil.UTF_8), request); //////////// // final FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT)); // response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); ctx.write(response); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, Values.KEEP_ALIVE); // ctx.executor().submit(new Runnable() { // @Override // public void run() { ctx.write(response); // } // }); } } }
From source file:com.netty.fileTest.http.download.HttpStaticFileServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.getDecoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);/*from ww w.j av a2s .co 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; } // Cache Validation String ifModifiedSince = request.headers().get(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(CONNECTION, HttpHeaders.Values.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.write(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() { @Override 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); } } @Override public void operationComplete(ChannelProgressiveFuture future) { System.err.println(future.channel() + " Transfer complete."); } }); // Decide whether to close the connection or not. if (!HttpHeaders.isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.netty.grpc.proxy.demo.handler.GrpcProxyFrontendHandler.java
License:Apache License
/** * Closes the specified channel after all queued write requests are flushed. *//* ww w. j a va 2 s .com*/ static void closeOnFlush(Channel ch) { if (ch.isActive()) { // System.out.println("----------------------------------------------"); ch.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } }
From source file:com.netty.telnet.impl.TelnetServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, String request) throws Exception { // Generate and write a response. String response;//w w w. j av a2s.c o m boolean close = false; if (StringUtil.isNullOrEmpty(request)) { response = "Please type something.\r\n"; } else if ("bye".equals(request.toLowerCase())) { response = "Have a good day!\r\n"; close = true; } else { response = "Did you say '" + request + "'?\r\n"; } // We do not need to write a ChannelBuffer here. // We know the encoder inserted at TelnetPipelineFactory will do the conversion. ChannelFuture future = ctx.write(response); // Close the connection after sending 'Have a good day!' // if the client has sent 'bye'. if (close) { future.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.netty4.http.helloword.HttpHelloWorldServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); }//from w w w . j a va2 s. c o m boolean keepAlive = HttpHeaders.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT)); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, Values.KEEP_ALIVE); ctx.write(response); } } if (msg instanceof HttpContent) { } }
From source file:com.nettyhttpserver.server.util.HttpRequestHandler.java
private static void writeToResponse(ChannelHandlerContext ctx, FullHttpResponse response, boolean keepAlive) { response.headers().set(CONTENT_TYPE, "text/html"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else {//from w w w .j a v a 2s .c om response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE + ":timeout=10"); ctx.write(response); } }
From source file:com.nextcont.ecm.fileengine.http.nettyServer.HttpUploadServerHandler.java
License:Apache License
private void doGet(ChannelHandlerContext ctx, HttpRequest httpRequest) throws URISyntaxException { String uri = new URI(request.getUri()).getPath(); if (uri.equals("/ping")) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT)); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }/* ww w . jav a 2 s . co m*/ }