netty-reacter写一个http服务器

使用Netty和Reactor编写一个HTTP服务器,首先需要添加相关依赖到项目中。在Maven项目的pom.xml文件中添加以下依赖:

```xml
<dependencies>
    <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-all</artifactId>
        <version>4.1.68.Final</version>
    </dependency>
    <dependency>
        <groupId>io.projectreactor</groupId>
        <artifactId>reactor-core</artifactId>
        <version>3.4.0</version>
    </dependency>
</dependencies>
```

接下来,创建一个Netty HTTP服务器的示例代码:

```java
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
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;
import reactor.core.publisher.Mono;

public class NettyHttpServer {

    private final int port;

    public NettyHttpServer(int port) {
        this.port = port;
    }

    public void start() throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new HttpRequestDecoder());
                            ch.pipeline().addLast(new HttpResponseEncoder());
                            ch.pipeline().addLast(new HttpServerHandler());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture f = b.bind(port).sync();
            System.out.println("HTTP服务器启动,监听端口:" + port);
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new NettyHttpServer(8080).start();
    }
}
```

上面的代码中,创建了一个Netty HTTP服务器,监听8080端口。当有客户端连接时,会调用`HttpServerHandler`来处理请求。接下来,我们需要实现`HttpServerHandler`类来处理HTTP请求:

```java
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
        if (req.method() == HttpMethod.GET) {
            handleGet(ctx, req);
        } else {
            sendError(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED);
        }
    }

    private void handleGet(ChannelHandlerContext ctx, FullHttpRequest req) {
        String responseBody = "Hello, Netty and Reactor!";
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.copiedBuffer(responseBody, StandardCharsets.UTF_8));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, responseBody.length());

        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);

        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }
}
```

在上面的代码中,我们实现了一个简单的HTTP服务器,只处理GET请求,并返回"Hello, Netty and Reactor!"作为响应。运行`NettyHttpServer`的`main`方法,启动服务器后,可以使用浏览器或其他HTTP客户端访问`http://localhost:8080`,看到返回的响应。 

相关推荐

  1. netty-reacter一个http服务器

    2024-06-16 18:02:01       29 阅读
  2. Netty HTTP

    2024-06-16 18:02:01       18 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-16 18:02:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-16 18:02:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-06-16 18:02:01       82 阅读
  4. Python语言-面向对象

    2024-06-16 18:02:01       91 阅读

热门阅读

  1. Spring多数据源管理方案

    2024-06-16 18:02:01       32 阅读
  2. Web前端行距代码:深入探索与实战应用

    2024-06-16 18:02:01       35 阅读
  3. 介绍一个 SpringBoot 集成各种场景的项目

    2024-06-16 18:02:01       122 阅读
  4. 外包公司泛滥,这些常识你应该提前知道?

    2024-06-16 18:02:01       33 阅读
  5. 学习分享-FutureTask

    2024-06-16 18:02:01       31 阅读
  6. 基于深度学习的物体材质预测

    2024-06-16 18:02:01       31 阅读
  7. iOS cell的复用以及自定义cell

    2024-06-16 18:02:01       38 阅读
  8. lwip中server和client的socket、地址和端口号

    2024-06-16 18:02:01       35 阅读