using DotNetty.Buffers; using DotNetty.Transport.Channels; using JSMachine.WMS.Common.Cache; using JSMachine.WMS.Common.Cache.Model; using JSMachine.WMS.Infrastructure.Helper; using JSMachine.WMS.Netty.NettyAsServer.Command; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reactive.Linq; using System.Threading; using System.Threading.Tasks; namespace JSMachine.WMS.Netty.NettyAsServer.Transport { public static class TransportManager { /// /// 已连接的客户端 /// key-ip 一个客户端仅允许一个连接 /// public static readonly ConcurrentDictionary DicClientChannels = new(); /// /// 移除有问题通道 /// /// public static void RemoveInActiveChannel(IChannelHandlerContext channel) { try { DicClientChannels .Where(p => p.Value == channel) .Select(p => p.Key) .ToList() ?.ForEach(p => DicClientChannels.Remove(p, out IChannelHandlerContext channelHandlerContext)); } catch (Exception ex) { LogHelper.Error($"移除有问题通道出错: {ex.Message} \n {ex.StackTrace}"); } } /// /// 指定客户端发送消息 /// /// /// /// public async static Task SendMsg(string ip, string msg) { var result = false; try { if (!DicClientChannels.ContainsKey(ip)) return result; IChannelHandlerContext channel = DicClientChannels[ip]; await channel.Channel.WriteAndFlushAsync(msg); result = true; } catch (Exception ex) { LogHelper.Error($"指定客户端发送消息出错: {ex.Message} \n {ex.StackTrace}"); } return result; } /// /// 发送广播消息 /// /// public static void BroadcastMsg(IByteBuffer messagePackage) { try { DicClientChannels.Keys.ToList().ForEach(async key => { await DicClientChannels[key].Channel.WriteAndFlushAsync(messagePackage); }); } catch (Exception ex) { LogHelper.Error($"发送广播消息出错: {ex.Message} \n {ex.StackTrace}"); } } /// /// 发送扫码命令并获取返回结果 /// /// 具体扫码器的IP /// public async static Task SendReadBarCodeCmd(string ip) { var barCodeInfo = new BarCodeInfo(); try { string msg = new BarCodeReadCmd().Msg; bool bRet = await SendMsg(ip, msg); if (!bRet) { LogHelper.Error($"向 {ip} 发送条码扫描命令失败"); return null; } DateTime sendTime = DateTime.Now; int count = 0; while (true) { count++; Thread.Sleep(100); barCodeInfo = GlobalMemoryCache.GetCach(ip); if (barCodeInfo == null || barCodeInfo.AddTime < sendTime) { if (count < 20) continue; else return null; } } } catch (Exception ex) { LogHelper.Error($"向 {ip} 发送条码扫描命令返回结果失败{ex.Message} \n {ex.StackTrace}"); } return barCodeInfo; } } }