站务联系

Netty从没听过到入门 -- 服务器端详解(2)

发布时间:2021-03-31   来源:网络整理    
字号:

比如:

public class childChannelHandler extends ChannelInitializer{
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new OutboundHandler1());  //handler1
            ch.pipeline().addLast(new OutboundHandler2());  //handler2
            ch.pipeline().addLast(new InboundHandler1());   //handler3
            ch.pipeline().addLast(new InboundHandler2());   //handler4
        }
    }

以上4个handler的实际执行次序分别为handler3 -> handler4 -> handler2 ->handler1

如果在handler4下方加上OutboundHandler3,那么这个handler是不会被执行至的。

3、同步等候绑定指定端口

此处可多次执行bind句子绑定多个端口

    ChannelFuture channelFuture = serverBootstrap.bind(8080).sync();
    channelFuture = serverBootstrap.bind(8081).sync();
    ...    

4、同步等候服务器关掉信息

  channelFuture.channel().closeFuture().sync();

5、最后关掉此前开辟的两个线程池

  bossGroup.shutdownGracefully();
  workerGroup.shutdownGracefully();

最后整段服务器代码如下:

package Netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.AdaptiveRecvByteBufAllocator;
public class NettyServer {
    public void startServerInPort(int port) throws Exception{
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try{
            //设置启动辅助类
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)//设置channel类型
            .childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(64, 2048, 65536))
            .childHandler(new childChannelHandler());//选择执行handler
            
            //阻塞等待服务器完全启动
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            
            channelFuture.channel().closeFuture().sync();
        }finally{
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
    public class childChannelHandler extends ChannelInitializer{
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            //TODO 添加各种功能handler 消息加解密,消息规范检测,构建返回码
            ch.pipeline().addLast(new NettyServerHandler());
        }
    }
}

图说天下

×
二维码生成