Netty对Http提供了非常丰富的支持,让我们可以针对自己的需求实现需要的Http服务器。
1、HttpServer实现
HttpServer实现源码:
public class HttpServer {
public static void main(String[] args){
HttpServer.startServer(9999);
}
public static void startServer(int port){
//负责接收客户端连接
EventLoopGroup boosGroup = new NioEventLoopGroup();
//处理连接
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(boosGroup,workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline channelPipeline = ch.pipeline();
//负载http 请求编码解码
channelPipeline.addLast(new HttpServerCodec());
//实际处理请求
channelPipeline.addLast(new HttpRequestHandler());
}
});
//绑定端口号
ChannelFuture channelFuture = bootstrap.bind(port).sync();
channelFuture.channel().closeFuture().sync();
}catch(Exception e){
e.printStackTrace();
}finally {
boosGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
Http协议的编解码主要由HttpServerCodec实现。
2、HttpRequestHandler实现
HttpRequestHandler实现源码:
public class HttpRequestHandler extends SimpleChannelInboundHandler<HttpObject> {
@Override
protected void messageReceived(ChannelHandlerContext ctx, HttpObject httpObject) throws Exception {
if(httpObject instanceof HttpRequest){
HttpRequest request = (HttpRequest) httpObject;
System.out.println("接收到请求: "+ request.method() + ",url=" + request.uri());
//设置返回内容
ByteBuf content = Unpooled.copiedBuffer("Hello World\n", CharsetUtil.UTF_8);
//创建响应
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK,content);
response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
response.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes() + "");
ctx.writeAndFlush(response);
}
}
}
3、测试结果
3.1、启动服务器:
打开浏览器,输入以下url:http://127.0.0.1:9999/test/http?name=zhaozhou