78 lines
2.2 KiB
C#
78 lines
2.2 KiB
C#
using DotNetty.Transport.Channels;
|
|
using JSMachine.WMS.Infrastructure.Helper;
|
|
using JSMachine.WMS.Netty.Common.Util;
|
|
using JSMachine.WMS.Netty.NettyUdp.Command;
|
|
using JSMachine.WMS.Netty.NettyUdp.CommandHandler;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.ComponentModel.Composition;
|
|
using System.ComponentModel.Composition.Hosting;
|
|
using System.Reflection;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace JSMachine.WMS.Netty.NettyUdp.Transport
|
|
{
|
|
public class NettyUdpTransport
|
|
{
|
|
public IChannelHandlerContext ChannelHandlerContext;
|
|
public IPInfo RemoteIpInfo;
|
|
|
|
[ImportMany("NettyUdp")]
|
|
private List<BaseCmdhandler> AllCmds { get; set; }
|
|
|
|
private Lazy<CompositionContainer> _Container = new Lazy<CompositionContainer>(() =>
|
|
{
|
|
AggregateCatalog catalog = new();
|
|
catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
|
|
|
|
return new CompositionContainer(catalog);
|
|
});
|
|
|
|
public NettyUdpTransport(IChannelHandlerContext channel)
|
|
{
|
|
_Container.Value.ComposeParts(this);
|
|
|
|
ChannelHandlerContext = channel;
|
|
|
|
foreach (BaseCmdhandler cmd in AllCmds)
|
|
{
|
|
cmd.Channel = channel;
|
|
}
|
|
|
|
RemoteIpInfo = channel.ToIPInfo(AddressOnwer.Remote);
|
|
}
|
|
|
|
public Task ChannelReadHandle(string msg)
|
|
{
|
|
return Task.Run(async () =>
|
|
{
|
|
foreach (BaseCmdhandler cmd in AllCmds)
|
|
{
|
|
bool isMsgHasBeenHandled = await cmd.Handle(msg);
|
|
if (isMsgHasBeenHandled)
|
|
break;
|
|
}
|
|
});
|
|
}
|
|
|
|
public async Task<bool> WriteMsg(BaseCmd msg)
|
|
{
|
|
try
|
|
{
|
|
if (ChannelHandlerContext.Channel.Active)
|
|
{
|
|
await ChannelHandlerContext.Channel.WriteAndFlushAsync(msg);
|
|
return true;
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
LogHelper.Error($"向TCP通道写入数据失败,错误信息 {ex.Message}");
|
|
|
|
}
|
|
|
|
return false;
|
|
}
|
|
}
|
|
}
|