List of usage examples for io.netty.channel ChannelHandlerContext channel
Channel channel();
From source file:com.dwarf.netty.guide.securechat.SecureChatServerHandler.java
License:Apache License
@Override public void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception { // Send the received message to all channels but the current one. for (Channel c : channels) { if (c != ctx.channel()) { c.writeAndFlush("[" + ctx.channel().remoteAddress() + "] " + msg + '\n'); } else {/* w ww . j a v a 2s . c om*/ c.writeAndFlush("[you] " + msg + '\n'); } } // Close the connection if the client has sent 'bye'. if ("bye".equals(msg.toLowerCase())) { ctx.close(); } }
From source file:com.dwarf.netty.guide.worldclock.WorldClockClientHandler.java
License:Apache License
@Override public void channelRegistered(ChannelHandlerContext ctx) { channel = ctx.channel(); }
From source file:com.e2e.management.HttpSocketHandler.java
License:Apache License
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) { // Handle a bad request. if (!req.getDecoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return;//from ww w .j a v a 2 s . c o m } // Allow only GET methods. if (req.getMethod() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; } if ("/favicon.ico".equals(req.getUri())) { FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND); sendHttpResponse(ctx, req, res); return; } // Handshake WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req), null, true); handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel()); } else { handshaker.handshake(ctx.channel(), req); } }
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;/* w w w . j a v a 2 s . c o m*/ } 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.earasoft.framework.http.WebSocketServerHandler.java
License:Apache License
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { System.out.println("pre1:" + frame); // Check for closing frame if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return;/*from ww w. j av a 2 s. c o m*/ } 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())); } WebsocketMessageHandlerI websocketMessageHandler = new WebSocketMessageHander(ctx, channels); // Send the uppercase string back. String requestRaw = ((TextWebSocketFrame) frame).text(); websocketMessageHandler.handleMessage(requestRaw); }
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;//from ww w. j a va 2s . com 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 {//from www.j a v a2s. 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.client.HttpResponseHandler.java
License:MIT License
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { printInfo("Rcvr Session created to host - " + ((InetSocketAddress) ctx.channel().remoteAddress()).getHostName()); super.channelActive(ctx); }
From source file:com.ebay.jetstream.http.netty.client.HttpResponseHandler.java
License:MIT License
@Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { printInfo("EventProducerSessionHandler -> session closed to host - " + ((InetSocketAddress) ctx.channel().remoteAddress()).getHostName()); super.channelInactive(ctx); m_httpClient.channelDisconnected(ctx.channel()); }
From source file:com.ebay.jetstream.http.netty.client.HttpResponseHandler.java
License:MIT License
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable ee) throws Exception { String message = "Exception Caught while communicating to "; try {//from w w w.ja v a 2s .c o m message += ((InetSocketAddress) ctx.channel().remoteAddress()).getHostName(); message += ee.getCause(); printInfo(message); } catch (Throwable t) { } printInfo("EventProducerSessionHandler -> exceptionCaught" + ee.toString()); super.exceptionCaught(ctx, ee); }