NettyInitializer.java
1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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 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());
//入站解码
//channel.pipeline().addLast(new MyByteToLongDecoder2());
//出站编码
channel.pipeline().addLast(new MyByteEncoder());
//websocket协议本身是基于http协议的,所以这边也要使用http解编码器
channel.pipeline().addLast(new HttpServerCodec());
//以块的方式来写的处理器
channel.pipeline().addLast(new ChunkedWriteHandler());
channel.pipeline().addLast(new HttpObjectAggregator(1024 * 1024));
//WebSocket 数据压缩 ,压缩来自 client
channel.pipeline().addLast(new WebSocketServerCompressionHandler());
channel.pipeline().addLast(new WebSocketServerProtocolHandler("/ws", "WebSocket", true, 65536 * 10));
channel.pipeline().addLast(new NettyServerHandler());//自定义消息处理类
}
}