注:源代码来自享学课堂,学习之后所做笔记,方便回顾,也给大家一个参考

目录

1 netty编写http服务器

1.1 主函数

1.2 ServerHandlerInit

1.3 服务端自定义BusiHandler

1.4至此,最简单的netty编写的服务器就成了,启动主函数,通过浏览器访问

2 服务器增加压缩支持

2.1 修改ServerHandlerInit,添加上压缩的handler

2.2 访问接口,header出现了

2.3 transfer-encoding: chunked:接受压缩请求

3 Client支持

3.1 client主函数

3.2 HttpClientInboundHandler

4 Https支持

4.1 修改server主函数

4.2 修改handler,加上构造函数,并给ptieline加上ssl支持

4.3 此时可通过https访问


目录

netty编写http服务器

主函数

ServerHandlerInit

服务端自定义BusiHandler

至此,最简单的netty编写的服务器就成了,启动主函数,通过浏览器访问

浏览器访问,返回的结果和正常调用接口是一样的,/test是被拦截的请求

默认是正常的请求

服务器增加压缩支持

修改ServerHandlerInit,添加上压缩的handler

访问接口,header出现了

transfer-encoding: chunked:接受压缩请求

Client支持

HttpClientInboundHandler

Https支持

修改server主函数

修改handler,加上构造函数,并给ptieline加上ssl支持

此时可通过https访问


1 netty编写http服务器

1.1 主函数

public class HttpServer {public static final int port = 6789; //设置服务端端口public static void main(String[] args) throws Exception {EventLoopGroup group = new NioEventLoopGroup();ServerBootstrap b = new ServerBootstrap();try {b.group(group);b.channel(NioServerSocketChannel.class);b.childHandler(new ServerHandlerInit ());// 服务器绑定端口监听ChannelFuture f = b.bind(port).sync();System.out.println("服务端启动成功,端口是:"+port);// 监听服务器关闭监听f.channel().closeFuture().sync();} finally {group.shutdownGracefully();}}
}

1.2 ServerHandlerInit

public class ServerHandlerInit extends ChannelInitializer<SocketChannel> {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();//http响应编码,服务端,对于request是解码,对于response是编码pipeline.addLast("encode",new HttpResponseEncoder());//这里我开始写成了HttpResponseDecoder,程序一直报类型转换异常,要注意pipeline.addLast("decode",new HttpRequestDecoder());///将http请求聚合在一起,可以通过对象.content()来调用,HttpObject, HttpMessage, HttpContent, FullHttpMessagepipeline.addLast("aggre",new HttpObjectAggregator(10*1024*1024));//业务操作,自定义业务操作pipeline.addLast("busi",new BusiHandler());}
}

1.3 服务端自定义BusiHandler

