如何用Netty实现一个简单HTTP服务器

绝地灬酷狼 2022-03-26 06:20 380阅读 0赞

本文代码基于netty 4.1版本。

既然你搜到这篇文章了,说明对netty有所了解了,不废话直接上例子,基本上根据netty官网DEMO修改而成。

HttpServer

  1. public class HttpServer {
  2. private int port;
  3. public HttpServer(int port) {
  4. this.port = port;
  5. }
  6. public void run() throws Exception {
  7. //NioEventLoopGroup是一个处理I/O操作的多线程事件循环
  8. //bossGroup作为boss,接收传入连接
  9. //bossGroup只负责接收客户端的连接,不做复杂操作,为了减少资源占用,取值越小越好
  10. //Group:群组,Loop:循环,Event:事件,这几个东西联在一起,相比大家也大概明白它的用途了。
  11. //Netty内部都是通过线程在处理各种数据,EventLoopGroup就是用来管理调度他们的,注册Channel,管理他们的生命周期。
  12. EventLoopGroup bossGroup = new NioEventLoopGroup();
  13. //workerGroup作为worker,处理boss接收的连接的流量和将接收的连接注册进入这个worker
  14. EventLoopGroup workerGroup = new NioEventLoopGroup();
  15. try {
  16. //ServerBootstrap负责建立服务端
  17. //你可以直接使用Channel去建立服务端,但是大多数情况下你无需做这种乏味的事情
  18. ServerBootstrap b = new ServerBootstrap();
  19. b.group(bossGroup, workerGroup)
  20. //指定使用NioServerSocketChannel产生一个Channel用来接收连接
  21. .channel(NioServerSocketChannel.class)
  22. //ChannelInitializer用于配置一个新的Channel
  23. //用于向你的Channel当中添加ChannelInboundHandler的实现
  24. .childHandler(new ChannelInitializer<SocketChannel>() {
  25. public void initChannel(SocketChannel ch) throws Exception {
  26. // server端接收到的是httpRequest,所以要使用HttpRequestDecoder进行解码
  27. ch.pipeline().addLast("http-decoder",new HttpRequestDecoder());
  28. //将多个消息转换为单一的FullHttpRequest或FullHttpResponse对象
  29. ch.pipeline().addLast("http-aggregator",new HttpObjectAggregator(65535));
  30. // server端发送的是httpResponse,所以要使用HttpResponseEncoder进行编码
  31. ch.pipeline().addLast("http-encoder",new HttpResponseEncoder());
  32. //解决大数据包传输问题,用于支持异步写大量数据流并且不需要消耗大量内存也不会导致内存溢出错误( OutOfMemoryError )。
  33. //仅支持ChunkedInput类型的消息。也就是说,仅当消息类型是ChunkedInput时才能实现ChunkedWriteHandler提供的大数据包传输功能
  34. ch.pipeline().addLast("http-chunked",new ChunkedWriteHandler());//解决大码流的问题
  35. ch.pipeline().addLast("http-server",new HttpServerHandler());
  36. }
  37. })
  38. //对Channel进行一些配置
  39. //注意以下是socket的标准参数
  40. //BACKLOG用于构造服务端套接字ServerSocket对象,标识当服务器请求处理线程全满时,用于临时存放已完成三次握手的请求的队列的最大长度。如果未设置或所设置的值小于1,Java将使用默认值50。
  41. //Option是为了NioServerSocketChannel设置的,用来接收传入连接的
  42. .option(ChannelOption.SO_BACKLOG, 128)
  43. //是否启用心跳保活机制。在双方TCP套接字建立连接后(即都进入ESTABLISHED状态)并且在两个小时左右上层没有任何数据传输的情况下,这套机制才会被激活。
  44. //childOption是用来给父级ServerChannel之下的Channels设置参数的
  45. .childOption(ChannelOption.SO_KEEPALIVE, true);
  46. // 绑定并开始接受传入的连接。
  47. ChannelFuture f = b.bind(port).sync();
  48. //等到服务器socket关闭。
  49. // 在这个例子中,这种情况不会发生,但你可以优雅的做到这一点
  50. // 关闭服务器.
  51. //sync()会同步等待连接操作结果,用户线程将在此wait(),直到连接操作完成之后,线程被notify(),用户代码继续执行
  52. //closeFuture()当Channel关闭时返回一个ChannelFuture,用于链路检测
  53. f.channel().closeFuture().sync();
  54. } finally {
  55. //资源优雅释放
  56. bossGroup.shutdownGracefully();
  57. workerGroup.shutdownGracefully();
  58. }
  59. }
  60. public static void main(String[] args) {
  61. int port = 8099;
  62. try {
  63. new HttpServer(port).run();
  64. } catch (Exception e) {
  65. e.printStackTrace();
  66. }
  67. }
  68. }

HttpServerHandler

  1. public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
  2. @Override
  3. protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
  4. // 获取请求的uri
  5. String uri = req.uri();
  6. String msg = "<html><head><title>DEMO</title></head><body>你请求uri为:" + uri+"</body></html>";
  7. // 创建http响应
  8. FullHttpResponse response = new DefaultFullHttpResponse(
  9. HttpVersion.HTTP_1_1,
  10. HttpResponseStatus.OK,
  11. Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8));
  12. // 设置头信息
  13. response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
  14. //response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
  15. // 将html write到客户端
  16. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
  17. }
  18. }

直接运行HttpServer的main函数,在浏览器中访问:http://localhost:8099/index ,http://localhost:8099/text试试看吧。

整个DEMO流程很简单:

  1. 启动服务
  2. 浏览器访问,如:http://localhost:8081/index
  3. 在浏览器看到结果 : 你请求的uri为:/index

至此,我们基于Netty的简易的Http服务器实现了(如果可以称作“HTTP服务器”的话)。 假如我们想要实现,访问 /index.html就返回index.html页面,访问/productList就返回“商品列表JSON”,那么我们还需要做请求路由,还要加入JSON序列化支持,还要根据不同的请求类型调整HTTP响应头。

发表评论

表情:
评论列表 (有 0 条评论,380人围观)

还没有评论,来说两句吧...

相关阅读