netty 实现http

[复制链接]
发表于 2025-12-6 19:37:43 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
  1. package cn.rainwer.nettywebsocket.Server;
  2. import io.netty.bootstrap.ServerBootstrap;
  3. import io.netty.channel.ChannelFuture;
  4. import io.netty.channel.ChannelInitializer;
  5. import io.netty.channel.EventLoopGroup;
  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.HttpObjectAggregator;
  10. import io.netty.handler.codec.http.HttpServerCodec;
  11. import io.netty.handler.codec.http.HttpServerExpectContinueHandler;
  12. public class NettyHttpServer {
  13.     public static void main(String[] args) {
  14.         EventLoopGroup bossGroup = new NioEventLoopGroup(1);
  15.         EventLoopGroup workerGroup = new NioEventLoopGroup();
  16.         ChannelFuture f = null;
  17.         try {
  18.             //ServerBootstrap负责初始化netty服务器,并且开始监听端口的socket请求
  19.             ServerBootstrap b = new ServerBootstrap();
  20.             b.group(bossGroup, workerGroup)
  21.                     .channel(NioServerSocketChannel.class)
  22.                     .childHandler(new ChannelInitializer<SocketChannel>() {
  23.                         @Override
  24.                         protected void initChannel(SocketChannel socketChannel) throws Exception {
  25.                             // 为监听客户端read/write事件的Channel添加用户自定义的ChannelHandler
  26.                             socketChannel.pipeline()
  27. //                                    .addLast("decoder", new HttpRequestDecoder())
  28. //                                    .addLast("encoder", new HttpResponseEncoder())
  29.                                     .addLast(new HttpServerCodec())
  30.                                     .addLast(new HttpServerExpectContinueHandler())
  31.                                     .addLast("aggregator", new HttpObjectAggregator(512 * 1024))
  32.                                     .addLast(new NettyWebSocketConnectHandler2());
  33.                         }
  34.                     });
  35.             f = b.bind(9996).sync();
  36.             System.out.println("======NettyServer启动成功!!!=========");
  37.             // f.channel().closeFuture().sync();
  38.         } catch (Exception e) {
  39.             e.printStackTrace();
  40.         } finally {
  41.             if (f != null && f.isSuccess()) {
  42.                 System.out.println("Netty server listening on port " + " and ready for connections...");
  43.             } else {
  44.                 System.out.println("Netty server start up Error!");
  45.             }
  46.         }
  47.     }
  48. }
复制代码
  1. package cn.rainwer.nettywebsocket.Server;
  2. import io.netty.buffer.Unpooled;
  3. import io.netty.channel.ChannelHandler;
  4. import io.netty.channel.ChannelHandlerContext;
  5. import io.netty.channel.SimpleChannelInboundHandler;
  6. import io.netty.handler.codec.http.*;
  7. import lombok.extern.slf4j.Slf4j;
  8. import org.springframework.stereotype.Component;
  9. import java.net.InetAddress;
  10. import java.nio.charset.StandardCharsets;
  11. @Slf4j
  12. @ChannelHandler.Sharable
  13. @Component
  14. public class NettyWebSocketConnectHandler2 extends SimpleChannelInboundHandler<Object> {
  15.     @Override
  16.     public void channelRead(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {
  17.         if (msg instanceof FullHttpRequest) {
  18.             log.info("准备提取token");
  19.             //转化为http请求
  20.             FullHttpRequest request = (FullHttpRequest) msg;
  21.             //拿到请求地址
  22.             String uri = request.uri();
  23.             System.out.println(uri);
  24.             //判断是不是websocket请求,如果是拿出我们传递的参数(我的是token)
  25.             channelHandlerContext.channel().writeAndFlush("Welcome to " + InetAddress.getLocalHost().getHostName() + " service!\n");
  26.             FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(request.protocolVersion(), HttpResponseStatus.OK, Unpooled.wrappedBuffer(uri.getBytes(StandardCharsets.UTF_8)));
  27.             fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN)
  28.                     .set(HttpHeaderNames.CONTENT_LENGTH, fullHttpResponse.content().readableBytes());
  29.             channelHandlerContext.writeAndFlush(fullHttpResponse);
  30.         } else {
  31.         }
  32.     }
  33. }
复制代码

回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表