Netty详解

public class Server {
    public static void main(String[] args) throws InterruptedException {
        // 1. Netty服务器的引导类
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        // 2. 声明此次通信所用的Channel
        serverBootstrap.channel(NioServerSocketChannel.class);
        // 3. 用于逻辑控制的(这是开发人员主要做的事)
        serverBootstrap.handler(new LoggingHandler(LogLevel.INFO));
        // 4. 相当于是线程池,内部维护一组线程,每个线程处理多个Channel上的事件(Channel仅对应一个线程)
        NioEventLoopGroup group = new NioEventLoopGroup();
        try{
            serverBootstrap.group(group);
            // 5. handler在服务器初始化就会执行,childHandler会在客户端成功connect后才执行(服务器端特有)
            serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    // 5.1 Netty中的事件传播机制以及数据的过滤、写出都是由其负责
                    //① pipeline在创建Channel的时候被创建
                    //② pipeline节点数据结构:ChannelHandlerContext的双向链表
                    //③ pipeline中的两大哨兵:head和tail
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(new OrderFrameDecoder());
                    pipeline.addLast(new OrderFrameEncoder());
                    pipeline.addLast(new OrderProtocolEncoder());
                    pipeline.addLast(new OrderProtocolDecoder());
                    pipeline.addLast(new LoggingHandler(LogLevel.INFO));
                    pipeline.addLast(new OrderServerProcessHandler());
                }
            });
            ChannelFuture channelFuture = serverBootstrap.bind(8090).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
}

Netty详解

上一篇:[GXYCTF2019]禁止套娃 1


下一篇:jQuery 选择器