netty-http服务demo
服务端
NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap
.group(bossGroup,workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new TestServerInitializer());
ChannelFuture channelFuture = bootstrap
.bind(12345).sync();
channelFuture.channel().closeFuture().sync();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
通道初始化对象
public class TestServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
//向管道加入处理器
//得到管道
ChannelPipeline pipeline = socketChannel.pipeline();
//加入一个netty提供的httpServerCodec(code,decoder的缩写)
//HttpServerCodec是netty提供的处理http的编解码器
pipeline.addLast("myCodec",new HttpServerCodec());
//增加一个自定义的处理器
pipeline.addLast("myServerHandler",new TestServerHandler());
}
}
控制器
//SimpleChannelInboundHandler是ChannelInboundHandlerAdapter的子类
//HttpObject 客户端和服务器端相互通信的数据被封装成HttpObject
public class TestServerHandler extends SimpleChannelInboundHandler<HttpObject> {
//读取客户端数据
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
//判断msg是不是一个HttpRequest
if (msg instanceof HttpRequest){
System.out.println("msg类型:"+msg.getClass());
System.out.println("客户端地址:"+ctx.channel().remoteAddress());
//过滤请求
HttpRequest httpRequest = (HttpRequest) msg;
//获取uri
URI uri = new URI(httpRequest.uri());
if ("/favicon.ico".equals(uri.getPath())){
System.out.println("此资源不做响应...");
return;
}
//回复信息给浏览器(http协议)
ByteBuf content = Unpooled.copiedBuffer("hello,我是服务器", CharsetUtil.UTF_16);
//构造一个http的响应,即httpResponse
DefaultFullHttpResponse 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());
//将构建好的response返回
ctx.writeAndFlush(response);
}
}
}