• Hello Netty


    Hello Netty 服务

    • 构建一对主从线程组

    • 定义服务器启动类

    • 为服务器设置Channel

    • 设置从线程池的助手类初初始化器

    • 监听启动和关闭服务器

    代码

    1.导入依赖

    <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-all</artifactId>
        <version>4.1.25.Final</version>
    </dependency>
    

    2.编写主从线程组启动类

    /**
     * @author: webin
     * @date: 2020/4/3 21:59
     * @description: 实现客户端发送一个请求,服务器会返回一个 hello netty
     * @version: 0.0.1
     */
    public class HelloServer {
    
        public static void main(String[] args) throws InterruptedException {
    
            // 定义一对线程组
            // 主线程组 用于接收客户端的连接,但是不做任何处理
            EventLoopGroup bossGroup = new NioEventLoopGroup();
            // 从线程组 主线程组会把任务丢给从线程组,从线程组去做事
            EventLoopGroup workerGroup = new NioEventLoopGroup();
    
            try {
                // netty服务器的创建,serverBootstrap是一个启动类
                ServerBootstrap serverBootstrap = new ServerBootstrap();
                serverBootstrap.group(bossGroup,workerGroup)    //设置主从线程组
                        .channel(NioServerSocketChannel.class) // 设置nio的双线通道
                        .childHandler(new HelloServerInitializer());                    // 用于处理workerGroup的线程
    
                // 启动server,并设置8088为启动端口,同时启动方式为同步
                ChannelFuture channelFuture = serverBootstrap.bind(8080).sync();// 设置同步
                // 用于监听关闭的channel
                channelFuture.channel().closeFuture().sync();
                System.out.println("关闭");
            } finally {
                // 关闭服务器
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        }
    }
    
    1. 定义初始化器
    /**
     * @author: webin
     * @date: 2020/4/3 22:31
     * @description: 初始化器,channel注册后,会执行里面相应的初始化方法
     * @version: 0.0.1
     */
    public class HelloServerInitializer extends ChannelInitializer<SocketChannel> {
    
        @Override
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            // 通过SocketChannel去获取对应的管道
            ChannelPipeline pipeline = socketChannel.pipeline();
            // HttpServerCodec是由netty自己提供的助手类,可以理解为拦截器
            // 当请求到服务器,我们需要做解码,响应到客户端需要编码
            pipeline.addLast("HttpServerCodec",new HttpServerCodec()); // 通过管道添加了一个handler
    
            pipeline.addLast("customHandler",new CustomHandler());
    
        }
    }
    
    1. 自定义处理器
    /**
     * @author: webin
     * @date: 2020/4/3 22:38
     * @description: 创建自定义助手类,
     *  SimpleChannelInboundHandler: 对于请求来讲,其实相当于入站
     * @version: 0.0.1
     */
    public class CustomHandler extends SimpleChannelInboundHandler {
    
        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
            System.out.println("channel .. 添加");
            super.handlerAdded(ctx);
        }
    
        /**
         * channel注册
         * @param ctx
         * @throws Exception
         */
        @Override
        public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
            System.out.println("channel ... 注册");
            super.channelRegistered(ctx);
        }
    
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            System.out.println("channel ... 连接");
            super.channelActive(ctx);
        }
    
    
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, Object o) throws Exception {
            // 获取channel
            Channel channel = ctx.channel();
            if (o instanceof HttpRequest)
                System.out.println(channel.remoteAddress());
    
            // 定义发送数据的消息
            ByteBuf content = Unpooled.copiedBuffer("hello, netty", CharsetUtil.UTF_8);
    
            // 构建一个http response
            FullHttpResponse 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());
            // 把响应刷新到客户端
            ctx.writeAndFlush(response);
        }
    
        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            System.out.println("channel ... 读取完毕");
            super.channelReadComplete(ctx);
        }
    
        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            System.out.println("channel ... 不活跃状态");
            super.channelInactive(ctx);
        }
    
        @Override
        public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
            System.out.println("channel ... 销毁");
            super.channelUnregistered(ctx);
        }
    
        @Override
        public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
            System.out.println("channel .. 移除");
            super.handlerRemoved(ctx);
        }
    
        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            System.out.println("channel ... 事件触发");
            super.userEventTriggered(ctx, evt);
        }
    
        @Override
        public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
            System.out.println("channel ... 可写可更改");
            super.channelWritabilityChanged(ctx);
        }
    
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            System.out.println("channel ... 捕获到异常");
            super.exceptionCaught(ctx, cause);
        }
    }
    
  • 相关阅读:
    haproxy 看到的是https,后台是http的原因
    frontend http 前端名字定义问题
    frontend http 前端名字定义问题
    Git学习总结(3)——代码托管平台简介
    Git学习总结(3)——代码托管平台简介
    Git学习总结(3)——代码托管平台简介
    [置顶] 开源史上最成功的8个开源产品
    [置顶] 开源史上最成功的8个开源产品
    [置顶] 开源史上最成功的8个开源产品
    Maven学习总结(十一)——Maven项目对象模型pom.xml文件详解
  • 原文地址:https://www.cnblogs.com/smallwolf/p/12630881.html
Copyright © 2020-2023  润新知