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:madtest.common.netty.study.chapter11.WebSocketServerHandler.java
License:Apache License
private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // //from w w w . ja v a 2s.c om if (res.status().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf); buf.release(); HttpHeaderUtil.setContentLength(res, res.content().readableBytes()); } // ?Keep-Alive ChannelFuture f = ctx.channel().writeAndFlush(res); if (!HttpHeaderUtil.isKeepAlive(req) || res.status().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
From source file:malcolm.HttpProxyBackendHandler.java
License:Apache License
private static void closeOnFlush(final Channel ch) { if (ch.isActive()) { ch.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); }//from www .j a v a2 s . c o m }
From source file:md.mgmt.facade.IndexServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { logger.info(String.valueOf(msg)); long start = System.currentTimeMillis(); String respStr = commandMapper.selectService((String) msg); long end = System.currentTimeMillis(); logger.info("resp:" + respStr); logger.info("time spend: " + (end - start)); ChannelFuture f = ctx.writeAndFlush(respStr); f.addListener(ChannelFutureListener.CLOSE); }
From source file:me.ferrybig.javacoding.webmapper.netty.WebServerHandler.java
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return;/* w w w. ja va 2s . c om*/ } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (!(frame instanceof TextWebSocketFrame)) { throw new UnsupportedOperationException( String.format("%s frame types not supported", frame.getClass().getName())); } String request = ((TextWebSocketFrame) frame).text(); JSONObject json; try { json = new JSONObject(request); } catch (JSONException ex) { ctx.channel().writeAndFlush(new TextWebSocketFrame("{\"error\":\"BAD_JSON\"}")) .addListener(ChannelFutureListener.CLOSE); return; } String endpoint = json.optString("endpoint", null); if (endpoint == null) { ctx.channel().writeAndFlush(new TextWebSocketFrame("{\"error\":\"MISSING_ENDPOINT\"}")); return; } String reqid = json.optString("reqid", json.optInt("reqid", 0) + ""); boolean containedReqId = json.has("reqid"); websocketTmp.endpoint(endpoint).setDataOrClear(json.optJSONObject("data")); EndpointResult<?> res; try { res = this.httpMapper.handleHttpRequest(websocketTmp); } catch (RouteException ex) { res = new EndpointResult<>(Result.SERVER_ERROR, "Server error!", ContentType.TEXT); Logger.getLogger(WebServerHandler.class.getName()).log(Level.SEVERE, null, ex); } JSONObject jsonRes; if (res.getContentType() != ContentType.JSON) { jsonRes = new JSONObject(); if (res.getResult() != Result.OK) { jsonRes.put("error", res.getResult().name()); } else { jsonRes.put("error", "BAD_RETURN_DATA"); } jsonRes.put("status", "BAD_RETURN_DATA"); if (containedReqId) { jsonRes.put("reqid", reqid); jsonRes.put("reqid-connection", "close"); } jsonRes.put("data", new JSONObject()); } else { @SuppressWarnings("unchecked") EndpointResult<JSONObject> obj = (EndpointResult<JSONObject>) res; jsonRes = new JSONObject(); if (res.getResult() != Result.OK) { jsonRes.put("error", res.getResult().name()); } jsonRes.put("status", res.getResult().name()); if (containedReqId) { jsonRes.put("reqid", reqid); jsonRes.put("reqid-connection", "close"); } jsonRes.put("data", obj.getData()); } ctx.channel().writeAndFlush(new TextWebSocketFrame(jsonRes.toString())); }
From source file:me.ferrybig.javacoding.webmapper.netty.WebServerHandler.java
private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { ChannelFuture f = ctx.channel().writeAndFlush(res); if (!isKeepAlive(req) || res.status().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); }/*w ww .java2s .c om*/ }
From source file:me.ferrybig.p2pnetwork.codec.PacketHandler.java
@Override protected void channelRead0(ChannelHandlerContext ctx, ProcessedPacket msg) throws Exception { try {//w ww. j a v a 2 s . com if (msg.getPacket() instanceof PingPacket) { PingPacket pingPacket = (PingPacket) msg.getPacket(); msg.respond(new PongPacket(pingPacket.getData())); } else if (msg.getPacket() instanceof RoutingUpdatePacket) { RoutingUpdatePacket routingUpdatePacket = (RoutingUpdatePacket) msg.getPacket(); if (!msg.getFrom().equals(con.getDirectNode())) { LOG.log(Level.WARNING, "Dropped wrong routing packet coming from node {0} but packet states it comes from {1}", new Object[] { con.getDirectNode(), msg.getFrom() }); return; } con.updateKnownDestinations(routingUpdatePacket.getRoutes()); } else { if (msg.getPacket() instanceof ExitPacket) { ExitPacket exitPacket = (ExitPacket) msg.getPacket(); if (exitPacket.isPreparing()) { msg.respond(new ExitPacket(exitPacket.getReason(), false)) .addListener(ChannelFutureListener.CLOSE); } else { ctx.close(); } } packetHandler.accept(msg); } } finally { msg.getPacket().release(); } }
From source file:me.ferrybig.p2pnetwork.LocalConnection.java
public void close(CloseReason reason, boolean prepare) { ChannelFuture f = this.channel.write(new ExitPacket(reason, prepare)); if (!prepare) f.addListener(ChannelFutureListener.CLOSE); }
From source file:me.hrps.rp.preview.chat.service.WebSocketServerHandler.java
License:Apache License
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { Channel chn = ctx.channel();//from ww w.java2s . c o m String chnId = chn.id().toString(); // Check for closing frame if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (!(frame instanceof TextWebSocketFrame)) { throw new UnsupportedOperationException( String.format("%s frame types not supported", frame.getClass().getName())); } // Send the uppercase string back. String request = ((TextWebSocketFrame) frame).text().toLowerCase(); //MSG=&FROM=4&TO=%235&TYPING=TRUE //MSG=222&FROM=4&TO=%235&TYPING=FALSE ? if (request != null && request.startsWith("msg")) { request = Encodes.urlDecode(request.toLowerCase()); String[] reqMsg = request.split("&"); Message msg = new Message(); for (String input : reqMsg) { String[] inputvalue = input.split("="); if (inputvalue.length == 2) ReflectionUtils.invokeSetter(msg, inputvalue[0], inputvalue[1]); } Channel toChannel = WebSocketServerInitializer.chs.get(msg.getChannelid()); //?? if ("false".equals(msg.getTyping())) { if (msg.getTo() != null) { msg.setTo(msg.getTo().replace("#", "")); } MetaData chatMsgInfo = new MetaData(); chatMsgInfo.setType(2); chatMsgInfo.setMsg(msg); if (toChannel.isActive()) { String pushChatInfo = JacksonMapper.toJSONString(chatMsgInfo); toChannel.writeAndFlush(new TextWebSocketFrame(pushChatInfo)); } } return; } MetaData md = JacksonMapper.readValue(request, MetaData.class); //??,?? if (WebSocketServerInitializer.mds.get(chnId) == null && md != null && md.getType() == 3) { PreChatUser user = chatUserMapper.selectByPrimaryKey(md.getUser().getId()); user.setChannelid(chnId); if (user != null) md.setUser(user); WebSocketServerInitializer.mds.put(chnId, md); //??, MetaData onlineMemberInfo = new MetaData(); onlineMemberInfo.setType(1); List<PreChatUser> users = Lists.newArrayList(); Iterator<MetaData> it = WebSocketServerInitializer.mds.values().iterator(); while (it.hasNext()) { MetaData onlineUser = it.next(); users.add(onlineUser.getUser()); } onlineMemberInfo.setUsers(users); String pushOnlineInfo = JacksonMapper.toJSONString(onlineMemberInfo); Iterator<Channel> chnItor = WebSocketServerInitializer.chs.values().iterator(); while (chnItor.hasNext()) { Channel currChn = chnItor.next(); if (currChn.isActive()) { currChn.writeAndFlush(new TextWebSocketFrame(pushOnlineInfo)); } } return; } System.err.printf("%s received %s%n", ctx.channel(), request); ChannelFuture f = ctx.channel().write(new TextWebSocketFrame(request.toUpperCase())); if ("bye".equals(request)) { f.addListener(ChannelFutureListener.CLOSE); } }
From source file:me.jesonlee.jjfsserver.httpserver.HttpStaticFileServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.getDecoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);/*www. j a va2s . co m*/ return; } if (request.getMethod() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return; } final String uri = request.getUri(); final String path = PathUtil.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:me.jesonlee.jjfsserver.httpserver.HttpStaticFileServerHandler.java
License:Apache License
private static void sendListing(ChannelHandlerContext ctx, File dir) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK); response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8"); String dirPath = dir.getPath(); StringBuilder buf = new StringBuilder().append("<!DOCTYPE html>\r\n").append("<html><head><title>") .append("Listing of: ").append(PathUtil.getRelativePath(dirPath)) .append("</title></head><body>\r\n").append("<h3>Listing of: ") .append(PathUtil.getRelativePath(dirPath)).append("</h3>\r\n") .append("<ul>").append("<li><a href=\"../\">..</a></li>\r\n"); for (File f : dir.listFiles()) { if (f.isHidden() || !f.canRead()) { continue; }//from w w w .ja v a 2 s . c o m String name = f.getName(); if (!ALLOWED_FILE_NAME.matcher(name).matches()) { continue; } buf.append("<li><a href=\"").append(name).append("\">").append(name).append("</a></li>\r\n"); } buf.append("</ul></body></html>\r\n"); ByteBuf buffer = Unpooled.copiedBuffer(buf, CharsetUtil.UTF_8); response.content().writeBytes(buffer); buffer.release(); // Close the connection as soon as the error message is sent. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }