1 Netty开发Http服务实战
(1)Netty服务器监听8000端口,浏览器发出请求“http://localhost:8000”
(2)服务器可以回复消息给客户端,“你好,我是服务器”,并对特定请求资源进行过滤。
HttpServer.java
public class HttpServer {
public static void main(String[] args) throws Exception{
//1 创建bossGroup和workerGroup线程组
NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
try {
//创建ServerBootstrap对象
ServerBootstrap serverBootstrap = new ServerBootstrap();
//配置ServerBootstrap对象
serverBootstrap.group(bossGroup,workerGroup) // 设置两个线程组
.channel(NioServerSocketChannel.class) //使用NIOServerSocketChannel作为服务端的通道
.childHandler(new ServerInitializer()); //设置Handler
//绑定端口并异步启动
ChannelFuture channelFuture = serverBootstrap.bind(8000).sync();
// 监听 关闭通道事件
channelFuture.channel().closeFuture().sync();
}finally {
//关闭线程组
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
HttpServerHandler.java
/*
SimpleChannelInboundHandler 是 ChannelInboundHandlerAdapter的子类
HttpObject 封装了客户端和服务端相互通讯的数据
*/
@Slf4j
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
//读取客户端数据
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
log.info("对应的channel是:{},pipeline是:{},通过pipeline获取channel是:{}",ctx.channel(),ctx.pipeline(),ctx.pipeline().channel());
log.info("当前ctx的handler是:{}",ctx.handler());
//获取
//判断 msg 是不是HttpRequest请求
if(msg instanceof HttpRequest){
log.info("ctx类型是:{}",ctx.getClass());
log.info("pipeline的hashcode是:{},HttpServerHandler的 hashcode是:",ctx.pipeline().hashCode(),this.hashCode());
log.info("msg类型是:{}",msg.getClass());
log.info("客户端地址是:{}",ctx.channel().remoteAddress());
//获取httpRequest
HttpRequest request = (HttpRequest) msg;
//获取uri
String uri = request.uri();
//过滤指定的资源
if("/favicon.ico".equals(uri)){
log.info("请求了 favicon.ico, 不做响应");
return;
}
//回复信息到浏览器(http协议)
ByteBuf content = Unpooled.copiedBuffer("hello,我是服务器",CharsetUtil.UTF_8);
//构造一个http的响应
FullHttpResponse response = new DefaultFullHttpResponse(

最低0.47元/天 解锁文章
1343

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



