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.dlc.server.DLCHttpServerHandler.java
private void writeResponse(ChannelHandlerContext ctx, String json) { buf.setLength(0);// w ww. ja v a 2s.c o m buf.append(json); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.copiedBuffer(buf, CharsetUtil.UTF_8)); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes()); response.headers().set(ACCESS_CONTROL_ALLOW_ORIGIN, "*"); ctx.write(response).addListener(ChannelFutureListener.CLOSE); }
From source file:com.dwarf.netty.guide.http.snoop.HttpSnoopServerHandler.java
License:Apache License
@Override protected void messageReceived(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (HttpHeaderUtil.is100ContinueExpected(request)) { send100Continue(ctx);/*w w w .ja v a 2 s . com*/ } buf.setLength(0); buf.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); buf.append("===================================\r\n"); buf.append("VERSION: ").append(request.protocolVersion()).append("\r\n"); buf.append("HOSTNAME: ").append(request.headers().get(HOST, "unknown")).append("\r\n"); buf.append("REQUEST_URI: ").append(request.uri()).append("\r\n\r\n"); HttpHeaders headers = request.headers(); if (!headers.isEmpty()) { for (Map.Entry<CharSequence, CharSequence> h : headers) { CharSequence key = h.getKey(); CharSequence value = h.getValue(); buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n"); } buf.append("\r\n"); } QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri()); Map<String, List<String>> params = queryStringDecoder.parameters(); if (!params.isEmpty()) { for (Entry<String, List<String>> p : params.entrySet()) { String key = p.getKey(); List<String> vals = p.getValue(); for (String val : vals) { buf.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n"); } } buf.append("\r\n"); } appendDecoderResult(buf, request); } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { buf.append("CONTENT: "); buf.append(content.toString(CharsetUtil.UTF_8)); buf.append("\r\n"); appendDecoderResult(buf, request); } if (msg instanceof LastHttpContent) { buf.append("END OF CONTENT\r\n"); LastHttpContent trailer = (LastHttpContent) msg; if (!trailer.trailingHeaders().isEmpty()) { buf.append("\r\n"); for (CharSequence name : trailer.trailingHeaders().names()) { for (CharSequence value : trailer.trailingHeaders().getAll(name)) { buf.append("TRAILING HEADER: "); buf.append(name).append(" = ").append(value).append("\r\n"); } } buf.append("\r\n"); } if (!writeResponse(trailer, ctx)) { // If keep-alive is off, close the connection once the content is fully written. ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } } }
From source file:com.e2e.management.HttpSocketHandler.java
License:Apache License
public void handleHttpFileRequest(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.getDecoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);/*from w ww .j a v a2 s.c o m*/ return; } if (request.getMethod() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return; } String uri = request.getUri(); if (uri == null) { sendError(ctx, FORBIDDEN); return; } if ((uri.equals("")) || (uri.equals("/"))) { uri = "/index.html"; } final String path = sanitizeUri(uri); 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, 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 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.earasoft.framework.http.WebSocketServerHandler.java
License:Apache License
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest request) { // Handle a bad request. if (!request.getDecoderResult().isSuccess()) { sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST)); return;//from w w w . ja v a 2s . c om } if (RouterHits.checkIfMappingExit(request)) { //Do Router Mapping First RouterHits.execute(ctx, request); return; } if ("/websocket".equals(request.getUri())) { // Handshake WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( getWebSocketLocation(request), null, true); handshaker = wsFactory.newHandshaker(request); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { handshaker.handshake(ctx.channel(), request); channels.add(ctx.channel()); } return; } final String uri = request.getUri(); //System.out.println("uri: " + uri); final String path = sanitizeUri("www", uri); //System.out.println("path: " + path); if (path == null) { sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.FORBIDDEN)); return; } File file = new File(path); if (file.isHidden() || !file.exists()) { sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.NOT_FOUND)); return; } if (file.isDirectory()) { if (uri.endsWith("/")) { File checkIndexFile = new File(file.getAbsolutePath() + File.separator + "index.html"); System.out.println(checkIndexFile.exists()); if (checkIndexFile.exists()) { file = checkIndexFile; } else { sendListing(ctx, file); return; } } else { sendRedirect(ctx, uri + '/'); } } if (!file.isFile()) { sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.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 = null; try { ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 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) { sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.NOT_FOUND)); return; } long fileLength = 0; try { fileLength = raf.length(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } 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 = null; 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 { try { sendFileFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 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); } // // Send the demo page and favicon.ico // if ("/".equals(req.getUri()) && req.getMethod() == GET) { // ByteBuf content = WebSocketServerIndexPage.getContent(getWebSocketLocation(req)); // FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content); // // res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8"); // HttpHeaders.setContentLength(res, content.readableBytes()); // // sendHttpResponse(ctx, req, res); // return; // } // // if ("/favicon.ico".equals(req.getUri())) { // FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND); // sendHttpResponse(ctx, req, res); // return; // } sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.FORBIDDEN)); return; }
From source file:com.easy.remoting.netty.handler.EasyDecoder.java
License:Apache License
@Override public Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception { ByteBuf frame = null;//ww w .ja va2 s.c o m try { frame = (ByteBuf) super.decode(ctx, in); if (null == frame) { return null; } ByteBuffer byteBuffer = frame.nioBuffer(); return Cmd.decode(byteBuffer); } catch (Exception e) { log.error("decode exception:{}", e); ctx.channel().close().addListener(ChannelFutureListener.CLOSE); } finally { if (null != frame) { frame.release(); } } return null; }
From source file:com.easy.remoting.netty.handler.EasyEncoder.java
License:Apache License
@Override public void encode(ChannelHandlerContext ctx, Cmd cmd, ByteBuf out) throws Exception { try {/*ww w. j av a 2 s. c om*/ ByteBuffer cmdBytes = cmd.encode(); out.writeBytes(cmdBytes); } catch (Exception e) { log.error("encode exception: {}", e); ctx.channel().close().addListener(ChannelFutureListener.CLOSE); } }
From source file:com.ebay.jetstream.http.netty.server.AbstractHttpRequest.java
License:MIT License
protected void postResponse(Channel channel, HttpRequest request, HttpResponse response) { boolean keepAlive = HttpHeaders.isKeepAlive(request); String reqid = request.headers().get("X_EBAY_REQ_ID"); if (reqid != null && !reqid.isEmpty()) // if request contains // X_EBAY_REQ_ID we will echo it // back HttpHeaders.setHeader(response, "X_EBAY_REQ_ID", reqid); // we will echo back cookies for now in the response. Our request ID is // set as a cookie String contentLenHeader = response.headers().get(HttpHeaders.Names.CONTENT_LENGTH); if (contentLenHeader == null) HttpHeaders.setContentLength(response, 0); // Write the response. ChannelFuture future = channel.writeAndFlush(response); // Close the non-keep-alive connection after the write operation is // done.//from ww w. j ava2 s. c o m if (!keepAlive) { future.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.ebay.jetstream.http.netty.server.KeepAliveHandler.java
License:MIT License
private void closeConnection(Object msg, ChannelPromise promise) { if (msg instanceof HttpResponse) { HttpHeaders.setHeader((HttpResponse) msg, HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); }/*from ww w . j av a 2 s . co m*/ promise.addListener(ChannelFutureListener.CLOSE); }
From source file:com.elephant.framework.network.telnet.netty.TelnetServerHandler.java
License:Apache License
@Override public void messageReceived(ChannelHandlerContext ctx, String request) throws Exception { //String msgId = request.substring(0, endIndex) // Generate and write a response. String response;/*w w w . j a v a 2 s.c om*/ boolean close = false; if (request.isEmpty()) { 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.example.grpc.server.PrometheusServer.java
License:Apache License
public void start() { final ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() { @Override// ww w. j a va 2 s. c o m protected void initChannel(SocketChannel socketChannel) throws Exception { ChannelPipeline pipeline = socketChannel.pipeline(); pipeline.addLast("decoder", new HttpRequestDecoder()); pipeline.addLast("encoder", new HttpResponseEncoder()); pipeline.addLast("prometheus", new SimpleChannelInboundHandler<Object>() { @Override protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception { if (!(o instanceof HttpRequest)) { return; } HttpRequest request = (HttpRequest) o; if (!"/metrics".equals(request.uri())) { final FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND); channelHandlerContext.writeAndFlush(response) .addListener(ChannelFutureListener.CLOSE); return; } if (!HttpMethod.GET.equals(request.method())) { final FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_ACCEPTABLE); channelHandlerContext.writeAndFlush(response) .addListener(ChannelFutureListener.CLOSE); return; } ByteBuf buf = Unpooled.buffer(); ByteBufOutputStream os = new ByteBufOutputStream(buf); OutputStreamWriter writer = new OutputStreamWriter(os); TextFormat.write004(writer, registry.metricFamilySamples()); writer.close(); os.close(); final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf); response.headers().set(HttpHeaderNames.CONTENT_TYPE, TextFormat.CONTENT_TYPE_004); channelHandlerContext.writeAndFlush(response) .addListener(ChannelFutureListener.CLOSE); } }); } }); try { this.channel = bootstrap.bind(this.port).sync().channel(); } catch (InterruptedException e) { // do nothing } }