Netty学习——实战篇4 Netty开发Http服务实战、ByteBuf使用、开发群聊系统 备份

 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(
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

geminigoth

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值