接着来看看

/** Copyright 2012 The Netty Project** The Netty Project licenses this file to you under the Apache License,* version 2.0 (the "License"); you may not use this file except in compliance* with the License. You may obtain a copy of the License at:**   http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the* License for the specific language governing permissions and limitations* under the License.*/
package io.netty.example.http.snoop;import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.example.securechat.SecureChatSslContextFactory;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpContentDecompressor;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslHandler;import javax.net.ssl.SSLEngine;public class HttpSnoopClientInitializer extends ChannelInitializer<SocketChannel> {private final boolean ssl;public HttpSnoopClientInitializer(boolean ssl) {this.ssl = ssl;}@Overridepublic void initChannel(SocketChannel ch) throws Exception {// Create a default pipeline implementation.ChannelPipeline p = ch.pipeline();p.addLast("log", new LoggingHandler(LogLevel.INFO));// Enable HTTPS if necessary.if (ssl) {SSLEngine engine =SecureChatSslContextFactory.getClientContext().createSSLEngine();engine.setUseClientMode(true);p.addLast("ssl", new SslHandler(engine));}p.addLast("codec", new HttpClientCodec());// Remove the following line if you don't want automatic content decompression.p.addLast("inflater", new HttpContentDecompressor());// Uncomment the following line if you don't want to handle HttpChunks.//p.addLast("aggregator", new HttpObjectAggregator(1048576));p.addLast("handler", new HttpSnoopClientHandler());}
}
/** Copyright 2012 The Netty Project** The Netty Project licenses this file to you under the Apache License,* version 2.0 (the "License"); you may not use this file except in compliance* with the License. You may obtain a copy of the License at:**   http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the* License for the specific language governing permissions and limitations* under the License.*/
package io.netty.example.http.snoop;import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;public class HttpSnoopServerInitializer extends ChannelInitializer<SocketChannel> {@Overridepublic void initChannel(SocketChannel ch) throws Exception {// Create a default pipeline implementation.ChannelPipeline p = ch.pipeline();// Uncomment the following line if you want HTTPS//SSLEngine engine = SecureChatSslContextFactory.getServerContext().createSSLEngine();//engine.setUseClientMode(false);//p.addLast("ssl", new SslHandler(engine));p.addLast("decoder", new HttpRequestDecoder());// Uncomment the following line if you don't want to handle HttpChunks.//p.addLast("aggregator", new HttpObjectAggregator(1048576));p.addLast("encoder", new HttpResponseEncoder());// Remove the following line if you don't want automatic content compression.//p.addLast("deflater", new HttpContentCompressor());p.addLast("handler", new HttpSnoopServerHandler());}
}
/** Copyright 2012 The Netty Project** The Netty Project licenses this file to you under the Apache License,* version 2.0 (the "License"); you may not use this file except in compliance* with the License. You may obtain a copy of the License at:**   http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the* License for the specific language governing permissions and limitations* under the License.*/
package io.netty.example.http.snoop;import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.util.CharsetUtil;public class HttpSnoopClientHandler extends SimpleChannelInboundHandler<HttpObject> {@Overridepublic void messageReceived(ChannelHandlerContext ctx, HttpObject msg) throws Exception {if (msg instanceof HttpResponse) {HttpResponse response = (HttpResponse) msg;System.out.println("STATUS: " + response.getStatus());System.out.println("VERSION: " + response.getProtocolVersion());System.out.println();if (!response.headers().isEmpty()) {for (String name: response.headers().names()) {for (String value: response.headers().getAll(name)) {System.out.println("HEADER: " + name + " = " + value);}}System.out.println();}if (HttpHeaders.isTransferEncodingChunked(response)) {System.out.println("CHUNKED CONTENT {");} else {System.out.println("CONTENT {");}}if (msg instanceof HttpContent) {HttpContent content = (HttpContent) msg;System.out.print(content.content().toString(CharsetUtil.UTF_8));System.out.flush();if (content instanceof LastHttpContent) {System.out.println("} END OF CONTENT");}}}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {cause.printStackTrace();ctx.close();}
}
/** Copyright 2012 The Netty Project** The Netty Project licenses this file to you under the Apache License,* version 2.0 (the "License"); you may not use this file except in compliance* with the License. You may obtain a copy of the License at:**   http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the* License for the specific language governing permissions and limitations* under the License.*/
package io.netty.example.http.snoop;import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.DecoderResult;
import io.netty.handler.codec.http.Cookie;
import io.netty.handler.codec.http.CookieDecoder;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.handler.codec.http.ServerCookieEncoder;
import io.netty.util.CharsetUtil;import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;import static io.netty.handler.codec.http.HttpHeaders.Names.*;
import static io.netty.handler.codec.http.HttpHeaders.*;
import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http.HttpVersion.*;public class HttpSnoopServerHandler extends SimpleChannelInboundHandler<Object> {private HttpRequest request;/** Buffer that stores the response content */private final StringBuilder buf = new StringBuilder();@Overridepublic void channelReadComplete(ChannelHandlerContext ctx) throws Exception {ctx.flush();}@Overrideprotected void messageReceived(ChannelHandlerContext ctx, Object msg) {if (msg instanceof HttpRequest) {HttpRequest request = this.request = (HttpRequest) msg;if (is100ContinueExpected(request)) {send100Continue(ctx);}buf.setLength(0);buf.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");buf.append("===================================\r\n");buf.append("VERSION: ").append(request.getProtocolVersion()).append("\r\n");buf.append("HOSTNAME: ").append(getHost(request, "unknown")).append("\r\n");buf.append("REQUEST_URI: ").append(request.getUri()).append("\r\n\r\n");HttpHeaders headers = request.headers();if (!headers.isEmpty()) {for (Map.Entry<String, String> h: headers) {String key = h.getKey();String value = h.getValue();buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n");}buf.append("\r\n");}QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri());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 (String name: trailer.trailingHeaders().names()) {for (String value: trailer.trailingHeaders().getAll(name)) {buf.append("TRAILING HEADER: ");buf.append(name).append(" = ").append(value).append("\r\n");}}buf.append("\r\n");}writeResponse(trailer, ctx);}}}private static void appendDecoderResult(StringBuilder buf, HttpObject o) {DecoderResult result = o.getDecoderResult();if (result.isSuccess()) {return;}buf.append(".. WITH DECODER FAILURE: ");buf.append(result.cause());buf.append("\r\n");}private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) {// Decide whether to close the connection or not.boolean keepAlive = isKeepAlive(request);// Build the response object.FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, currentObj.getDecoderResult().isSuccess()? OK : BAD_REQUEST,Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8));response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");if (keepAlive) {// Add 'Content-Length' header only for a keep-alive connection.response.headers().set(CONTENT_LENGTH, response.content().readableBytes());// Add keep alive header as per:// - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connectionresponse.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);}// Encode the cookie.String cookieString = request.headers().get(COOKIE);if (cookieString != null) {Set<Cookie> cookies = CookieDecoder.decode(cookieString);if (!cookies.isEmpty()) {// Reset the cookies if necessary.for (Cookie cookie: cookies) {response.headers().add(SET_COOKIE, ServerCookieEncoder.encode(cookie));}}} else {// Browser sent no cookie.  Add some.response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("key1", "value1"));response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("key2", "value2"));}// Write the response.ctx.write(response);return keepAlive;}private static void send100Continue(ChannelHandlerContext ctx) {FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, CONTINUE);ctx.write(response);}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {cause.printStackTrace();ctx.close();}
}

