首发于Enaium的个人博客
public class Server {
public static void main(String[] args) {
EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
ServerBootstrap serverBootstrap = new ServerBootstrap();
try {
serverBootstrap.group(eventLoopGroup).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 HttpObjectAggregator(65535));
ch.pipeline().addLast(new SimpleChannelInboundHandler<FullHttpRequest>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
ByteBuf byteBuf = Unpooled.wrappedBuffer("Hello world!".getBytes(StandardCharsets.UTF_8));
FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuf);
fullHttpResponse.headers().set("Content-Type", "text/plain;charset=UTF-8");
fullHttpResponse.headers().set("Content-Length", byteBuf.readableBytes());
ctx.writeAndFlush(fullHttpResponse).addListener(ChannelFutureListener.CLOSE);
}
});
}
}).bind(8080).sync().channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
eventLoopGroup.shutdownGracefully();
}
}
}
这篇博客介绍了如何使用Java的Netty库,通过NIO事件循环组和ServerBootstrap创建一个简单的HTTP服务器,能发送'Hello World!'响应。它展示了如何初始化Channel、设置HTTP解析器和编码器,并在接收到请求后生成并返回HTTP响应。
679

被折叠的 条评论
为什么被折叠?



