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.hydramq.network.server.ProtocolSelector.java
License:Open Source License
@Override public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception { ByteBuf buffer = (ByteBuf) msg;/*from ww w . j av a 2 s . co m*/ for (ProtocolHandler protocolHandler : protocols) { if (protocolHandler.accept(buffer)) { logger.info("Loading {} protocol handler", protocolHandler); ctx.pipeline().addLast("commandEncoder", new CommandEncoder(protocolHandler.getConversionContext())); ctx.pipeline().addLast("commandDecoder", new CommandDecoder(protocolHandler.getConversionContext())); ctx.pipeline().addLast("protocol", protocolHandler); ctx.pipeline().addLast("responseHandler", completableFutureHandler); ctx.pipeline().remove(this); ctx.pipeline().fireChannelActive(); ctx.fireChannelRead(msg); return; } } logger.error("No acceptable protocols found to handle client with protocol id of " + buffer.getInt(0)); ctx.writeAndFlush(new Error(buffer.getInt(1), 5)).addListener(ChannelFutureListener.CLOSE); }
From source file:io.jafka.http.HttpServerHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx);/*from ww w . j a v a 2s.c om*/ } body = new ByteArrayOutputStream(64); args = new HashMap<String, String>(4); // if (request.getMethod() != HttpMethod.POST) { sendStatusMessage(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED, "POST METHOD REQUIRED"); return; } HttpHeaders headers = request.headers(); String contentType = headers.get("Content-Type"); // ? text or octstream String key = headers.get("key"); key = key != null ? key : headers.get("request_key"); args.put("key", key); args.put("topic", headers.get("topic")); args.put("partition", headers.get("partition")); } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { //body.write(content.array()); content.readBytes(body, content.readableBytes()); //body.append(content.toString(CharsetUtil.UTF_8)); } if (msg instanceof LastHttpContent) { //process request if (server.handler != null) { server.handler.handle(args, body.toByteArray()); } if (!writeResponse(ctx)) { // If keep-alive is off, close the connection once the content is fully written. ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } body = null; args = null; } } }
From source file:io.jsync.http.impl.cgbystrom.FlashPolicyHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buffer = (ByteBuf) msg;//w w w . jav a 2 s. c o m int index = buffer.readerIndex(); switch (state) { case MAGIC1: if (!buffer.isReadable()) { return; } final int magic1 = buffer.getUnsignedByte(index++); state = ParseState.MAGIC2; if (magic1 != '<') { ctx.fireChannelRead(buffer); ctx.pipeline().remove(this); return; } // fall through case MAGIC2: if (!buffer.isReadable()) { return; } final int magic2 = buffer.getUnsignedByte(index); if (magic2 != 'p') { ctx.fireChannelRead(buffer); ctx.pipeline().remove(this); } else { ctx.writeAndFlush(Unpooled.copiedBuffer(XML, CharsetUtil.UTF_8)) .addListener(ChannelFutureListener.CLOSE); } } }
From source file:io.jsync.net.impl.DefaultNetSocket.java
License:Open Source License
@Override public void close() { if (writeFuture != null) { // Close after all data is written writeFuture.addListener(ChannelFutureListener.CLOSE); channel.flush();/*from w w w .j a v a 2s.c om*/ } else { super.close(); } }
From source file:io.maelstorm.server.RequestHandler.java
License:Open Source License
private void sendResponse(final ChannelHandlerContext ctx, final FullHttpResponse response, final HttpRequest request) { ReferenceCountUtil.release(request); if (!ctx.channel().isActive()) { return;/*from w ww .j a va 2 s . c o m*/ } final boolean keepalive = HttpHeaders.isKeepAlive(request); if (keepalive) { HttpHeaders.setContentLength(response, response.content().readableBytes()); response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } final ChannelFuture future = ctx.write(response); ctx.flush(); if (!keepalive) { future.addListener(ChannelFutureListener.CLOSE); } }
From source file:io.netty.example.http.cors.OkResponseHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, Object msg) { final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.EMPTY_BUFFER);//from w ww.java 2 s .c om response.headers().set("custom-response-header", "Some value"); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
From source file:io.netty.example.http.file.HttpStaticFileServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { this.request = request; if (!request.decoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);/*from w w w .j a va 2s . com*/ return; } if (!GET.equals(request.method())) { this.sendError(ctx, METHOD_NOT_ALLOWED); return; } final boolean keepAlive = HttpUtil.isKeepAlive(request); final String uri = request.uri(); final String path = sanitizeUri(uri); if (path == null) { this.sendError(ctx, FORBIDDEN); return; } File file = new File(path); if (file.isHidden() || !file.exists()) { this.sendError(ctx, NOT_FOUND); return; } if (file.isDirectory()) { if (uri.endsWith("/")) { this.sendListing(ctx, file, uri); } else { this.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) { this.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); HttpUtil.setContentLength(response, fileLength); setContentTypeHeader(response, file); setDateAndCacheHeaders(response, file); if (!keepAlive) { response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); } else if (request.protocolVersion().equals(HTTP_1_0)) { 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() { @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 (!keepAlive) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:io.netty.example.http.file.HttpStaticFileServerHandler.java
License:Apache License
/** * If Keep-Alive is disabled, attaches "Connection: close" header to the response * and closes the connection after the response being sent. *//*ww w .java 2 s.c o m*/ private void sendAndCleanupConnection(ChannelHandlerContext ctx, FullHttpResponse response) { final FullHttpRequest request = this.request; final boolean keepAlive = HttpUtil.isKeepAlive(request); HttpUtil.setContentLength(response, response.content().readableBytes()); if (!keepAlive) { // We're going to close the connection as soon as the response is sent, // so we should also make it clear for the client. response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); } else if (request.protocolVersion().equals(HTTP_1_0)) { response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } ChannelFuture flushPromise = ctx.writeAndFlush(response); if (!keepAlive) { // Close the connection as soon as the response is sent. flushPromise.addListener(ChannelFutureListener.CLOSE); } }
From source file:io.netty.example.http.helloworld.HttpHelloWorldServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; boolean keepAlive = HttpUtil.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(req.protocolVersion(), OK, Unpooled.wrappedBuffer(CONTENT)); response.headers().set(CONTENT_TYPE, TEXT_PLAIN).setInt(CONTENT_LENGTH, response.content().readableBytes()); if (keepAlive) { if (!req.protocolVersion().isKeepAliveDefault()) { response.headers().set(CONNECTION, KEEP_ALIVE); }//from w w w . j av a2 s . c om } else { // Tell the client we're going to close the connection. response.headers().set(CONNECTION, CLOSE); } ChannelFuture f = ctx.write(response); if (!keepAlive) { f.addListener(ChannelFutureListener.CLOSE); } } }
From source file:io.netty.example.http.upload.HttpUploadServerHandler.java
License:Apache License
private void writeResponse(Channel channel, boolean forceClose) { // Convert the response content to a ChannelBuffer. ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8); responseContent.setLength(0);//from w ww. j av a 2 s. co m // Decide whether to close the connection or not. boolean keepAlive = HttpUtil.isKeepAlive(request) && !forceClose; // Build the response object. FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes()); if (!keepAlive) { response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); } else if (request.protocolVersion().equals(HttpVersion.HTTP_1_0)) { response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } Set<Cookie> cookies; String value = request.headers().get(HttpHeaderNames.COOKIE); if (value == null) { cookies = Collections.emptySet(); } else { cookies = ServerCookieDecoder.STRICT.decode(value); } if (!cookies.isEmpty()) { // Reset the cookies if necessary. for (Cookie cookie : cookies) { response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie)); } } // Write the response. ChannelFuture future = channel.writeAndFlush(response); // Close the connection after the write operation is done if necessary. if (!keepAlive) { future.addListener(ChannelFutureListener.CLOSE); } }