netty官方例子 三 http snoop监听相关推荐

  1. 【Netty】入门Netty官方例子解析(二)Time Server

    本文承接上文<[Netty]入门Netty官方例子解析(一)写个 Discard Server> ,接下来讲解官网文档中Netty入门官方例子第二个例子 Time Server 原文这个章 ...

  2. Cesium 三维球转动监听事件(相机监听事件)并且获取当前中心点位置

    三维球转动监听,可以使用相机监听,也可以使用鼠标移动监听. 相机监听有延迟,必须转动到一定程度后,才会启动监听. 鼠标移动监听可以实时监听 /* 三维球转动添加监听事件 */ viewer.camer ...

  3. 【Netty】入门Netty官方例子解析(三)处理一个基于流的传输 TCP粘包和拆包问题分析和解决

    关于 Socket Buffer的一个小警告 基于流的传输比如 TCP/IP, 接收到数据是存在 socket 接收的 buffer 中.不幸的是,基于流的传输并不是一个数据包队列,而是一个字节队列. ...

  4. 【Netty】入门Netty官方例子解析(一)写个 Discard Server

    本文以Netty官方给出的列子来讲解Netty带你一步步进入Netty.Netty最全教程在这里 Getting Started 版本 netty4 maven依赖: <!-- https:// ...

  5. Curator 三种 Watcher 监听实现

    项目背景: 实时 Flink任务中,需要实现不停实时任务,清除关联维表的本地缓存. 方案: 方案采用 Zookeeper 的配置中心的功能,即当需要清除正在运行 Flink App 的维表本地缓存时, ...

  6. 安卓Android绘制一个信息填写页面,使用了三种事件监听方法

    先上效果图片: 第一种,匿名内部类 //设置提交按钮监听submitButton.setOnClickListener(new View.OnClickListener() {@Overridepub ...

  7. webpack学习笔记(三):监听文件变化并编译

    在上一篇webpack学习笔记中主要认识了webpack配置文件中相关的基础配置和命令的执行.这次学习如何在文件发生变化时自动打包编译. 首先,我们来看一下配置文件 const path = requ ...

  8. Elastic Job 入门教程(三)— 作业监听

    接上一篇:Elastic Job 入门教程(二)- Spring Boot框架下是实现Elastic Job 脚本作业(Script Job),本章我们讨论作业Job的监听. 定义监听器 @Compo ...

  9. watch事件监听三种写法

    第一种 普通监听 <input type="text" v-model="userName"/> //监听 当userName值发生变化时触发 wa ...

  10. Java中事件监听机制

    Java中事件监听机制 一.事件监听机制的定义 要想了解Java中的事件监听机制,首先就要去了解一下在Java中事件是怎样去定义的呢!在使用Java编写好一个界面后,我们就会对界面进行一些操作,比如, ...

