package com.ruoyi.dataInterchange.netty.server;
|
|
import com.ruoyi.dataInterchange.util.jtt809.decoder.Jtt809Decoder;
|
import com.ruoyi.dataInterchange.util.jtt809.encoder.Jtt809Encoder;
|
import io.netty.channel.ChannelHandler;
|
import io.netty.channel.ChannelInitializer;
|
import io.netty.channel.ChannelPipeline;
|
import io.netty.channel.socket.SocketChannel;
|
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
|
import io.netty.handler.timeout.IdleStateHandler;
|
import org.springframework.stereotype.Component;
|
|
import javax.annotation.Resource;
|
import java.util.concurrent.TimeUnit;
|
|
/**
|
* @author zhibing.pu
|
* @Date 2025/3/3 19:26
|
*/
|
@Component
|
@ChannelHandler.Sharable
|
public class NettyInitalizer extends ChannelInitializer<SocketChannel> {
|
|
|
|
@Override
|
protected void initChannel(SocketChannel socketChannel) throws Exception {
|
ChannelPipeline pipeline = socketChannel.pipeline();
|
// 解码器
|
pipeline.addLast("decoder", new Jtt809Decoder());
|
// 编码器
|
pipeline.addLast("encoder", new Jtt809Encoder());
|
// 空闲检测处理器 触发空闲状态事件 读空闲:5秒 写空闲:7秒 读写空闲:10秒
|
pipeline.addLast(new IdleStateHandler(5,7,3, TimeUnit.SECONDS));
|
// 处理器
|
pipeline.addLast("handler", new NettyHandle());
|
// 如果后期处理拆包粘包可以在这里处理
|
/** LineBasedFrameDecoder:以行为单位进行数据包的解码,使用换行符\n或者\r\n作为依据遇
|
到\n或者\r\n都认为是一条完整的消息。
|
DelimiterBasedFrameDecoder:以特殊的符号作为分隔来进行数据包的解码。
|
FixedLengthFrameDecoder:以固定长度进行数据包的解码。
|
LenghtFieldBasedFrameDecode:适用于消息头包含消息长度的协议(最常用)。
|
*/
|
pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
|
}
|
}
|