NettyInitializer.java 1.93 KB
package cn.com.glsx.notify.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@ChannelHandler.Sharable
public class NettyInitializer extends ChannelInitializer {

    @Override
    protected void initChannel(Channel channel) throws Exception {
        //创建一个通道初始化对象(匿名对象)
        //给pipeline设置处理器
        //可以使用一个集合管理 SocketChannel,再推送消息时,可以将业务加入到各个channel对应的NIOEventLoop的taskQueue
        //或者ScheduleTaskQueue
        log.info("客户SocketChannel hashcode=" + channel.hashCode());

        //websocket协议本身是基于http协议的,所以这边也要使用http解编码器
        channel.pipeline().addLast(new HttpServerCodec());
        //以块的方式来写的处理器
        channel.pipeline().addLast(new ChunkedWriteHandler());
        channel.pipeline().addLast(new HttpObjectAggregator(1024 * 1024));
        channel.pipeline().addLast(new IdleStateHandler(10, 0, 0));
        //WebSocket 数据压缩 ,压缩来自 client
        channel.pipeline().addLast(new WebSocketServerCompressionHandler());
        channel.pipeline().addLast(new WebSocketServerProtocolHandler("/ws", "WebSocket", true, 65536 * 10));

        //自定义消息处理类
        channel.pipeline().addLast(new NettyTokenHandler());
        channel.pipeline().addLast(new NettyServerHandler());
    }
}