最新文章

  1. 慕课网 深入浅出javascript 笔记
  2. Android 程序启动界面Demo
  3. 笑话(15) 这是地球
  4. 一个mapper接口有多个mapper.xml 文件_爱了!分享一个基于Spring Boot的API、RESTful API项目种子(骨架)!...
  5. Server2012R2 ADFS3.0 The same client browser session has made '6' requests in the last '13'seconds
  6. CentOS7 安装管理KVM虚拟机
  7. 苹果Mac硬件温度监控软件:TG Pro
  8. SIP协议搭建电信级VOIP/IM运营平台--架构篇(sip集群)
  9. 国产车崛起粉碎德日工业神话
  10. 《日本制造业白皮书(2018)》重磅发布!附400多页PPT
  11. The RSpec Book笔记《二》Describing Features描述功能
  12. python量化之路:获取历史某一时刻沪深上市公司股票代码及上市时间
  13. Android 使用三级缓存实现对图片的加载
  14. (转)2016年对冲基金经理“封神榜”
  15. 文件服务器+快照恢复,删除vmware ESXi快照文件 – 以任何方式恢复?
  16. Excel的IYQ钓鱼
  17. CF869C The Intriguing Obsession
  18. 任务教学法在计算机教学,“任务驱动”教学法在计算机基础教学中的应用
  19. WPS文字绿色版下载 WPS Office 2010 中文绿色版
  20. JS如何终止forEach循环

热门文章

  1. Firefox检测到潜在的安全威胁,并因blog.csdn.net要求安全连接而没有继续
  2. 联系人管理-添加/修改/删除联系人/条件查询/解决与客户之间的问题| CRM客户关系管理系统项目实战五(Struts2+Spring+Hibernate)解析+源代码
  3. 手游服务器常用架构图
  4. 大型网站的静态化处理
  5. Python shift()
  6. android java char_Android句子迷客户端
  7. code3:使用set判断数组中是否有重复值
  8. Oracle VirtualBox 6.1.18 安装扩展包
  9. dell笔记本外接显示器_戴尔笔记本怎样外接显示器
  10. premiere导入视频没有声音怎么办?快速解决方法,几步就搞定