netty 实现一个http服务器

梦里梦外; 2023-10-10 17:15 142阅读 0赞

netty 实现一个http服务器

首先,确保您已将 Netty 依赖添加到 Maven 项目的 pom.xml 文件中。接下来,我们将创建一个简单的 Netty HTTP 服务器,监听 6668 端口,并对特定请求资源进行过滤。

  1. 创建一个 HttpServerHandler 类,它扩展了 SimpleChannelInboundHandler<HttpRequest>

    import io.netty.buffer.Unpooled;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.SimpleChannelInboundHandler;
    import io.netty.handler.codec.http.*;

    import java.nio.charset.StandardCharsets;

    public class HttpServerHandler extends SimpleChannelInboundHandler {

    1. @Override
    2. protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {
    3. // 对特定请求资源进行过滤,例如不处理 favicon.ico 请求
    4. if ("/favicon.ico".equals(msg.uri())) {
    5. System.out.println("请求了 favicon.ico,不做处理");
    6. return;
    7. }
    8. // 构造 HTTP 响应
    9. String content = "Hello! 我是服务器5";
    10. FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
    11. HttpResponseStatus.OK,
    12. Unpooled.wrappedBuffer(content.getBytes(StandardCharsets.UTF_8)));
    13. response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
    14. response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
    15. // 将响应发送回客户端
    16. ctx.writeAndFlush(response);
    17. }

    }

  2. 创建一个 HttpServer 类,用于设置并启动 Netty HTTP 服务器:

    import io.netty.bootstrap.ServerBootstrap;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.EventLoopGroup;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.channel.socket.nio.NioServerSocketChannel;
    import io.netty.handler.codec.http.HttpRequestDecoder;
    import io.netty.handler.codec.http.HttpResponseEncoder;

    public class HttpServer {

    1. public static void main(String[] args) throws InterruptedException {
    2. EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    3. EventLoopGroup workerGroup = new NioEventLoopGroup();
    4. try {
    5. ServerBootstrap serverBootstrap = new ServerBootstrap();
    6. serverBootstrap.group(bossGroup, workerGroup)
    7. .channel(NioServerSocketChannel.class)
    8. .childHandler(new ChannelInitializer<SocketChannel>() {
    9. @Override
    10. protected void initChannel(SocketChannel ch) throws Exception {
    11. ch.pipeline().addLast("httpRequestDecoder", new HttpRequestDecoder());
    12. ch.pipeline().addLast("httpResponseEncoder", new HttpResponseEncoder());
    13. ch.pipeline().addLast("httpServerHandler", new HttpServerHandler());
    14. }
    15. });
    16. ChannelFuture channelFuture = serverBootstrap.bind(6668).sync();
    17. System.out.println("HTTP 服务器启动,监听端口:6668");
    18. channelFuture.channel().closeFuture().sync();
    19. } finally {
    20. bossGroup.shutdownGracefully();
    21. workerGroup.shutdownGracefully();
    22. }
    23. }

    }

现在,运行 HttpServermain 方法,启动 Netty HTTP 服务器。然后,在浏览器中输入 http://localhost:6668/,您将看到服务器回复的消息 “Hello! 我是服务器5”。

这个示例展示了如何使用 Netty 实现一个简单的 HTTP 服务器。

发表评论

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

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

相关阅读