• 基于netty的HTTP服务


    1.服务端

    public class MyServer {
        public static void main(String[] args) throws Exception {
            //创建两个线程组 bossGroup 和 workerGroup,bossGroup 处理连接请求 ,
            // bossGroup 只是处理连接请求 ,workerGroup完成真正的和客户端业务处理
            EventLoopGroup bossGroup = new NioEventLoopGroup(1);
            EventLoopGroup workerGroup = new NioEventLoopGroup();
            try {
                //创建服务器端的启动对象,配置参数
                ServerBootstrap serverBootstrap = new ServerBootstrap();
                // DIYChannelInitializer自定义channel初始化类
                serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new DIYChannelInitializer());
                //监听
                ChannelFuture channelFuture = serverBootstrap.bind(6988).sync();
                //"关闭通道"监听
                channelFuture.channel().closeFuture().sync();
            } finally {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        }
    }

    2.自定义channel初始化类

    //自定义channel初始化类
    public class DIYChannelInitializer extends ChannelInitializer<SocketChannel> {
    
    
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            //得到管道
            ChannelPipeline pipeline = ch.pipeline();
            //添加Netty提供的Http编码器
            pipeline.addLast("MyHttpServerCodec", new HttpServerCodec());
            //添加自定义的处理类
            pipeline.addLast("MyHttpServerHandler", new HttpServerHandler());
            System.out.println("ok............");
        }
    
    }

    3.自定义处理类

    public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
            if (msg instanceof HttpRequest) {//判断是否是http请求
                System.out.println("msg的类型:" + msg.getClass());
                System.out.println("客户端地址:" + ctx.channel().remoteAddress());
                //准备给浏览器回复的信息
                //注释:要用CharsetUtil.UTF_16,此处用utf_8在谷歌浏览器失效
                ByteBuf content = Unpooled.copiedBuffer("hello, 我是服务器", CharsetUtil.UTF_16);
    
                //浏览器页面响应
                /*
                 * HttpVersion.HTTP_1_1:   http版本
                 * HttpResponseStatus.OK:  http响应状态码
                 * */
                FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
                //http响应头
                HttpHeaders headers = response.headers();
                //设置内容类型
                headers.set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
                //设置内容长度
                headers.set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
                //开始给浏览器回复消息
                ctx.writeAndFlush(response);
    
            }
        }
    }
  • 相关阅读:
    第二次作业
    复盘一个商品期货的通用模型
    C#如何获取枚举(Enum)变量的值
    [C#]Socket通信BeginReceive异步接收数据何时回调Callback
    [C#]浮点数除零无法捕获异常的解决办法
    js对字符串进行编码方法总结
    web最全资源网址
    简单粗暴地理解js原型链--js面向对象编程
    常见前端九十道面试题及答案-韩烨
    C语言文件读写,复制
  • 原文地址:https://www.cnblogs.com/hyy9527/p/13064958.html
Copyright © 2020-2023  润新知