代码实现
前情提要
- 如果你想采取行动 FullHttpRequest 你需要 HttpObjectAggregator 在管道中,负责组装这些部件。
- 没有这个你会收到
HttpRequest
,HttpContent
,LastHttpContent
表示HTTP消息部分的实例。每一个都需要处理,而HTT请求
标记新HTTP消息的开始,并最后一个httpcontent
结束了。
- 服务端
package com.wyk.day02;
import com.wyk.day01.SeverHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
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.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
/**
* @program: NettyCode
* @description:
* @author: WYK
* @create: 2021-08-30 21:29
**/
public class SeverHttp {
public static void main(String[] args) throws InterruptedException {
NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
NioEventLoopGroup workGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup,workGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline= socketChannel.pipeline();
pipeline.addLast(new HttpServerCodec());//http编解码
pipeline.addLast("httpAggregator",new HttpObjectAggregator(512*1024)); // http 消息聚合器
pipeline.addLast(new SeverHandler1());
}
});
ChannelFuture future = bootstrap.bind(8088).sync();
future.addListener(future1 -> {
if (future1.isSuccess()){
System.out.println("服务端准备就绪");
}
});
future.channel().closeFuture().sync();
}finally {
bossGroup.shutdownGracefully();
workGroup.shutdownGracefully();
System.out.println("服务器结束");
}
}
}
- 服务端Handler
package com.wyk.day02;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
/**
* @program: NettyCode
* @description:
* @author: WYK
* @create: 2021-08-30 21:36
**/
public class SeverHandler1 extends SimpleChannelInboundHandler<FullHttpRequest> {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest)
throws Exception {
System.out.println("收到请求");
//获取请求uri
String uri = fullHttpRequest.uri();
String msg = "<html><head><title>test</title></head><body>你请求uri为:" + uri+"</body></html>";
//ByteBuf buf = Unpooled.copiedBuffer("你好浏览器",CharsetUtil.UTF_8);
//创建http响应
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
HttpResponseStatus.OK, Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8));
//设置头信息
response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/html;charset=utf-8");
//发送消息到浏览器
channelHandlerContext.writeAndFlush(response);
}
}