常常我們需要開一個服務單,對接不同的客戶端,編碼器、解碼器等都不同,需要針對不同IP新增不同的處理器。
public class CustomInitializer :Channellnitializer<lSocketChannel>
{
Action<string,string>_dealMsgAction; lServer_server;
public CustomInitializer(Action<string,string>dealMsgAction,IServer server)
{
dealMsgAction = dealMsgAction;
_server = server;
}
protected override void InitChannel(lSocketChannel channel)
{
var ip = (channel.RemoteAddress as IPEndPoint).IPEndPointToString();
IChannelPipeline pipeline =channel.Pipeline;
if (ip== SystemSettingViewModel.Instance.SystemSetting.PLCIP)
{
pipeline.AddLast("modbus", new ModbusEncoder();
}
else
{
pipeline.AddLast(new LoggingHandler("SRV-CONN"));
pipeline.AddLast(new IdleStateHandler(10,10,30));//加心跳
pipeline.AddLast("encoder", new TIvEncoder();
pipeline.AddLast("decoder", new LengthFieldBasedFrameDecoder(DotNetty.Buffers.ByteOrder.LittleEndian, int.MaxValue, 4,4, 0,8,true));
pipeline.AddLast("handler", new SocketServerHandler(_dealMsgAction,_server));
}
}
}