public class BusiHandler extends ChannelInboundHandlerAdapter {private String result = "";private void send(String content, ChannelHandlerContext ctx,HttpResponseStatus status) {//大部分浏览器都是1.1FullHttpResponse response =new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status,Unpooled.copiedBuffer(content, CharsetUtil.UTF_8));response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain;charset=UTF-8");ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);}@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg)throws Exception {String result = "";//接收到完成的http请求FullHttpRequest httpRequest = (FullHttpRequest) msg;try {String path = httpRequest.uri();String body = httpRequest.content().toString(CharsetUtil.UTF_8);//get,post,delete,updateHttpMethod method = httpRequest.method();if ("/test".equalsIgnoreCase(path)) {result = "错误请求:" + path;send(result, ctx, HttpResponseStatus.BAD_REQUEST);return;}if (HttpMethod.GET.equals(method)) {System.out.println("body:" + body);result = "get Response=服务器返回数据";send(result, ctx, HttpResponseStatus.OK);}} catch (Exception e) {System.out.println("处理请求失败!");e.printStackTrace();} finally {httpRequest.release();}}/** 建立连接时,返回消息*/@Overridepublic void channelActive(ChannelHandlerContext ctx)throws Exception {System.out.println("连接的客户端地址:"+ ctx.channel().remoteAddress());}
}

1.4至此,最简单的netty编写的服务器就成了,启动主函数,通过浏览器访问

浏览器访问,返回的结果和正常调用接口是一样的,/test是被拦截的请求

默认是正常的请求

2 服务器增加压缩支持

2.1 修改ServerHandlerInit,添加上压缩的handler

public class ServerHandlerInit extends ChannelInitializer<SocketChannel> {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();//http响应编码,服务端,对于request是解码,对于response是编码pipeline.addLast("encode",new HttpResponseEncoder());//这里我开始写成了HttpResponseDecoder,程序一直报类型转换异常,要注意pipeline.addLast("decode",new HttpRequestDecoder());///将http请求聚合在一起,可以通过对象.content()来调用,HttpObject, HttpMessage, HttpContent, FullHttpMessagepipeline.addLast("aggre",new HttpObjectAggregator(10*1024*1024));//添加压缩支持pipeline.addLast("compressor",new HttpContentCompressor());//业务操作,自定义业务操作pipeline.addLast("busi",new BusiHandler());}
}

2.2 访问接口,header出现了

2.3 transfer-encoding: chunked:接受压缩请求

3 Client支持

3.1 client主函数

public class HttpClient {private static final boolean SSL = false;public void connect(String host, int port) throws Exception {EventLoopGroup workerGroup = new NioEventLoopGroup();try {Bootstrap b = new Bootstrap();b.group(workerGroup);b.channel(NioSocketChannel.class);b.option(ChannelOption.SO_KEEPALIVE, true);b.handler(new ChannelInitializer<SocketChannel>() {@Overridepublic void initChannel(SocketChannel ch)throws Exception {//这一句相当于下面的两句ch.pipeline().addLast(new HttpClientCodec());
//                    ch.pipeline().addLast(new HttpResponseDecoder());
//                    ch.pipeline().addLast(new HttpRequestEncoder());ch.pipeline().addLast("aggre",new HttpObjectAggregator(10 * 1024 * 1024));ch.pipeline().addLast("decompressor", new HttpContentDecompressor());ch.pipeline().addLast("busi", new HttpClientInboundHandler());}});// Start the client.ChannelFuture f = b.connect(host, port).sync();URI uri = new URI("/test");String msg = "Hello";DefaultFullHttpRequest request =new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,HttpMethod.GET,uri.toASCIIString(),Unpooled.wrappedBuffer(msg.getBytes("UTF-8")));// 构建http请求request.headers().set(HttpHeaderNames.HOST, host);request.headers().set(HttpHeaderNames.CONNECTION,HttpHeaderValues.KEEP_ALIVE);request.headers().set(HttpHeaderNames.CONTENT_LENGTH,request.content().readableBytes());// 发送http请求f.channel().write(request);f.channel().flush();f.channel().closeFuture().sync();} finally {workerGroup.shutdownGracefully();}}public static void main(String[] args) throws Exception {HttpClient client = new HttpClient();client.connect("127.0.0.1", HttpServer.port);}
}

3.2 HttpClientInboundHandler

public class HttpClientInboundHandlerextends ChannelInboundHandlerAdapter {public void channelRead(ChannelHandlerContext ctx, Object msg)throws Exception {//开始对服务器的响应做处理FullHttpResponse httpResponse = (FullHttpResponse)msg;System.out.println(httpResponse.headers());ByteBuf content = httpResponse.content();System.out.println(content.toString(CharsetUtil.UTF_8));content.release();}
}

建议直接使用开源的apache的HttpClient

4 Https支持

4.1 修改server主函数

public static void main(String[] args) throws Exception {//netty为我们提供的ssl加密,缺省SelfSignedCertificate ssc = new SelfSignedCertificate();SslContext build = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();EventLoopGroup group = new NioEventLoopGroup();ServerBootstrap b = new ServerBootstrap();try {b.group(group);b.channel(NioServerSocketChannel.class);b.childHandler(new ServerHandlerInit(build));// 服务器绑定端口监听ChannelFuture f = b.bind(port).sync();System.out.println("服务端启动成功,端口是:"+port);// 监听服务器关闭监听f.channel().closeFuture().sync();} finally {group.shutdownGracefully();}
}

4.2 修改handler,加上构造函数,并给ptieline加上ssl支持

public class ServerHandlerInit extends ChannelInitializer<SocketChannel> {private SslContext build;public ServerHandlerInit(SslContext build) {this.build = build;}@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();//启用sslpipeline.addLast(build.newHandler(ch.alloc()));//http响应编码,服务端,对于request是解码,对于response是编码
//        pipeline.addLast(new HttpServerCodec());这一句可以替代下面的几句pipeline.addLast("encode",new HttpResponseEncoder());//这里我开始写成了HttpResponseDecoder,程序一直报类型转换异常,要注意pipeline.addLast("decode",new HttpRequestDecoder());///将http请求聚合在一起,可以通过对象.content()来调用,HttpObject, HttpMessage, HttpContent, FullHttpMessagepipeline.addLast("aggre",new HttpObjectAggregator(10*1024*1024));//添加压缩支持pipeline.addLast("compressor",new HttpContentCompressor());//业务操作,自定义业务操作pipeline.addLast("busi",new BusiHandler());}
}

4.3 此时可通过https访问

4、netty编写http服务器、增加压缩支持、netty编写client、netty添加SL/TLS保护https支持相关推荐

  1. java 下载工具_java_java编写Http服务器下载工具,这个工具比较简单,用于配合 - phpStudy...

    java编写Http服务器下载工具 这个工具比较简单,用于配合另外一个工具进行文件传送,废话少说,上代码 import java.net.URL; import java.net.URLConnect ...

  2. mysql表增加压缩属性_InnoDB列压缩,提升DB性能

    作者 felixliang 腾讯游戏风雨十年,一直致力于带给玩家最好的快乐体验,为此也取得了巨大的成功. 腾讯游戏的后台数据库一直守护着亿万玩家的数据,提供着稳定透明的服务. 腾讯后台数据库大部分使用 ...

  3. netty系列之:使用netty搭建websocket服务器

    文章目录 简介 netty中的websocket websocket的版本 FrameDecoder和FrameEncoder WebSocketServerHandshaker WebSocketF ...

  4. java ios压缩_iOS与Java服务器GZip压缩问题【转】

    昨天搞了一天的GZip压缩,试了三种方式(libz库,ZipArchive,ASIHttpRequest),一开始都不成功. 理论上三个应该都能用的,但我都不行.等我试到第三种方式的时候才知道,不是我 ...

  5. 502无法解析服务器标头_编写下载服务器。 第三部分:标头:内容长度和范围...

    502无法解析服务器标头 这次,我们将探索更多HTTP请求和响应标头,以改善下载服务器的实现: Content-length和Range . 前者表示下载量很大,后者允许部分下载文件,或者从我们开始的 ...

  6. grpc 流式传输_编写下载服务器。 第一部分:始终流式传输,永远不要完全保留在内存中...

    grpc 流式传输 下载各种文件(文本或二进制文件)是每个企业应用程序的生死攸关的事情. PDF文档,附件,媒体,可执行文件,CSV,超大文件等.几乎每个应用程序迟早都必须提供某种形式的下载. 下载是 ...

  7. 502无法解析服务器标头_编写下载服务器。 第二部分:标头:Last-Modified,ETag和If-None-Match...

    502无法解析服务器标头 客户端缓存是万维网的基础之一. 服务器应通知客户端资源的有效性,客户端应尽可能快地对其进行缓存. 如我们所见,如果不缓存Web,它将非常缓慢. 只需在任何网站上Ctrl + ...

  8. 编写下载服务器。 第一部分:始终流式传输,永远不要完全保留在内存中

    下载各种文件(文本或二进制文件)是每个企业应用程序的生死攸关的事情. PDF文档,附件,媒体,可执行文件,CSV,超大文件等.几乎每个应用程序迟早都必须提供某种形式的下载. 下载是通过HTTP来实现的 ...

  9. 编写下载服务器。 第二部分:标头:Last-Modified,ETag和If-None-Match

    客户端缓存是万维网的基础之一. 服务器应告知客户端资源的有效性,客户端应尽可能快地对其进行缓存. 如我们所见,如果不缓存Web,将会非常慢. 只需在任何网站上Ctrl + F5并将其与普通F5进行比较 ...

最新文章

  1. Attribute在.net编程中的应用
  2. 微信小程序开发实战基础一、页面跳转,底部导航栏,分享,加载图片标签,列表
  3. mysql允许两个用户远程连接,配置MySQL服务允许用户远程连接
  4. Mac下iTerm2的ls输出如何显示文件件颜色呢?
  5. 余姚中考能用计算机吗,2018年余姚中考政策有大变化,2020年取消奖励加分项目...
  6. C++ Primer 第4章数组和指针
  7. Ssm手机电脑自适应新闻博客系统实战开发
  8. 赛锐信息:SAP ABAP 屏幕导航
  9. python必备基础代码-【Python基础系列】常见的数据预处理方法(附代码)
  10. 冯永昌:云计算与大数据时代的量化投资
  11. 没有任何借口——提升职场能力的文章
  12. 二叉搜索树 根据前序序列求中序序列
  13. 2021年中国养老保险参保人数、基金收入、基金支出及未来发展趋势分析[图]
  14. 干货|Android免Root最全Hook插件(免Root Hook任意App)
  15. php 获取农历,PHP通过新历获取农历日期的方法
  16. 全系列毕业设计论文来了
  17. 各类计算机接口标志,电脑usb3 USB4接口标准标识被英特尔重新规范
  18. 1.2 Objective-C语言和它的后继者:Swift
  19. c语言小红今年12岁小明13岁,[转载]三年级下“创新思维数学讲义”——年龄问题...
  20. 普洛斯2020迄今光伏发电能力增长56%,中国市场光伏装机容量增加113%

热门文章

  1. 浏览器页面内容无法复制粘贴?解决办法
  2. MyBatis中SqlSessionFactory和SqlSession简解
  3. xx公司员工信息精细化管理系统总结分析
  4. Hive on Spark Tachyon解析
  5. 成就DBA的职业生涯(转载)
  6. scrapy模拟浏览器翻页爬取智联
  7. 让罕见被看见 | “罕罕漫游”公益品牌发布会在上海成功举办
  8. 广播组件的实践——短信黑名单
  9. 优雅性感之 JSON 小姐姐
  10. NO.4 Android Opencv 特征检测