基于netty构建http服务器

深藏阁楼爱情的钟 2022-12-23 09:59 308阅读 0赞

基于netty构建http服务器

基于Netty构建Http服务的流程如下:

  1. Client向Server发送http请求。
  2. Server端对http请求进行解析。
  3. Server端向Client发送http响应。
  4. Client对http响应进行解析。

流程图如下:

在这里插入图片描述

服务器端实现

  1. package com.morris.netty.protocol.http;
  2. import io.netty.bootstrap.ServerBootstrap;
  3. import io.netty.buffer.ByteBuf;
  4. import io.netty.buffer.Unpooled;
  5. import io.netty.channel.*;
  6. import io.netty.channel.nio.NioEventLoopGroup;
  7. import io.netty.channel.socket.SocketChannel;
  8. import io.netty.channel.socket.nio.NioServerSocketChannel;
  9. import io.netty.handler.codec.http.*;
  10. import io.netty.util.CharsetUtil;
  11. import lombok.extern.slf4j.Slf4j;
  12. import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
  13. import static io.netty.handler.codec.http.HttpResponseStatus.OK;
  14. import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
  15. @Slf4j
  16. public class Server {
  17. private static final int port = 8899;
  18. public static void main(String[] args) throws Exception {
  19. EventLoopGroup bossGroup = new NioEventLoopGroup();
  20. EventLoopGroup workerGroup = new NioEventLoopGroup();
  21. try {
  22. ServerBootstrap b = new ServerBootstrap();
  23. b.group(bossGroup, workerGroup)
  24. .channel(NioServerSocketChannel.class)
  25. .childHandler(new ChannelInitializer<SocketChannel>() {
  26. @Override
  27. protected void initChannel(SocketChannel ch) throws Exception {
  28. ch.pipeline().addLast(new HttpRequestDecoder()); // 请求消息解码器
  29. ch.pipeline().addLast(new HttpObjectAggregator(65536));// 目的是将多个消息转换为单一的request或者response对象
  30. ch.pipeline().addLast(new HttpResponseEncoder());//响应编码器
  31. ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
  32. @Override
  33. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  34. FullHttpRequest request = (FullHttpRequest) msg;
  35. log.info("method:{}", request.method().name());
  36. log.info("uri:{}", request.uri());
  37. log.info("content:{}", request.content().toString(CharsetUtil.UTF_8));
  38. FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
  39. response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
  40. ByteBuf buffer = Unpooled.copiedBuffer("<h3>hello world</h3>", CharsetUtil.UTF_8);
  41. response.content().writeBytes(buffer);
  42. buffer.release();
  43. request.release();
  44. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
  45. }
  46. });// 业务逻辑
  47. }
  48. });
  49. ChannelFuture future = b.bind("127.0.0.1", port).sync();
  50. log.info("HTTP服务器启动,网址是 : " + "http://127.0.0.1:" + port);
  51. future.channel().closeFuture().sync();
  52. } finally {
  53. bossGroup.shutdownGracefully();
  54. workerGroup.shutdownGracefully();
  55. }
  56. }
  57. }

在浏览器输入http://127.0.0.1:8899就可以看到页面显示hello world

客户端实现

  1. package com.morris.netty.protocol.http;
  2. import io.netty.bootstrap.Bootstrap;
  3. import io.netty.channel.*;
  4. import io.netty.channel.nio.NioEventLoopGroup;
  5. import io.netty.channel.socket.nio.NioSocketChannel;
  6. import io.netty.handler.codec.http.*;
  7. import io.netty.util.CharsetUtil;
  8. import lombok.extern.slf4j.Slf4j;
  9. @Slf4j
  10. public class Client {
  11. public static void main(String[] args) throws InterruptedException {
  12. EventLoopGroup workerGroup = new NioEventLoopGroup();
  13. try {
  14. Bootstrap b = new Bootstrap();
  15. b.group(workerGroup)
  16. .channel(NioSocketChannel.class)
  17. .handler(new ChannelInitializer() {
  18. @Override
  19. protected void initChannel(Channel ch) throws Exception {
  20. ch.pipeline().addLast(new HttpResponseDecoder()); // 响应解码器
  21. ch.pipeline().addLast(new HttpObjectAggregator(65536));
  22. ch.pipeline().addLast(new HttpRequestEncoder()); // 请求编码器
  23. ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
  24. @Override
  25. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  26. FullHttpResponse httpResponse = (FullHttpResponse)msg;
  27. log.info("status:{}", httpResponse.status());
  28. log.info("headers:{}", httpResponse.headers());
  29. log.info("body:{}", httpResponse.content().toString(CharsetUtil.UTF_8));
  30. httpResponse.release();
  31. }
  32. @Override
  33. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  34. DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
  35. // 构建http请求
  36. request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
  37. request.headers().set(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes());
  38. // 发送http请求
  39. ctx.writeAndFlush(request);
  40. }
  41. });
  42. }
  43. });
  44. // 启动 server.
  45. ChannelFuture f = b.connect("127.0.0.1", 8899).sync();
  46. // 等待socket关闭
  47. f.channel().closeFuture().sync();
  48. } finally {
  49. workerGroup.shutdownGracefully();
  50. }
  51. }
  52. }

发表评论

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

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

相关阅读