netty 实现一个http服务器
netty 实现一个http服务器
首先,确保您已将 Netty 依赖添加到 Maven 项目的 pom.xml
文件中。接下来,我们将创建一个简单的 Netty HTTP 服务器,监听 6668 端口,并对特定请求资源进行过滤。
创建一个
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
{ @Override
protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {
// 对特定请求资源进行过滤,例如不处理 favicon.ico 请求
if ("/favicon.ico".equals(msg.uri())) {
System.out.println("请求了 favicon.ico,不做处理");
return;
}
// 构造 HTTP 响应
String content = "Hello! 我是服务器5";
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
HttpResponseStatus.OK,
Unpooled.wrappedBuffer(content.getBytes(StandardCharsets.UTF_8)));
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
// 将响应发送回客户端
ctx.writeAndFlush(response);
}
}
创建一个
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 {
public static void main(String[] args) throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast("httpRequestDecoder", new HttpRequestDecoder());
ch.pipeline().addLast("httpResponseEncoder", new HttpResponseEncoder());
ch.pipeline().addLast("httpServerHandler", new HttpServerHandler());
}
});
ChannelFuture channelFuture = serverBootstrap.bind(6668).sync();
System.out.println("HTTP 服务器启动,监听端口:6668");
channelFuture.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
现在,运行 HttpServer
的 main
方法,启动 Netty HTTP 服务器。然后,在浏览器中输入 http://localhost:6668/
,您将看到服务器回复的消息 “Hello! 我是服务器5”。
这个示例展示了如何使用 Netty 实现一个简单的 HTTP 服务器。
还没有评论,来说两句吧...