Netty实现简易版Http服务

秒速五厘米 2022-09-05 05:28 272阅读 0赞

浏览器访问服务端监听的端口,服务端做出应答

  1. package com.tech.netty.http;
  2. import io.netty.bootstrap.ServerBootstrap;
  3. import io.netty.channel.ChannelFuture;
  4. import io.netty.channel.nio.NioEventLoopGroup;
  5. import io.netty.channel.socket.nio.NioServerSocketChannel;
  6. /**
  7. * @author lw
  8. * @since 2021/8/17
  9. */
  10. public class TestServer {
  11. public static void main(String[] args) throws InterruptedException {
  12. NioEventLoopGroup bossGroup = new NioEventLoopGroup();
  13. NioEventLoopGroup workerGroup = new NioEventLoopGroup();
  14. try{
  15. ServerBootstrap serverBootstrap = new ServerBootstrap();
  16. serverBootstrap.group(bossGroup,workerGroup)
  17. .channel(NioServerSocketChannel.class)
  18. .childHandler(new TestServerInitializer());
  19. ChannelFuture channelFuture = serverBootstrap.bind(7000).sync();
  20. channelFuture.channel().closeFuture().sync();
  21. }finally {
  22. bossGroup.shutdownGracefully();
  23. workerGroup.shutdownGracefully();
  24. }
  25. }
  26. }
  27. package com.tech.netty.http;
  28. import io.netty.channel.ChannelInitializer;
  29. import io.netty.channel.socket.SocketChannel;
  30. import io.netty.handler.codec.http.HttpServerCodec;
  31. /**
  32. * @author lw
  33. * @since 2021/8/17
  34. */
  35. public class TestServerInitializer extends ChannelInitializer<SocketChannel> {
  36. @Override
  37. protected void initChannel(SocketChannel socketChannel) throws Exception {
  38. // HttpServerCodec 是Netty提供的编解码器
  39. socketChannel.pipeline().addLast("MyHttpServerCodec",new HttpServerCodec())
  40. .addLast("",new TestServerHandler()); //在管道添加一个自定义处理器
  41. }
  42. }
  43. package com.tech.netty.http;
  44. import io.netty.buffer.ByteBuf;
  45. import io.netty.buffer.Unpooled;
  46. import io.netty.channel.ChannelHandlerContext;
  47. import io.netty.channel.SimpleChannelInboundHandler;
  48. import io.netty.handler.codec.http.*;
  49. import io.netty.util.CharsetUtil;
  50. import java.net.URI;
  51. /**
  52. * SimpleChannelInboundHandler 是 ChannelInboundHandlerAdapter
  53. * 客户端与服务端相互通信的数据被封装成 HttpObject
  54. * @author lw
  55. * @since 2021/8/17
  56. */
  57. public class TestServerHandler extends SimpleChannelInboundHandler<HttpObject> {
  58. /**
  59. * @description 读取客户端数据
  60. * @author lw
  61. * @since 2021/8/17
  62. **/
  63. @Override
  64. protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
  65. //判断msg是不是HttpRequest请求
  66. if(msg instanceof HttpRequest){
  67. System.out.println("pipeline hashCode="+ctx.pipeline().hashCode()+",TestServerHandler hashCode="+this.hashCode());
  68. System.out.println("msg 类型="+msg.getClass());
  69. System.out.println("客户端地址="+ctx.channel().remoteAddress());
  70. HttpRequest httpRequest = (HttpRequest) msg;
  71. URI uri = new URI(httpRequest.uri());
  72. if("/favicon.ico".equals(uri.getPath())){
  73. System.out.println("请求了favicon.ico,不做响应");
  74. return;
  75. }
  76. //回复信息给浏览器 【http协议】
  77. ByteBuf content = Unpooled.copiedBuffer("hello,这里是服务器", CharsetUtil.UTF_8);
  78. //构造http响应
  79. DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
  80. response.headers().add(HttpHeaderNames.CONTENT_TYPE,"text/plain;charset=utf-8");
  81. response.headers().add(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());
  82. //将构建好response返回
  83. ctx.writeAndFlush(response);
  84. }
  85. }
  86. }

发表评论

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

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

相关阅读