Browse Source

更换tcp通讯库

刘彬 1 year ago
parent
commit
a946dfa99c

+ 13 - 1
Toolkit/App.config

@@ -1,6 +1,18 @@
-<?xml version="1.0" encoding="utf-8" ?>
+<?xml version="1.0" encoding="utf-8"?>
 <configuration>
     <startup> 
         <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
     </startup>
+  <runtime>
+    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
+      <dependentAssembly>
+        <assemblyIdentity name="System.Threading.Tasks.Extensions" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-4.2.0.1" newVersion="4.2.0.1" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="TouchSocket.Core" publicKeyToken="d6c415a2f58eda72" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-3.1.11.0" newVersion="2.0.15" />
+      </dependentAssembly>
+    </assemblyBinding>
+  </runtime>
 </configuration>

+ 2 - 5
Toolkit/App.xaml.cs

@@ -9,6 +9,7 @@ using System.Data;
 using System.Linq;
 using System.Threading.Tasks;
 using System.Windows;
+using Toolkit.Core;
 using Toolkit.View;
 using Toolkit.ViewMode;
 
@@ -27,9 +28,6 @@ namespace Toolkit
             window.Loaded += (sender, args) =>
             {
                 var manager = this.Container.Resolve<IRegionManager>();
-
-               
-
             };
 
 
@@ -63,8 +61,7 @@ namespace Toolkit
         protected override void RegisterTypes(IContainerRegistry containerRegistry)
         {
             containerRegistry.RegisterForNavigation<MainWindow, MainWindowViewMode>();
-            containerRegistry.RegisterForNavigation<TcpTrigger, TcpTriggerViewMode>();
-            containerRegistry.RegisterForNavigation<TcpWrite, TcpWriteViewMode>();
+            containerRegistry.RegisterSingleton<Management>();
         }
 
 

+ 284 - 0
Toolkit/Core/Management.cs

@@ -0,0 +1,284 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net.Sockets;
+using System.Reflection;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using Toolkit.Log4;
+using Toolkit.Tcp;
+using TouchSocket.Core;
+using TouchSocket.Sockets;
+
+namespace Toolkit.Core
+{
+    public class Management
+    {
+
+
+        public Management() { }
+
+        public string MsgSplit(string str)
+        {
+
+            StringBuilder sb = new StringBuilder();
+            try
+            {
+
+                str = str.Trim();
+                string[] strs = str.Split(';');
+
+                MesMsg msg = new MesMsg();
+
+                Type personType = msg.GetType();
+
+                PropertyInfo[] properties = msg.GetType().GetProperties();
+
+                for ( int i = 0; i < strs.Length; i++ )
+                {
+                    for ( int j = 0; j < properties.Length; j++ )
+                    {
+                        string temp=strs[ i ].Split(':')[ 0 ].ToString();
+                        if ( temp.Trim() == properties[ j ].Name )
+                        {
+                            string []splits=strs[ i ].Split(':');
+                            string splitst="";
+                            //if ( splits.Length > 2 )
+                            //{
+                            //    string[] newArray = new string[splits.Length - 1];
+                            //    Array.Copy(splits, 1, newArray, 0, newArray.Length);
+                            //    splits[ 0 ] = "";
+                            //    splitst = string.Join(":", newArray);
+
+                            //}
+                            //else 
+                            //{
+                            splitst = strs[ i ].Split(':')[ 1 ];
+                            // }
+                            properties[ j ].SetValue(msg, splitst);
+                            break;
+                        }
+                    }
+                }
+
+
+                sb.Append(msg.tasknum + ":|:");
+                sb.Append(msg.client_name + ":|:");
+                sb.Append(msg.datetime + ":|:");
+                sb.Append(msg.phone + ":|:");
+                string[] items = msg.items.Trim().Split(']');
+                string amount = "";
+                //string amountT="0";
+                for ( int i = 0; i < 9; i++ )
+                {
+                    if ( items.Length > i )
+                    {
+                        if ( items[ i ].Length == 0 )
+                        {
+                            sb.Append(" " + ":|:");
+                            sb.Append(" " + ":|:");
+                            sb.Append(" " + ":|:");
+                            sb.Append(" " + ":|:");
+                            continue;
+                        }
+                        int startindex = items[i].IndexOf("<") + 1;
+                        int stopindex = items[i].IndexOf(">") - startindex;
+                        amount = items[ i ].Substring(startindex, stopindex);
+                        items[ i ] = items[ i ].Substring(items[ i ].IndexOf(">") + 1);
+                        startindex = items[ i ].IndexOf("<") + 1;
+                        stopindex = items[ i ].IndexOf(">") - startindex;
+                        string currcycode = items[i].Substring(startindex, stopindex);
+                        //items:[amount<300>currcycode<USD>itdetail<100 | 1,50 | 4 >][...];
+                        items[ i ] = items[ i ].Substring(items[ i ].IndexOf(">") + 1);
+                        string[] itdetail = items[i].Split(',');
+                        for ( int j = 0; j < itdetail.Length; j++ )
+                        {
+                            if ( j != 0 )
+                                i++;
+                            sb.Append(currcycode + ":|:");
+                            startindex = itdetail[ j ].IndexOf("<") + 1;
+                            stopindex = itdetail[ j ].IndexOf("|") - startindex;
+                            sb.Append(( itdetail[ j ].Substring(startindex, stopindex) ) + ":|:");
+                            string numStr=itdetail[ j ].Substring(startindex, stopindex);
+                            int num=0;
+                            if ( numStr != "?" )
+                                num = Convert.ToInt32(numStr);
+                            startindex = itdetail[ j ].IndexOf("|") + 1;
+                            stopindex = itdetail[ j ].IndexOf(">");
+                            if ( stopindex == -1 )
+                            {
+
+                                if ( itdetail[ j ].Substring(startindex) == "?" )
+                                {
+                                    sb.Append("?:|:");
+                                    sb.Append("?:|:");
+                                }
+                                else
+                                {
+                                    int count = Convert.ToInt32(itdetail[ j ].Substring(startindex));
+                                    sb.Append(count + ":|:");
+                                    sb.Append(num * count + ":|:");
+                                }
+                            }
+                            else
+                            {
+
+                                if ( itdetail[ j ].Substring(startindex, stopindex - startindex) == "?" )
+                                {
+                                    sb.Append("?:|:");
+                                    sb.Append("?:|:");
+
+                                }
+                                else
+                                {
+                                    int count = Convert.ToInt32(itdetail[ j ].Substring(startindex, stopindex - startindex));
+                                    sb.Append(count + ":|:");
+                                    sb.Append(num * count + ":|:");
+                                }
+
+
+
+
+
+                            }
+                        }
+                        //if ( amount == "?" )
+                        //{
+                        //    amountT ="?";
+                        //}
+                        //else 
+                        //{
+                        //    amountT = (Convert.ToDouble(amount)+ Convert.ToDouble(amountT)).ToString();
+                        //}
+
+                    }
+                    else
+                    {
+                        sb.Append(" " + ":|:");
+                        sb.Append(" " + ":|:");
+                        sb.Append(" " + ":|:");
+                        sb.Append(" " + ":|:");
+                    }
+                }
+                //[amount<500>currcycode<CNY>]
+                string []currcycodes=msg.suminfo.Split("currcycode");
+                string []amounts=msg.suminfo.Split("amount");
+                for ( int i = 0; i < currcycodes.Length; i++ )
+                {
+
+                }
+               
+                sb.Append(msg.suminfo + ":|:");
+                sb.Append(msg.recv_date + ":|:");
+                sb.Append(msg.deal_name + ":|:");
+                sb.Append(msg.tasknum + ":|:");
+                sb.Append(msg.dep_name + ":|:");
+                sb.Append(msg.packinfo + ":|:");
+                //sb.Append(msg.packno + ":|:");
+                //sb.Append(msg.totalpack + ":|:");
+                if ( msg.taskstatus == "0" )
+                {
+                    sb.Append("正常");
+                }
+                else
+                {
+                    sb.Append("异常");
+                }
+                string oldstr=sb.ToString();
+                string newstr=oldstr.Replace(":|:",",");
+                string []sbs=newstr.Split(",");
+                string logprint="";
+                for ( int i = 0; i < sbs.Length; i++ )
+                {
+                    logprint += "    " + ( i + 1 ) + ":" + sbs[ i ];
+                }
+                LogHelper.Info(logprint);
+
+            }
+            catch ( Exception ex )
+            {
+                LogHelper.error.Error("解析异常", ex);
+                return "Err";
+            }
+
+
+            return sb.ToString();
+        }
+
+
+        public byte[] GetData(string NowSendData, int printcount = 1, int autostop = 0, int encode = 1)
+        {
+            string sends = "";
+            byte[] endbyte = new byte[] { 00, 00, 03, 04 };
+
+
+            byte[] VerBin = new byte[10000];
+            //计算校验字节。
+            byte VerByte = 0;
+            List<byte> CRCBuffer = new List<byte>();
+            CRCBuffer.Add(0x1D);                                      //起始
+            CRCBuffer.Add(( byte ) ( printcount & 0xff ));
+            CRCBuffer.Add(( byte ) ( ( printcount & 0xff00 ) >> 8 ));
+            CRCBuffer.Add(( byte ) ( ( printcount & 0xff0000 ) >> 16 ));
+            CRCBuffer.Add(( byte ) ( ( printcount & 0xff000000 ) >> 24 ));
+
+            if ( autostop == 0 )
+                CRCBuffer.Add(0x0A);
+            else
+                CRCBuffer.Add(0x0B);
+            encode = 1;     //220904统一采用utf8格式发送,解决部分gb2312乱码(二维码中)
+            switch ( encode )
+            {
+                case 0:
+                    VerBin = System.Text.Encoding.GetEncoding("gb2312").GetBytes(NowSendData);
+                    CRCBuffer.Add(0xC1);
+                    break;
+                case 1:
+                    VerBin = System.Text.Encoding.UTF8.GetBytes(NowSendData);
+                    CRCBuffer.Add(0xC2);
+                    break;
+                case 2:
+                    VerBin = System.Text.Encoding.Unicode.GetBytes(NowSendData);
+                    CRCBuffer.Add(0xC3);
+                    break;
+            }
+
+            CRCBuffer.AddRange(VerBin);                               //数据
+            VerByte = CRC8(CRCBuffer.ToArray());
+            CRCBuffer.Add(VerByte);
+            CRCBuffer.AddRange(endbyte);
+            byte[] sendbuff = CRCBuffer.ToArray();
+
+
+
+            return sendbuff;
+
+        }
+
+
+
+
+        public static byte CRC8(byte[] buffer)
+        {
+            byte crc = 0;
+            for ( int j = 0; j < buffer.Length; j++ )
+            {
+                crc ^= buffer[ j ];
+                for ( int i = 0; i < 8; i++ )
+                {
+                    if ( ( crc & 0x01 ) != 0 )
+                    {
+                        crc >>= 1;
+                        crc ^= 0x8c;
+                    }
+                    else
+                    {
+                        crc >>= 1;
+                    }
+                }
+            }
+            return crc;
+        }
+    }
+}

+ 1 - 1
Toolkit/Log4/LogHelper.cs

@@ -20,7 +20,7 @@ namespace Toolkit.Log4
                 Console.WriteLine(info);
             }
         }
-        public static readonly log4net.ILog error = log4net.LogManager.GetLogger("LogError");
+        public static readonly log4net.ILog error = log4net.LogManager.GetLogger("LogError"); 
         private static void Error(string info, Exception exception)
         {
             if (error.IsErrorEnabled)

+ 0 - 82
Toolkit/MainWindow.xaml

@@ -1,82 +0,0 @@
-<Window x:Class="Toolkit.MainWindow"
-        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
-        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
-        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
-        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
-        xmlns:local="clr-namespace:Toolkit"
-        xmlns:prism="http://prismlibrary.com/"
-        prism:ViewModelLocator.AutoWireViewModel="True"
-        mc:Ignorable="d"
-        Background="White"
-        Title="打印机通讯" Height="450" Width="800">
-    <Grid>
-        <Grid.RowDefinitions>
-            <RowDefinition Height="Auto"></RowDefinition>
-            <RowDefinition Height="*"></RowDefinition>
-        </Grid.RowDefinitions>
-        
-        <Grid Grid.Row="0">
-            <Grid.ColumnDefinitions>
-                <ColumnDefinition Width="auto"/>
-                <ColumnDefinition Width="auto"/>
-                <ColumnDefinition Width="*"/>
-            </Grid.ColumnDefinitions>
-
-            <Grid Grid.Column="0">
-                 <StackPanel>
-                    <ItemsControl Name="ToolItems">
-                        
-                    </ItemsControl>
-                </StackPanel>
-            </Grid>
-
-            <Grid Grid.Column="1">
-                <Grid.ColumnDefinitions>
-                    <ColumnDefinition Width="auto"/>
-                    <ColumnDefinition Width="auto"/>
-                    <ColumnDefinition Width="auto"/>
-                    <ColumnDefinition Width="auto"/>
-                    <ColumnDefinition Width="auto"/>
-                    <ColumnDefinition Width="auto"/>
-                    <ColumnDefinition Width="auto"/>
-                    <ColumnDefinition Width="auto"/>
-                    <ColumnDefinition Width="auto"/>
-                    <ColumnDefinition Width="auto"/>
-                </Grid.ColumnDefinitions>
-                <StackPanel Grid.Column="0" >
-
-                    <ItemsControl Name="TaskItems1" ItemsSource="{Binding Items}">
-                            <ItemsControl.ItemsPanel>
-                            <ItemsPanelTemplate>
-                                <StackPanel Orientation="Horizontal"/>
-                            </ItemsPanelTemplate>
-                        </ItemsControl.ItemsPanel>
-                        </ItemsControl>
-                           </StackPanel>
-                <StackPanel Grid.Column="1"></StackPanel>
-                <StackPanel Grid.Column="2"></StackPanel>
-                <StackPanel Grid.Column="3"></StackPanel>
-                <StackPanel Grid.Column="4"></StackPanel>
-                <StackPanel Grid.Column="5"></StackPanel>
-                <StackPanel Grid.Column="6"></StackPanel>
-                <StackPanel Grid.Column="7"></StackPanel>
-                <StackPanel Grid.Column="8"></StackPanel>
-                <StackPanel Grid.Column="9"></StackPanel>
-            </Grid>
-
-            <Grid Grid.Column="2">
-               
-            </Grid>
-        </Grid>
-
-        
-        <Grid Grid.Row="1">
-            <RichTextBox Name="LogShow"
-                         Background="White"
-                         Foreground="Black"
-                         VerticalScrollBarVisibility="Visible">
-            </RichTextBox>
-
-        </Grid>
-    </Grid>
-</Window>

+ 354 - 0
Toolkit/Tcp/BgCommunicate.cs

@@ -0,0 +1,354 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using TouchSocket.Sockets;
+using System.ComponentModel;
+using TouchSocket.Core;
+
+
+namespace Toolkit.Tcp
+{
+    public class BgCommunicate:INotifyPropertyChanged
+    {
+        private IWaitingClient<TouchSocket.Sockets.SocketClient> WaitClientServer;
+        public TcpService TcpService { get; private set; }
+
+        TouchSocketConfig Config;
+
+        public event Action<SocketClient, ConnectedEventArgs> ConnectedEvent;
+        public event Action<SocketClient, DisconnectEventArgs> DisconnectedEvent;
+        public event Action<SocketClient, string> ReceivedEvent;
+        public event Action<SocketClient, string> SendEvent;
+        public event PropertyChangedEventHandler PropertyChanged;
+
+       
+
+        public int ClientCount { get => TcpService.Count; }
+
+        public BgCommunicate()
+        {
+            Config = new TouchSocketConfig();
+            TcpService = new TcpService();
+
+            var config = new TouchSocketConfig();
+            config.SetListenIPHosts(new IPHost[] { new IPHost(503) }); //同时监听两个地址//503
+
+            config.SetTcpDataHandlingAdapter(() => { return new NormalDataHandlingAdapter(); });       ////亦或者省略\r\n,但此时调用方不能高速调用,会粘包
+            //载入配置
+            TcpService.Setup(config);
+
+            /////有客户端成功连接
+            TcpService.Connected = ConnectedVoid;
+            //有客户端断开连接
+            TcpService.Disconnected = DisconnectedVoid;
+            //从客户端收到信息
+            TcpService.Received = ReceivedVoid;
+        }
+
+        /// <summary>
+        /// 启动监听
+        /// </summary>
+        public void StartListening()
+        {
+            TcpService.Start();
+        }
+
+        /// <summary>
+        /// 停止监听
+        /// </summary>
+        public void StopListening()
+        {
+            TcpService.Stop();
+        }
+
+        public void Dispose()
+        {
+            TcpService.Stop();
+            TcpService.Dispose();
+        }
+
+        #region 事件接收
+        /// <summary>
+        /// 有客户端成功连接
+        /// </summary>
+        /// <param name="client"></param>
+        /// <param name="e"></param>
+        /// <returns></returns>
+        private Task ConnectedVoid(SocketClient client, ConnectedEventArgs e)
+        {
+            //调用CreateWaitingClient获取到IWaitingClient的对象。
+            WaitClientServer = client.CreateWaitingClient(new WaitingOptions()
+            {
+                FilterFunc = response => //设置用于筛选的fun委托,当返回为true时,才会响应返回
+                {
+                    return true;
+
+                    //if (response.Data.Length == 1)
+                    //{
+                    //    return true;
+                    //}
+                    //return false;
+                }
+            });
+            ConnectedEvent?.Invoke(client, e);
+            return EasyTask.CompletedTask;
+        }
+        /// <summary>
+        /// 有客户端断开连接
+        /// </summary>
+        /// <param name="client"></param>
+        /// <param name="e"></param>
+        /// <returns></returns>
+        private Task DisconnectedVoid(SocketClient client, DisconnectEventArgs e)
+        {
+            DisconnectedEvent?.Invoke(client, e);
+            if ( WaitClientServer != null )
+            {
+                if ( WaitClientServer.Client.Id == client.Id )
+                {
+                    if ( TcpService.Count > 0 )
+                    {
+                        WaitClientServer = ( ( SocketClient ) ( TcpService.SocketClients.GetClients().ElementAt(0) ) ).CreateWaitingClient(new WaitingOptions()
+                        {
+                            FilterFunc = response => //设置用于筛选的fun委托,当返回为true时,才会响应返回
+                            {
+                                return true;
+
+                                //if (response.Data.Length == 1)
+                                //{
+                                //    return true;
+                                //}
+                                //return false;
+                            }
+                        });
+                    }
+                }
+            }
+            return EasyTask.CompletedTask;
+        }
+        /// <summary>
+        /// 从客户端收到信息
+        /// </summary>
+        /// <param name="client"></param>
+        /// <param name="e"></param>
+        /// <returns></returns>
+        private Task ReceivedVoid(SocketClient client, ReceivedDataEventArgs e)
+        {
+            Encoding encoding = GetEncoding();
+            ReceivedEvent?.Invoke(client, encoding.GetString(e.ByteBlock.Buffer, 0, e.ByteBlock.Len));
+            //调用CreateWaitingClient获取到IWaitingClient的对象。
+            WaitClientServer = client.CreateWaitingClient(new WaitingOptions()
+            {
+                FilterFunc = response => //设置用于筛选的fun委托,当返回为true时,才会响应返回
+                {
+                    return true;
+
+                    //if (response.Data.Length == 1)
+                    //{
+                    //    return true;
+                    //}
+                    //return false;
+                }
+            });
+            return EasyTask.CompletedTask;
+        }
+        #endregion
+
+        #region 发送数据
+        /// <summary>
+        /// 发送信息给特定ID的客户端
+        /// </summary>
+        /// <param name="ID"></param>
+        /// <param name="msg"></param>
+        public void Send(string ID, string mes)
+        {
+            Encoding encoding = GetEncoding();
+            var clients = TcpService.GetClients();
+            var client = TcpService.GetClients().FirstOrDefault(cl => cl.Id == ID);
+            if ( client != null )
+            {
+                client.Send(encoding.GetBytes(mes));
+                SendEvent?.Invoke(client, mes);
+            }
+        }
+
+        /// <summary>
+        /// 发送信息给特定ID的客户端
+        /// </summary>
+        /// <param name="ID"></param>
+        /// <param name="mes"></param>
+        public async Task SendAsync(string ID, string mes)
+        {
+            Encoding encoding = GetEncoding();
+            var clients = TcpService.GetClients();
+            var client = TcpService.GetClients().FirstOrDefault(cl => cl.Id == ID);
+            if ( client != null )
+            {
+                await client.SendAsync(encoding.GetBytes(mes));
+                SendEvent?.Invoke(client, mes);
+            }
+        }
+
+        /// <summary>
+        /// 发送信息给在线的所有客户端
+        /// </summary>
+        /// <param name="ID"></param>
+        /// <param name="msg"></param>
+        public void Send(string mes)
+        {
+            Encoding encoding = GetEncoding();
+            foreach ( var client in TcpService.GetClients() )
+            {
+                client.Send(encoding.GetBytes(mes));
+                SendEvent?.Invoke(client, mes);
+            }
+        }
+
+        /// <summary>
+        /// 发送信息给在线的所有客户端
+        /// </summary>
+        /// <param name="mes"></param>
+        public async Task SendAsync(string mes)
+        {
+            Encoding encoding = GetEncoding();
+            foreach ( var client in TcpService.GetClients() )
+            {
+                await client.SendAsync(encoding.GetBytes(mes));
+                SendEvent?.Invoke(client, mes);
+            }
+        }
+
+        /// <summary>
+        /// 发送信息给客户端
+        /// </summary>
+        /// <param name="client">客户端</param>
+        /// <param name="mes"></param>
+        public void Send(SocketClient client, string mes)
+        {
+            if ( client == null ) return;
+            if ( !client.Online ) return;
+            Encoding encoding = GetEncoding();
+            client.Send(encoding.GetBytes(mes));
+            SendEvent?.Invoke(client, mes);
+        }
+
+        /// <summary>
+        /// 发送信息给客户端
+        /// </summary>
+        /// <param name="client"></param>
+        /// <param name="mes"></param>
+        public async Task SendAsync(SocketClient client, string mes)
+        {
+            if ( client == null ) return;
+            if ( !client.Online ) return;
+            Encoding encoding = GetEncoding();
+            await client.SendAsync(encoding.GetBytes(mes));
+            SendEvent?.Invoke(client, mes);
+        }
+
+        /// <summary>
+        /// 发送并接收数据(最后一次活动的客户端)
+        /// </summary>
+        /// <param name="mes"></param>
+        /// <param name="millisecondsTimeout"></param>
+        /// <returns></returns>
+        public string SendThenReturn(string mes, int millisecondsTimeout = 5000)
+        {
+            Encoding encoding = GetEncoding();
+            SendEvent?.Invoke(WaitClientServer.Client, mes);
+            var returnData = WaitClientServer.SendThenReturn(encoding.GetBytes(mes), millisecondsTimeout);
+            ReceivedEvent?.Invoke(WaitClientServer.Client, encoding.GetString(returnData));
+            return encoding.GetString(returnData);
+        }
+
+        /// <summary>
+        /// 发送并接收数据(最后一次活动的客户端)
+        /// </summary>
+        /// <param name="mes"></param>
+        /// <param name="millisecondsTimeout"></param>
+        /// <returns></returns>
+        public async Task<string> SendThenReturnAsync(string mes, int millisecondsTimeout = 5000)
+        {
+            Encoding encoding = GetEncoding();
+            SendEvent?.Invoke(WaitClientServer.Client, mes);
+            var returnData = await WaitClientServer.SendThenReturnAsync(encoding.GetBytes(mes), millisecondsTimeout);
+            ReceivedEvent?.Invoke(WaitClientServer.Client, encoding.GetString(returnData));
+            return encoding.GetString(returnData);
+        }
+
+        /// <summary>
+        /// 发送并接收数据
+        /// </summary>
+        /// <param name="client"></param>
+        /// <param name="mes"></param>
+        /// <param name="millisecondsTimeout"></param>
+        /// <returns></returns>
+        public string SendThenReturn(SocketClient client, string mes, int millisecondsTimeout = 5000)
+        {
+            WaitClientServer = client.CreateWaitingClient(new WaitingOptions()
+            {
+                FilterFunc = response => //设置用于筛选的fun委托,当返回为true时,才会响应返回
+                {
+                    return true;
+
+                    //if (response.Data.Length == 1)
+                    //{
+                    //    return true;
+                    //}
+                    //return false;
+                }
+            });
+            Encoding encoding = GetEncoding();
+            SendEvent?.Invoke(WaitClientServer.Client, mes);
+            var returnData = WaitClientServer.SendThenReturn(encoding.GetBytes(mes), millisecondsTimeout);
+            ReceivedEvent?.Invoke(WaitClientServer.Client, encoding.GetString(returnData));
+            return encoding.GetString(returnData);
+        }
+
+        /// <summary>
+        /// 发送并接收数据
+        /// </summary>
+        /// <param name="client"></param>
+        /// <param name="mes"></param>
+        /// <param name="millisecondsTimeout"></param>
+        /// <returns></returns>
+        public async Task<string> SendThenReturnAsync(SocketClient client, string mes, int millisecondsTimeout = 5000)
+        {
+            WaitClientServer = client.CreateWaitingClient(new WaitingOptions()
+            {
+                FilterFunc = response => //设置用于筛选的fun委托,当返回为true时,才会响应返回
+                {
+                    return true;
+
+                    //if (response.Data.Length == 1)
+                    //{
+                    //    return true;
+                    //}
+                    //return false;
+                }
+            });
+            Encoding encoding = GetEncoding();
+            SendEvent?.Invoke(WaitClientServer.Client, mes);
+            var returnData = await WaitClientServer.SendThenReturnAsync(encoding.GetBytes(mes), millisecondsTimeout);
+            ReceivedEvent?.Invoke(WaitClientServer.Client, encoding.GetString(returnData));
+            return encoding.GetString(returnData);
+        }
+        #endregion
+
+        #region 编码
+        /// <summary>
+        /// 获取编码
+        /// </summary>
+        /// <param name="dataEncoding"></param>
+        /// <returns></returns>
+        public Encoding GetEncoding()
+        {
+           
+         
+            return  Encoding.Unicode;
+        }
+        #endregion
+    }
+}

+ 515 - 0
Toolkit/Tcp/ClientCommunicate.cs

@@ -0,0 +1,515 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Net;
+using System.Runtime.CompilerServices;
+using System.Text;
+using System.Threading.Tasks;
+using Toolkit.Log4;
+using TouchSocket.Core;
+using TouchSocket.Sockets;
+
+namespace Toolkit.Tcp
+{
+    public class ClientCommunicate : INotifyPropertyChanged
+    {
+        private IWaitingClient<TouchSocket.Sockets.TcpClient> WaitClient;
+        private bool isFirstConnect = true;
+        private Task bgConnectTask;
+        public event Action<Guid, object, ConnectedEventArgs> ConnectedEvent;
+        public event Action<Guid, object, DisconnectEventArgs> DisconnectedEvent;
+        public event Action<Guid, object, ReceivedDataEventArgs> ReceivedEvent;
+        public event Action<Guid, object, string> SendEvent;
+
+        #region 属性
+        public TcpService TcpService { get; private set; }
+        public TcpClient TcpClient { get; private set; }
+    
+        public Guid Id { get; set; }
+
+        public int Port { get; private set; }
+
+        public string Ip { get; private set; }
+
+        public Terminator Terminator { get; private set; }
+
+        public DataEncoding DataEncoding { get; private set; }
+
+        public bool IsConnected
+        {
+            get
+            {
+                return TcpClient.Online;
+            }
+        }
+
+        public int Timeout { get; set; } = 5000;
+
+        private bool _CanExecute = false;
+
+        public bool CanExecute
+        {
+            get { return _CanExecute; }
+            set { SetProperty(ref _CanExecute, value); }
+        }
+        #endregion
+
+
+        public ClientCommunicate()
+        {
+            Id = Guid.NewGuid();
+            Ip = "127.0.0.1";//192.168.2.99
+            Port = 8888;
+            Terminator = Terminator.None;
+            DataEncoding = DataEncoding.UTF8;
+            //主站做服务器
+            TcpClient = new TouchSocket.Sockets.TcpClient();
+            var config = new TouchSocketConfig();
+            config.SetRemoteIPHost(new IPHost(IPAddress.Parse(Ip), Port));
+            config.ConfigurePlugins(a => { a.UseReconnection(-1, true, 1000); });       ////如需永远尝试连接,tryCount设置为-1即可。
+                
+            ////设置结束符
+            if ( Terminator == Terminator.None )
+            {
+                config.SetTcpDataHandlingAdapter(() => { return new FixedHeaderPackageAdapter() { FixedHeaderType= FixedHeaderType.Int }; });       ////亦或者省略\r\n,但此时调用方不能高速调用,会粘包
+            }
+            else if ( Terminator == Terminator.CR )
+            {
+                config.SetTcpDataHandlingAdapter(() => { return new TerminatorPackageAdapter("\r"); });       //命令行中使用\r结尾 
+            }
+            else if ( Terminator == Terminator.LF )
+            {
+                config.SetTcpDataHandlingAdapter(() => { return new TerminatorPackageAdapter("\n"); });       //命令行中使用\n结尾 
+            }
+            else if ( Terminator == Terminator.CRLF )
+            {
+                config.SetTcpDataHandlingAdapter(() => { return new TerminatorPackageAdapter("\r\n"); });       //命令行中使用\r\n结尾 
+            }
+            //载入配置
+            TcpClient.Setup(config);
+            ////调用CreateWaitingClient获取到IWaitingClient的对象。
+            WaitClient = TcpClient.CreateWaitingClient(new WaitingOptions()
+            {
+                FilterFunc = response => //设置用于筛选的fun委托,当返回为true时,才会响应返回
+                {
+                    return true;
+
+                    //if (response.Data.Length == 1)
+                    //{
+                    //    return true;
+                    //}
+                    //return false;
+                }
+            });
+            //成功连接到服务器
+            TcpClient.Connected = ConnectedVoid;
+            //有客户端断开连接
+            TcpClient.Disconnected = DisconnectedVoid;
+            //从客户端收到信息
+            TcpClient.Received = ReceivedVoid;
+        }
+
+        #region 事件接收
+        //---------------------------------------------客户端--------------------------------------------
+        /// <summary>
+        /// 连接到服务器时
+        /// </summary>
+        /// <param name="client"></param>
+        /// <param name="e"></param>
+        /// <returns></returns>
+        private Task ConnectedVoid(ITcpClient client, ConnectedEventArgs e)
+        {
+            CanExecute = true;
+            ConnectedEvent?.Invoke(this.Id, client, e);
+            return EasyTask.CompletedTask;
+        }
+
+        /// <summary>
+        /// 有客户端断开连接
+        /// </summary>
+        /// <param name="client"></param>
+        /// <param name="e"></param>
+        /// <returns></returns>
+        private Task DisconnectedVoid(ITcpClientBase client, DisconnectEventArgs e)
+        {
+            CanExecute = false;
+            DisconnectedEvent?.Invoke(this.Id, client, e);
+            return EasyTask.CompletedTask;
+        }
+        /// <summary>
+        /// 从客户端收到信息
+        /// </summary>
+        /// <param name="client"></param>
+        /// <param name="e"></param>
+        /// <returns></returns>
+        private Task ReceivedVoid(ITcpClient client, ReceivedDataEventArgs e)
+        {
+          
+            ReceivedEvent?.Invoke(this.Id, client, e );
+            return EasyTask.CompletedTask;
+        }
+        #endregion
+
+        #region 连接
+        public void Connect()
+        {
+            try
+            {
+                TcpClient.Connect();
+                isFirstConnect = false;
+            }
+            catch ( Exception )
+            {
+                if ( bgConnectTask == null )
+                {
+                    bgConnectTask = Task.Run(async () =>
+                    {
+                        while ( true )
+                        {
+                            try
+                            {
+                                TcpClient.Connect();
+                                isFirstConnect = false;
+                                return;
+                            }
+                            catch ( Exception )
+                            {
+                                await Task.Delay(1000);
+                            }
+                        }
+                    });
+                }
+                throw;
+            }
+        }
+
+        public async Task ConnectAsync()
+        {
+            try
+            {
+                await TcpClient.ConnectAsync();
+                LogHelper.Info(Ip+"  打印机连接成功");
+                isFirstConnect = false;
+            }
+            catch ( Exception )
+            {
+                if ( bgConnectTask == null )
+                {
+                    bgConnectTask = Task.Run(async () =>
+                    {
+                        while ( true )
+                        {
+                            try
+                            {
+                                TcpClient.Connect();
+                                isFirstConnect = false;
+                                LogHelper.Info(Ip + "打印机连接成功");
+                                return;
+                            }
+                            catch ( Exception )
+                            {
+                                LogHelper.Info(Ip + "打印机连接失败");
+                                await Task.Delay(500);
+                            }
+                        }
+                    });
+                }
+                throw;
+            }
+        }
+
+        public void Disconnect()
+        {
+            if ( TcpClient != null )
+            {
+                TcpClient.Close();
+            }
+        }
+
+        public void Dispose()
+        {
+            if ( TcpClient != null )
+            {
+                TcpClient.Dispose();
+            }
+        }
+        #endregion
+
+        #region 控制
+       
+
+        #endregion
+
+        #region 收发数据
+        /// <summary>
+        /// 发送并接收数据
+        /// </summary>
+        /// <param name="send"></param>
+        /// <returns></returns>
+        public string SendAndReceive(string send)
+        {
+            Encoding encoding = GetEncoding();
+            SendEvent?.Invoke(this.Id, WaitClient.Client, send);
+            var returnData = WaitClient.SendThenReturn(encoding.GetBytes(send), Timeout);
+            ReceivedDataEventArgs receivedDataEvent = new ReceivedDataEventArgs(new ByteBlock(returnData), null);
+            ReceivedEvent?.Invoke(this.Id, WaitClient, receivedDataEvent);
+            return encoding.GetString(returnData);
+        }
+        
+        /// <summary>
+        /// 发送并接收数据
+        /// </summary>
+        /// <param name="send"></param>
+        /// <returns></returns>
+        public byte[] SendAndReceive(byte[] send)
+        {
+            Encoding encoding = GetEncoding();
+            //SendEvent?.Invoke(this.Id, WaitClient.Client, send);
+            var returnData = WaitClient.SendThenReturn(send, Timeout);
+            ReceivedDataEventArgs receivedDataEvent = new ReceivedDataEventArgs(new ByteBlock(returnData), null);
+            ReceivedEvent?.Invoke(this.Id, WaitClient, receivedDataEvent);
+            return returnData;
+        }
+
+        /// <summary>
+        /// 发送并接收数据
+        /// </summary>
+        /// <param name="send"></param>
+        /// <returns></returns>
+        public async Task<string> SendAndReceiveAsync(string send)
+        {
+            Encoding encoding = GetEncoding();
+            SendEvent?.Invoke(this.Id, WaitClient.Client, send);
+            var returnData = await WaitClient.SendThenReturnAsync(encoding.GetBytes(send), Timeout);
+            ReceivedDataEventArgs receivedDataEvent = new ReceivedDataEventArgs(new ByteBlock(returnData), null);
+            ReceivedEvent?.Invoke(this.Id, WaitClient, receivedDataEvent);
+            return encoding.GetString(returnData);
+        }
+
+        /// <summary>
+        /// 发送并接收数据
+        /// </summary>
+        /// <param name="send"></param>
+        /// <returns></returns>
+        public string SendAndReceive(SocketClient client, string send)
+        {
+            Encoding encoding = GetEncoding();
+            SendEvent?.Invoke(this.Id, WaitClient.Client, send);
+            var returnData = WaitClient.SendThenReturn(encoding.GetBytes(send), Timeout);
+            ReceivedDataEventArgs receivedDataEvent = new ReceivedDataEventArgs(new ByteBlock(returnData), null);
+            ReceivedEvent?.Invoke(this.Id, WaitClient, receivedDataEvent);
+            return encoding.GetString(returnData);
+        }
+
+        /// <summary>
+        /// 发送并接收数据
+        /// </summary>
+        /// <param name="send"></param>
+        /// <returns></returns>
+        public async Task<string> SendAndReceiveAsync(SocketClient client, string send)
+        {
+            Encoding encoding = GetEncoding();
+            SendEvent?.Invoke(this.Id, WaitClient.Client, send);
+            var returnData = await WaitClient.SendThenReturnAsync(encoding.GetBytes(send), Timeout);
+            ReceivedDataEventArgs receivedDataEvent = new ReceivedDataEventArgs(new ByteBlock(returnData), null);
+            ReceivedEvent?.Invoke(this.Id, WaitClient, receivedDataEvent);
+            return encoding.GetString(returnData);
+        }
+
+        public void Send(string send)
+        {
+            Encoding encoding = GetEncoding();
+            //byte[]sendbuff=  encoding.GetBytes(send);
+            //int size = sendbuff.Length;
+            //byte[] datasize = new byte[4];
+            //datasize = BitConverter.GetBytes(size);
+
+            //byte[] mergedData = datasize.Concat(sendbuff).ToArray();
+            //SendEvent?.Invoke(this.Id, TcpClient, send);
+            TcpClient.Send(encoding.GetBytes(send));
+        }
+
+        public void Send(byte []send)
+        {
+            //int size = send.Length;
+            //byte[] datasize = new byte[4];
+            //datasize = BitConverter.GetBytes(size);
+
+            //byte[] mergedData = datasize.Concat(send).ToArray();
+
+            Encoding encoding = GetEncoding();
+            SendEvent?.Invoke(this.Id, TcpClient,encoding.GetString(send));
+            TcpClient.Send(send);
+        }
+
+        public async Task SendAsync(string send)
+        {
+            Encoding encoding = GetEncoding();
+            SendEvent?.Invoke(this.Id, TcpClient, send);
+            await TcpClient.SendAsync(encoding.GetBytes(send));
+        }
+
+        public void Send(SocketClient client, string send)
+        {
+            try
+            {
+                if ( client == null )
+                {
+                    return;
+                }
+
+                Encoding encoding = GetEncoding();
+                SendEvent?.Invoke(this.Id, TcpClient, send);
+                TcpClient.Send(encoding.GetBytes(send));
+            }
+            catch ( Exception ex )
+            {
+                LogHelper.error.Error("发送数据时出错", ex);
+            }
+
+        }
+
+        public async Task SendAsync(SocketClient client, string send)
+        {
+            try
+            {
+                if ( client == null )
+                {
+                    return;
+                }
+
+                Encoding encoding = GetEncoding();
+                SendEvent?.Invoke(this.Id, TcpClient, send);
+                await TcpClient.SendAsync(encoding.GetBytes(send));
+            }
+            catch ( Exception ex )
+            {
+                LogHelper.error.Error("发送数据时出错", ex);
+            }
+        }
+
+        /// <summary>
+        /// 获取编码
+        /// </summary>
+        /// <param name="dataEncoding"></param>
+        /// <returns></returns>
+        public Encoding GetEncoding()
+        {
+            DataEncoding dataEncoding = this.DataEncoding;
+            Encoding encoding;
+            if ( dataEncoding == DataEncoding.Default )
+            {
+                encoding = Encoding.Default;
+            }
+            else if ( dataEncoding == DataEncoding.ASCII )
+            {
+                encoding = Encoding.ASCII;
+            }
+            else if ( dataEncoding == DataEncoding.UTF7 )
+            {
+                encoding = Encoding.UTF7;
+            }
+            else if ( dataEncoding == DataEncoding.UTF8 )
+            {
+                encoding = Encoding.UTF8;
+            }
+            else if ( dataEncoding == DataEncoding.UTF32 )
+            {
+                encoding = Encoding.UTF32;
+            }
+            else if ( dataEncoding == DataEncoding.Unicode )
+            {
+                encoding = Encoding.Unicode;
+            }
+            else if ( dataEncoding == DataEncoding.BigEndianUnicode )
+            {
+                encoding = Encoding.BigEndianUnicode;
+            }
+            else if ( dataEncoding == DataEncoding.GB2312 )
+            {
+
+                encoding = Encoding.GetEncoding("gb2312");
+            }
+            else
+            {
+                encoding = Encoding.Default;
+            }
+            return encoding;
+        }
+        #endregion
+
+        #region 属性通知
+        /// <summary>
+        /// Occurs when a property value changes.
+        /// </summary>
+        public event PropertyChangedEventHandler PropertyChanged;
+
+        /// <summary>
+        /// Checks if a property already matches a desired value. Sets the property and
+        /// notifies listeners only when necessary.
+        /// </summary>
+        /// <typeparam name="T">Type of the property.</typeparam>
+        /// <param name="storage">Reference to a property with both getter and setter.</param>
+        /// <param name="value">Desired value for the property.</param>
+        /// <param name="propertyName">Name of the property used to notify listeners. This
+        /// value is optional and can be provided automatically when invoked from compilers that
+        /// support CallerMemberName.</param>
+        /// <returns>True if the value was changed, false if the existing value matched the
+        /// desired value.</returns>
+        protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
+        {
+            if ( EqualityComparer<T>.Default.Equals(storage, value) ) return false;
+
+            storage = value;
+            RaisePropertyChanged(propertyName);
+
+            return true;
+        }
+
+        /// <summary>
+        /// Checks if a property already matches a desired value. Sets the property and
+        /// notifies listeners only when necessary.
+        /// </summary>
+        /// <typeparam name="T">Type of the property.</typeparam>
+        /// <param name="storage">Reference to a property with both getter and setter.</param>
+        /// <param name="value">Desired value for the property.</param>
+        /// <param name="propertyName">Name of the property used to notify listeners. This
+        /// value is optional and can be provided automatically when invoked from compilers that
+        /// support CallerMemberName.</param>
+        /// <param name="onChanged">Action that is called after the property value has been changed.</param>
+        /// <returns>True if the value was changed, false if the existing value matched the
+        /// desired value.</returns>
+        protected virtual bool SetProperty<T>(ref T storage, T value, Action onChanged, [CallerMemberName] string propertyName = null)
+        {
+            if ( EqualityComparer<T>.Default.Equals(storage, value) ) return false;
+
+            storage = value;
+            onChanged?.Invoke();
+            RaisePropertyChanged(propertyName);
+
+            return true;
+        }
+
+        /// <summary>
+        /// Raises this object's PropertyChanged event.
+        /// </summary>
+        /// <param name="propertyName">Name of the property used to notify listeners. This
+        /// value is optional and can be provided automatically when invoked from compilers
+        /// that support <see cref="CallerMemberNameAttribute"/>.</param>
+        protected void RaisePropertyChanged([CallerMemberName] string propertyName = null)
+        {
+            OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
+        }
+
+        /// <summary>
+        /// Raises this object's PropertyChanged event.
+        /// </summary>
+        /// <param name="args">The PropertyChangedEventArgs</param>
+        protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
+        {
+            PropertyChanged?.Invoke(this, args);
+        }
+        #endregion
+    }
+}

+ 34 - 0
Toolkit/Tcp/MesMsg.cs

@@ -28,6 +28,10 @@ namespace Toolkit.Tcp
 
         public string totalpack { get; set; }
         public string packno { get; set; }
+
+       public string packinfo { get; set; }
+
+       public string suminfo { get; set; }
         public string clientCode { get; set; } = "";
 
     }
@@ -54,4 +58,34 @@ namespace Toolkit.Tcp
         public string ribbon { get; set; } = "0";
 
     }
+
+    public enum DataEncoding
+    {
+        Default = 0,
+        ASCII=1,
+        UTF7=2,
+        UTF8=3,
+        UTF32=4,
+        Unicode=5,
+        BigEndianUnicode=6,
+        GB2312=7,
+
+    }
+    /// <summary>
+    /// 结束符
+    /// </summary>
+    public enum Terminator
+    {
+        CR=0,
+        LF=1,
+        CRLF=2,
+        None=3
+    }
+
+    public enum Stepenum 
+    {
+       SendData,
+       RecvTD,
+       RecvPD
+    }
 }

+ 0 - 357
Toolkit/Tcp/TCPClient.cs

@@ -1,357 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Net;
-using System.Net.Sockets;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using Toolkit.Log4;
-using static Toolkit.Tcp.TCPServer;
-
-namespace Toolkit.Tcp
-{
-    public class TCPClient
-    {
-        /// <summary>
-        /// 所有可以正常使用的连接
-        /// </summary>
-        public static List<TCPClient> sockets = new List<TCPClient>();
-        public List<IPEndPoint> endps = new List<IPEndPoint>();
-        public static bool createState = true;//创建是否成功
-        public Socket socket;
-        public string startstr;
-        public string stopstr;
-        public IPEndPoint iPEndPoint= new IPEndPoint(IPAddress.Parse("192.168.2.99"), 8888);//192.168.2.99
-        public TCPClient()
-        {
-            Connect();
-        }
-
-        public void Connect()
-        {
-            try
-            {
-                AddressFamily addressFamily = AddressFamily.InterNetwork;
-                SocketType socketType = SocketType.Stream;
-                ProtocolType protocolType = ProtocolType.Tcp;
-                socket = new Socket(addressFamily, socketType, protocolType);
-                //socket.IOControl();
-                socket.Connect(iPEndPoint);
-                LogHelper.Info(iPEndPoint.Address.ToString() + ":" + iPEndPoint.Port + " 已连接");
-                socket.SendTimeout = 1000;
-                socket.ReceiveTimeout = 1000;
-
-
-                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
-
-                // 配置Keep-Alive参数(空闲3秒,间隔1秒,尝试3次)
-                byte[] keepAliveParams = new byte[] {
-    1, 0, 0, 0,        // 启用Keep-Alive
-    0x88, 0x13, 0, 0,  // 空闲时间3000ms (十六进制0x00001388)
-    0xE8, 0x03, 0, 0,  // 探测间隔1000ms (0x000003E8)
-    3, 0, 0, 0         // 探测次数3次
-};
-
-
-                socket.IOControl(IOControlCode.KeepAliveValues, keepAliveParams, null);
-                // 参数说明:空闲60秒后探测,间隔5秒,尝试3次 ‌:ml-citation{ref="5,8" data="citationList"}
-
-
-                //  startstr = tcp.StartStr;
-                //stopstr = tcp.StopStr;
-                sockets.Add(this);
-                createState = true;
-                string str = ReceiveVarData(socket);
-                LogHelper.Info(str);
-            }
-            catch
-            {
-                createState = false;
-                if ( socket.Connected )
-                {
-                    socket.Close();
-                }
-            }
-
-        }
-        public string SendAndReceive(string msg, int timeout = 2000)
-        {
-
-            try
-            {
-                byte[] msgbytes = Encoding.Default.GetBytes(msg);
-
-                int i = socket.Send(msgbytes);
-
-                byte[] bytes = new byte[256];
-
-                i = socket.Receive(bytes);
-
-                if ( i != 0 )
-                {
-                    string str = Encoding.Default.GetString(bytes);
-                    str = str.Substring(0, i);
-                    int startindex = 0;
-                    int stopindex = 0;
-                    //if (startstr.Length != 0 && stopstr.Length != 0)
-                    //{
-                    //    startindex = str.IndexOf(startstr);
-                    //    stopindex = str.IndexOf(stopstr);
-                    //}
-                    //if (startindex != -1 && stopindex != -1)
-                    {
-                        //        str = str.Substring(startindex + startstr.Length, stopindex - (startindex + startstr.Length));
-                        if ( str.Length != 0 )
-                        {
-                            LogHelper.Info("-" + socket.RemoteEndPoint.ToString() + ":" + str + "\r\n");
-
-                            return str;
-                        }
-                        else
-                        {
-                            return "ERROR";
-                        }
-                    }
-
-                }
-                return null;
-
-            }
-            catch ( Exception ex )
-            {
-                LogHelper.error.Error("", ex);
-
-                return "";
-            }
-
-        }
-
-        public string SendLinux(string NowSendData, int printcount = 1, int autostop = 0, int encode = 1)
-        {
-            string sends = "";
-            byte[] endbyte = new byte[] { 00, 00, 03, 04 };
-
-            if ( NowSendData != "" )
-            {
-                byte[] VerBin = new byte[10000];
-                //计算校验字节。
-                byte VerByte = 0;
-                List<byte> CRCBuffer = new List<byte>();
-                CRCBuffer.Add(0x1D);                                      //起始
-                CRCBuffer.Add(( byte ) ( printcount & 0xff ));
-                CRCBuffer.Add(( byte ) ( ( printcount & 0xff00 ) >> 8 ));
-                CRCBuffer.Add(( byte ) ( ( printcount & 0xff0000 ) >> 16 ));
-                CRCBuffer.Add(( byte ) ( ( printcount & 0xff000000 ) >> 24 ));
-
-                if ( autostop == 0 )
-                    CRCBuffer.Add(0x0A);
-                else
-                    CRCBuffer.Add(0x0B);
-                encode = 1;     //220904统一采用utf8格式发送,解决部分gb2312乱码(二维码中)
-                switch ( encode )
-                {
-                    case 0:
-                        VerBin = System.Text.Encoding.GetEncoding("gb2312").GetBytes(NowSendData);
-                        CRCBuffer.Add(0xC1);
-                        break;
-                    case 1:
-                        VerBin = System.Text.Encoding.UTF8.GetBytes(NowSendData);
-                        CRCBuffer.Add(0xC2);
-                        break;
-                    case 2:
-                        VerBin = System.Text.Encoding.Unicode.GetBytes(NowSendData);
-                        CRCBuffer.Add(0xC3);
-                        break;
-                }
-
-                CRCBuffer.AddRange(VerBin);                               //数据
-                VerByte = CRC8(CRCBuffer.ToArray());
-                CRCBuffer.Add(VerByte);
-                CRCBuffer.AddRange(endbyte);
-                byte[] sendbuff = CRCBuffer.ToArray();
-                LogHelper.Info("                              发送给打印机: outdata");
-                string res = SendVarData(socket, Encoding.UTF8.GetBytes("outdata"));
-                LogHelper.Info("                              打印机返回:  " + res);
-                if ( res != "Fail" && res != "Err" )
-                {
-                    LogHelper.Info("                              发送给打印机: " + NowSendData);
-                    res = SendVarData(socket, sendbuff);
-                    LogHelper.Info("                              打印机返回:  " + res);
-                }
-
-
-                return res;
-            }
-            else
-            {
-                return "null";
-            }
-        }
-
-        public string ReceiveVarData(Socket s)
-        {
-            int total = 0;
-            int recv;
-            string datas = "";
-
-            if ( s == null )
-                return "未连接";
-            if ( !s.Connected )
-            {
-                return "未连接";
-            }
-            int size = 0;
-            byte[] datasize = new byte[4];
-            try
-            {
-                
-                recv = s.Receive(datasize, 0, 4, SocketFlags.None);
-            }
-            catch
-            {
-                return "未收到数据";
-            }
-            size = BitConverter.ToInt32(datasize, 0);
-            if ( size == 0 )
-                return "未收到数据";
-            for ( int i = 0; i < datasize.Length; i++ )
-                datas += datasize[ i ].ToString("X2") + " ";
-
-
-            int dataleft = size;
-
-            byte[] data = new byte[size];
-            while ( total < size )
-            {
-                recv = s.Receive(data, total, dataleft, SocketFlags.None);
-                if ( recv == 0 )
-                {
-                    data = null;
-                    break;
-                }
-                total += recv;
-                dataleft -= recv;
-            }
-            datas = "";
-
-            return Encoding.UTF8.GetString(data);
-
-        }
-        public static byte CRC8(byte[] buffer)
-        {
-            byte crc = 0;
-            for ( int j = 0; j < buffer.Length; j++ )
-            {
-                crc ^= buffer[ j ];
-                for ( int i = 0; i < 8; i++ )
-                {
-                    if ( ( crc & 0x01 ) != 0 )
-                    {
-                        crc >>= 1;
-                        crc ^= 0x8c;
-                    }
-                    else
-                    {
-                        crc >>= 1;
-                    }
-                }
-            }
-            return crc;
-        }
-
-        public string SendVarData(Socket s, byte[] data)
-        {
-
-            if ( s == null )
-                return "null";
-            if ( !s.Connected )
-            {
-
-                return "未连接";
-
-            }
-            string datas = "";
-            try
-            {
-                int total = 0;
-                int size = data.Length;
-                int dataleft = size;
-                int sent;
-                byte[] datasize = new byte[4];
-                datasize = BitConverter.GetBytes(size);
-                sent = s.Send(datasize);
-                datas = "";
-                while ( total < size )
-                {
-                    sent = s.Send(data, total, dataleft, SocketFlags.None);
-                    total += sent;
-                    dataleft -= sent;
-                }
-                if ( total != 0 )
-                {
-                    return "OK";
-                }
-                return "Fail";
-            }
-            catch ( Exception ex )
-            {
-
-
-                return "Err";
-            }
-        }
-
-
-        public int Send(string msg, int timeout = 2000)
-        {
-            try
-            {
-
-
-                byte[] msgbytes = Encoding.Default.GetBytes(msg);
-
-                int i = socket.Send(msgbytes);
-
-                LogHelper.Info("本地发送数据:" + msg);
-                return i;
-
-            }
-            catch ( Exception ex )
-            {
-                LogHelper.error.Error("", ex);
-
-                return -1;
-            }
-
-
-        }
-
-        public string Receive(int timeout = 2000)
-        {
-
-            try
-            {
-
-                byte[] bytes = new byte[256];
-                int i = socket.Receive(bytes);
-
-                if ( i != 0 )
-                {
-                    return null;
-                }
-                return null;
-
-
-
-            }
-            catch ( Exception ex )
-            {
-                LogHelper.error.Error("", ex);
-                return null;
-            }
-
-        }
-
-    }
-}

+ 0 - 240
Toolkit/Tcp/TCPServer.cs

@@ -1,240 +0,0 @@
-using Prism.Events;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Net;
-using System.Net.Sockets;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using Toolkit.Event;
-using Toolkit.Log4;
-
-namespace Toolkit.Tcp
-{
-    public class TCPServer
-    {
-
-        public IPAddress iPAddress;
-        private IPEndPoint endp;
-        private AddressFamily addressFamily;
-        private SocketType socketType;
-        private ProtocolType protocolType;
-        public static List<Client> clientList = new List<Client>();
-        private bool isEnd = true;
-        public string startstr;
-        public string stopstr;
-        public List<string> strmes = new List<string>();
-        public Socket _socket;
-
-
-        public static List<TCPServer> servers = new List<TCPServer>();
-
-        public TCPServer()
-        {
-            addressFamily = AddressFamily.InterNetwork;
-            socketType = SocketType.Stream;
-            protocolType = ProtocolType.Tcp;
-            iPAddress = IPAddress.Parse("192.168.2.109");//192.168.2.109
-            endp = new IPEndPoint(iPAddress, 503);
-            //startstr = server.StartStr;
-            //stopstr = server.StopStr;
-
-        }
-        public static bool createState = true;//创建是否成功
-        public bool Start()
-        {
-            try
-            {
-                foreach ( var client in clientList )//遍历已经存储的客户端
-                {
-                    client.clientSocket.Close();
-                }
-                clientList.Clear();
-                _socket = new Socket(addressFamily, socketType, protocolType);
-                _socket.Bind(endp);
-                _socket.Listen(1024);
-                isEnd = true;
-                LogHelper.Info(iPAddress + "服务已启动,等待连接......");
-                Console.WriteLine(iPAddress + "服务已启动,等待连接......");
-                Thread l = new Thread(tcpCon);
-                l.Name = iPAddress + "服务";
-                l.Start();
-                servers.Add(this);
-                createState = true;
-                return true;
-            }
-            catch (Exception ex)
-            {
-                createState = false;
-                LogHelper.error.Error("", ex);
-                return false;
-            }
-        }
-
-        public void tcpCon()
-        {
-            
-            while (isEnd)
-            {
-                try
-                {
-                    Socket clientSocket = _socket.Accept();
-                    Console.WriteLine((clientSocket.RemoteEndPoint as IPEndPoint).Address + "已连接");
-                    LogHelper.Info((clientSocket.RemoteEndPoint as IPEndPoint).Address + "已连接");
-                    Thread thread = new Thread(new ThreadStart(()=>{
-
-                        Client client = new Client(clientSocket, startstr, stopstr);
-                        strmes = client.strmegs;
-                        if(clientList.Count>0)
-                        {
-                            for (int i = 0; i < clientList.Count; i++)
-                            {
-                                clientList[i].clientSocket.Close();
-                            }
-                        }
-                        clientList.Clear();
-                        clientList.Add(client);
-                    }));
-                    thread.Start();
-                }
-                catch
-                {
-                    break;
-                }
-               
-            }
-            
-        }
-
-        public bool Stop()
-        {
-            try
-            {
-                isEnd = false;
-                _socket.Close();
-
-                foreach ( var client in clientList )//遍历已经存储的客户端
-                {
-                    client.clientSocket.Close();
-                }
-                clientList.Clear();
-                    return true;
-            }
-            catch (Exception ex)
-            {
-                LogHelper.error.Error("", ex);
-                return false;
-            }
-        }
-
-
-        public static void BroadcastMessage(string message, Client clientSocket)//这个函数用来广播接收到的客户端消息  参数1为消息,参数2为消息来源(客户端)
-        {
-            var onConnectedList = new List<Client>();//用来存储已断开服务器连接的客户端
-
-            foreach (var client in clientList)//遍历已经存储的客户端
-            {
-                if (clientSocket == client)//如果该客户端是消息来源,则不重复发送消息给该客户端
-                {
-                    continue;
-                }
-                if (client.Connected)//判断该客户端的状态
-                {
-                    client.SendMessage(client.ip + ":" + message);//
-                }
-                else//把已断开连接的客户端放到数组中
-                {
-                    onConnectedList.Add(client);
-                }
-            }
-            foreach (var temp in onConnectedList)//广播完之后从存储已连接客户端集合中移除掉已断开连接的客户端
-            {
-                clientList.Remove(temp);
-            }
-        }
-
-        public  static IEventAggregator eventAggregator;
-        public class Client
-        {
-            public Socket clientSocket;
-            private Thread t;
-            public string ip = "";
-            private byte[] data = new byte[1024];
-            public List<string> strmegs = new List<string>();
-            public string startstr;
-            public string stopstr;
-            public Client(Socket socket, string startstr, string stopstr)
-            {
-                clientSocket = socket;
-                this.startstr = startstr;
-                this.stopstr = stopstr;
-                ip = (clientSocket.RemoteEndPoint as IPEndPoint).Address.ToString();//获取客户端的ip
-                t = new Thread(ReceiveMessage);//开启线程执行循环接收消息
-                t.Name = "tcp接收消息";
-                t.Start();
-
-            }
-            private void ReceiveMessage()//接收消息
-            {
-                int length = 0;//初始化消息的长度
-                while (true)//循环接收消息
-                {
-                    try
-                    {
-
-                      
-                        length = clientSocket.Receive(data);//获取存放消息数据数组的长度
-                        if (clientSocket.Poll(10, SelectMode.SelectRead))//????
-                        {
-                            clientSocket.Close();
-                            break;
-                        }
-                        if (length != 0)//判断是否有数组内是否存放消息数据
-                        {
-                               string str = Encoding.Unicode.GetString(data, 0, length);//Byte转为string
-                                if (str.Length != 0)
-                                {
-                                    eventAggregator.GetEvent<TcpServerMsg>().Publish(str);
-                                    LogHelper.Info("服务器收到消息"+str);
-                                    
-                                    strmegs.Add(str);
-                                }
-                        }
-                    }
-                    catch(Exception e)
-                    {
-                            LogHelper.Info(ip + "客户端断开");
-                            Console.WriteLine(ip + "客户端断开");
-                            break;
-                        
-                    }
-                }
-
-                LogHelper.Info("服务器消息线程关闭");
-            }
-
-
-
-            public void SendMessage(string message)//发送消息
-            {
-                byte[] data = Encoding.Unicode.GetBytes(message);
-                if ( clientSocket != null && clientSocket.Connected )
-                {
-                    clientSocket.Send(data);
-                    LogHelper.Info(message);
-                }
-                else
-                {
-
-                    LogHelper.Info("");
-                }
-            }
-            public bool Connected//获取该客户端的状态
-            {
-                get { return clientSocket.Connected; }
-            }
-        }
-
-    }
-}

+ 0 - 24
Toolkit/ToolBase/ToolBase.cs

@@ -1,24 +0,0 @@
-using Prism.Mvvm;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using System.Windows.Media;
-
-namespace Toolkit.ToolBase
-{
-   public class ToolBase:BindableBase
-    {
-
-        public int Tid = 0;
-       
-        public string Tres = "";
-
-        public List<string> SendStrs = new List<string>();
-        public string Tdata = "";
-
-        private Brush backgroundColor = Brushes.White;
-        public Brush BackgroundColor { get => backgroundColor; set { SetProperty(ref backgroundColor, value); } }
-    }
-}

+ 37 - 39
Toolkit/Toolkit.csproj

@@ -14,6 +14,8 @@
     <WarningLevel>4</WarningLevel>
     <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
     <Deterministic>true</Deterministic>
+    <NuGetPackageImportStamp>
+    </NuGetPackageImportStamp>
   </PropertyGroup>
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
     <PlatformTarget>AnyCPU</PlatformTarget>
@@ -55,13 +57,23 @@
       <HintPath>..\packages\Prism.Wpf.8.1.97\lib\net47\Prism.Wpf.dll</HintPath>
     </Reference>
     <Reference Include="System" />
+    <Reference Include="System.Buffers, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll</HintPath>
+    </Reference>
     <Reference Include="System.Configuration" />
     <Reference Include="System.Data" />
+    <Reference Include="System.Memory, Version=4.0.1.2, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Memory.4.5.5\lib\net461\System.Memory.dll</HintPath>
+    </Reference>
+    <Reference Include="System.Numerics" />
+    <Reference Include="System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll</HintPath>
+    </Reference>
     <Reference Include="System.Runtime.CompilerServices.Unsafe, Version=4.0.4.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
-      <HintPath>..\packages\System.Runtime.CompilerServices.Unsafe.4.5.2\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
+      <HintPath>..\packages\System.Runtime.CompilerServices.Unsafe.4.5.3\lib\net461\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
     </Reference>
-    <Reference Include="System.Threading.Tasks.Extensions, Version=4.2.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
-      <HintPath>..\packages\System.Threading.Tasks.Extensions.4.5.2\lib\netstandard2.0\System.Threading.Tasks.Extensions.dll</HintPath>
+    <Reference Include="System.Threading.Tasks.Extensions, Version=4.2.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll</HintPath>
     </Reference>
     <Reference Include="System.Xml" />
     <Reference Include="Microsoft.CSharp" />
@@ -72,6 +84,12 @@
     <Reference Include="System.Xaml">
       <RequiredTargetFramework>4.0</RequiredTargetFramework>
     </Reference>
+    <Reference Include="TouchSocket, Version=2.0.15.0, Culture=neutral, PublicKeyToken=5f39d7da98dac6a9, processorArchitecture=MSIL">
+      <HintPath>..\packages\TouchSocket.2.0.15\lib\net472\TouchSocket.dll</HintPath>
+    </Reference>
+    <Reference Include="TouchSocket.Core, Version=2.0.15.0, Culture=neutral, PublicKeyToken=d6c415a2f58eda72, processorArchitecture=MSIL">
+      <HintPath>..\packages\TouchSocket.Core.2.0.15\lib\net472\TouchSocket.Core.dll</HintPath>
+    </Reference>
     <Reference Include="Unity.Abstractions, Version=5.11.7.0, Culture=neutral, PublicKeyToken=489b6accfaf20ef0, processorArchitecture=MSIL">
       <HintPath>..\packages\Unity.Abstractions.5.11.7\lib\net47\Unity.Abstractions.dll</HintPath>
     </Reference>
@@ -87,27 +105,13 @@
       <Generator>MSBuild:Compile</Generator>
       <SubType>Designer</SubType>
     </ApplicationDefinition>
+    <Compile Include="Core\Management.cs" />
     <Compile Include="Event\TcpServerMsg.cs" />
+    <Compile Include="Tcp\BgCommunicate.cs" />
+    <Compile Include="Tcp\ClientCommunicate.cs" />
     <Compile Include="Tcp\MesMsg.cs" />
-    <Compile Include="Tcp\TCPClient.cs" />
-    <Compile Include="Tcp\TCPServer.cs" />
-    <Compile Include="ToolBase\ToolBase.cs" />
     <Compile Include="ViewMode\MainWindowViewMode.cs" />
-    <Compile Include="ViewMode\TcpTriggerViewMode.cs" />
-    <Compile Include="ViewMode\TcpWriteViewMode.cs" />
-    <Compile Include="View\ReadPlc.xaml.cs">
-      <DependentUpon>ReadPlc.xaml</DependentUpon>
-    </Compile>
-    <Compile Include="View\TcpTrigger.xaml.cs">
-      <DependentUpon>TcpTrigger.xaml</DependentUpon>
-    </Compile>
-    <Compile Include="View\TcpWrite.xaml.cs">
-      <DependentUpon>TcpWrite.xaml</DependentUpon>
-    </Compile>
-    <Compile Include="View\WritePcl.xaml.cs">
-      <DependentUpon>WritePcl.xaml</DependentUpon>
-    </Compile>
-    <Page Include="MainWindow.xaml">
+    <Page Include="View\MainWindow.xaml">
       <Generator>MSBuild:Compile</Generator>
       <SubType>Designer</SubType>
     </Page>
@@ -116,26 +120,10 @@
       <SubType>Code</SubType>
     </Compile>
     <Compile Include="Log4\LogHelper.cs" />
-    <Compile Include="MainWindow.xaml.cs">
+    <Compile Include="View\MainWindow.xaml.cs">
       <DependentUpon>MainWindow.xaml</DependentUpon>
       <SubType>Code</SubType>
     </Compile>
-    <Page Include="View\ReadPlc.xaml">
-      <SubType>Designer</SubType>
-      <Generator>MSBuild:Compile</Generator>
-    </Page>
-    <Page Include="View\TcpTrigger.xaml">
-      <SubType>Designer</SubType>
-      <Generator>MSBuild:Compile</Generator>
-    </Page>
-    <Page Include="View\TcpWrite.xaml">
-      <SubType>Designer</SubType>
-      <Generator>MSBuild:Compile</Generator>
-    </Page>
-    <Page Include="View\WritePcl.xaml">
-      <SubType>Designer</SubType>
-      <Generator>MSBuild:Compile</Generator>
-    </Page>
   </ItemGroup>
   <ItemGroup>
     <Compile Include="PLc\PlcConn.cs" />
@@ -165,11 +153,21 @@
   <ItemGroup>
     <None Include="App.config" />
   </ItemGroup>
-  <ItemGroup />
   <ItemGroup>
     <None Include="Properties\LogConfigure.xml">
       <CopyToOutputDirectory>Always</CopyToOutputDirectory>
     </None>
   </ItemGroup>
+  <ItemGroup>
+    <Analyzer Include="..\packages\TouchSocket.Core.2.0.15\analyzers\dotnet\cs\TouchSocket.Core.SourceGenerator.dll" />
+  </ItemGroup>
+  <ItemGroup />
   <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <Import Project="..\packages\System.ValueTuple.4.6.1\build\net471\System.ValueTuple.targets" Condition="Exists('..\packages\System.ValueTuple.4.6.1\build\net471\System.ValueTuple.targets')" />
+  <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
+    <PropertyGroup>
+      <ErrorText>这台计算机上缺少此项目引用的 NuGet 程序包。使用“NuGet 程序包还原”可下载这些程序包。有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。</ErrorText>
+    </PropertyGroup>
+    <Error Condition="!Exists('..\packages\System.ValueTuple.4.6.1\build\net471\System.ValueTuple.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\System.ValueTuple.4.6.1\build\net471\System.ValueTuple.targets'))" />
+  </Target>
 </Project>

+ 32 - 0
Toolkit/View/MainWindow.xaml

@@ -0,0 +1,32 @@
+<Window x:Class="Toolkit.View.MainWindow"
+        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+        xmlns:local="clr-namespace:Toolkit"
+        xmlns:prism="http://prismlibrary.com/"
+        prism:ViewModelLocator.AutoWireViewModel="True"
+        mc:Ignorable="d"
+        Background="White"
+        Title="打印机通讯" Height="450" Width="800">
+    <Grid>
+        <Grid>
+
+            <Grid.RowDefinitions>
+                <RowDefinition Height="50"/>
+                <RowDefinition />
+            </Grid.RowDefinitions>
+        <StackPanel Grid.Row="0">
+            <TextBlock  Background="{Binding Rushes}"
+                        Height="50"
+                        Text="{Binding Errstr}" TextAlignment="Center"/>
+        
+        </StackPanel>
+            <RichTextBox Name="LogShow" Grid.Row="1"
+                         Background="White"
+                         Foreground="Black"
+                         VerticalScrollBarVisibility="Visible">
+            </RichTextBox>
+        </Grid>
+    </Grid>
+</Window>

+ 23 - 13
Toolkit/MainWindow.xaml.cs → Toolkit/View/MainWindow.xaml.cs

@@ -15,7 +15,7 @@ using System.Windows.Navigation;
 using System.Windows.Shapes;
 using Toolkit.Log4;
 
-namespace Toolkit
+namespace Toolkit.View
 {
     /// <summary>
     /// MainWindow.xaml 的交互逻辑
@@ -31,24 +31,33 @@ namespace Toolkit
 
             Task.Run(() =>
             {
-                string[] strs = new string[2];
-                while (true)
+                try
                 {
-                    if (LogHelper.logQueue.Count > 0)
+                    string[] strs = new string[2];
+                    while ( true )
                     {
-                        if (LogHelper.logQueue.TryDequeue(out strs))
+                        if ( LogHelper.logQueue.Count > 0 )
                         {
-                            this.Dispatcher.Invoke( new Action(() => { LogShow.AppendText(strs[0] + "  " + strs[1]+"\n"); }), null);
+                            if ( LogHelper.logQueue.TryDequeue(out strs) )
+                            {
+                                this.Dispatcher.Invoke(new Action(() => { LogShow.AppendText(strs[ 0 ] + "  " + strs[ 1 ] + "\n"); }), null);
 
-                            this.Dispatcher.Invoke(new Action(() => { LogShow.ScrollToEnd(); }), null);
+                                this.Dispatcher.Invoke(new Action(() => { LogShow.ScrollToEnd(); }), null);
+                            }
+                        }
+                        if ( LogHelper.logQueue.Count > 1000 )
+                        {
+                            this.Dispatcher.Invoke(new Action(() => { LogShow.Document.Blocks.Clear(); }), null);
+                           
+                            LogHelper.logQueue = new System.Collections.Concurrent.ConcurrentQueue<string[]>();
                         }
-                    }
-                    if ( LogHelper.logQueue.Count > 100 ) 
-                    {
-                        LogHelper.logQueue = new System.Collections.Concurrent.ConcurrentQueue<string[]>();
-                    }
                         Thread.Sleep(200);
-                   
+
+                    }
+                }
+                catch(Exception ex)
+                {
+                
                 }
 
             });
@@ -56,6 +65,7 @@ namespace Toolkit
 
         private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
         {
+            
             Environment.Exit(0);
         }
     }

+ 0 - 40
Toolkit/View/ReadPlc.xaml

@@ -1,40 +0,0 @@
-<UserControl x:Class="Toolkit.View.ReadPlc"
-             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
-             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
-             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
-             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
-             xmlns:local="clr-namespace:Toolkit.View"
-             xmlns:prism="http://prismlibrary.com/"
-             prism:ViewModelLocator.AutoWireViewModel="True"
-             mc:Ignorable="d" 
-             d:DesignHeight="450" d:DesignWidth="800">
-    <Grid>
-        <Border Margin="40">
-             <Grid>
-                <Grid.ColumnDefinitions>
-                    <ColumnDefinition/>
-                    <ColumnDefinition/>
-                </Grid.ColumnDefinitions>
-                <StackPanel Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Left" Orientation="Horizontal">
-                    <Label Content="写入:" Foreground="White"></Label>
-                    <TextBlock Text="{Binding data}" Foreground="White" Margin="5"/>
-                </StackPanel>
-                <StackPanel Grid.Column="1" VerticalAlignment="Center" HorizontalAlignment="Right" Orientation="Horizontal">
-                    <Label Content="结果:" Foreground="White"></Label>
-                    <RichTextBox Margin="5" Width="150" Height="auto" Foreground="Black" >
-                        <RichTextBox.Document>
-                            <FlowDocument>
-                                <Paragraph >
-                                    <Run Text="{Binding res}">
-                                    </Run>
-                                </Paragraph>
-                            </FlowDocument>
-                        </RichTextBox.Document>
-                    </RichTextBox>
-                  
-
-                </StackPanel>
-            </Grid>
-        </Border>
-    </Grid>
-</UserControl>

+ 0 - 28
Toolkit/View/ReadPlc.xaml.cs

@@ -1,28 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using System.Windows;
-using System.Windows.Controls;
-using System.Windows.Data;
-using System.Windows.Documents;
-using System.Windows.Input;
-using System.Windows.Media;
-using System.Windows.Media.Imaging;
-using System.Windows.Navigation;
-using System.Windows.Shapes;
-
-namespace Toolkit.View
-{
-    /// <summary>
-    /// ReadPlc.xaml 的交互逻辑
-    /// </summary>
-    public partial class ReadPlc : UserControl
-    {
-        public ReadPlc()
-        {
-            InitializeComponent();
-        }
-    }
-}

+ 0 - 38
Toolkit/View/TcpTrigger.xaml

@@ -1,38 +0,0 @@
-<UserControl x:Class="Toolkit.View.TcpTrigger"
-             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
-             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
-             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
-             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
-             xmlns:local="clr-namespace:Toolkit.View"
-             xmlns:prism="http://prismlibrary.com/"
-             prism:ViewModelLocator.AutoWireViewModel="True"
-             Background="BlanchedAlmond"
-             mc:Ignorable="d" Height="223" Width="270">
-    <Grid>
-        <Border Margin="10" Background="{Binding BackgroundColor}">
-            <Grid>
-                <Grid.ColumnDefinitions>
-                    <ColumnDefinition/>
-                    <ColumnDefinition/>
-                </Grid.ColumnDefinitions>
-                <StackPanel Grid.Column="0" VerticalAlignment="Top" HorizontalAlignment="Left" Orientation="Vertical">
-                    <Label Content="接收:" Foreground="Black"></Label>
-                    <TextBlock Text="{Binding Data}" Foreground="Black" Margin="5"/>
-                </StackPanel>
-                <StackPanel Grid.Column="1" VerticalAlignment="Top" HorizontalAlignment="Right" Orientation="Vertical">
-                    <Label Content="结果:" Foreground="Black"></Label>
-                    <RichTextBox Margin="5" Width="80" Height="auto" Foreground="Black" >
-                        <RichTextBox.Document>
-                            <FlowDocument>
-                                <Paragraph >
-                                    <Run Text="{Binding Res}">
-                                    </Run>
-                                </Paragraph>
-                            </FlowDocument>
-                        </RichTextBox.Document>
-                    </RichTextBox>
-                </StackPanel>
-            </Grid>
-        </Border>
-    </Grid>
-</UserControl>

+ 0 - 29
Toolkit/View/TcpTrigger.xaml.cs

@@ -1,29 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using System.Windows;
-using System.Windows.Controls;
-using System.Windows.Data;
-using System.Windows.Documents;
-using System.Windows.Input;
-using System.Windows.Media;
-using System.Windows.Media.Imaging;
-using System.Windows.Navigation;
-using System.Windows.Shapes;
-
-namespace Toolkit.View
-{
-    /// <summary>
-    /// TcpTrigger.xaml 的交互逻辑
-    /// </summary>
-    public partial class TcpTrigger : UserControl
-    {
-        public TcpTrigger()
-        {
-            InitializeComponent();
-            
-        }
-    }
-}

+ 0 - 39
Toolkit/View/TcpWrite.xaml

@@ -1,39 +0,0 @@
-<UserControl x:Class="Toolkit.View.TcpWrite"
-             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
-             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
-             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
-             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
-             xmlns:local="clr-namespace:Toolkit.View"
-             mc:Ignorable="d" 
-             xmlns:prism="http://prismlibrary.com/"
-             prism:ViewModelLocator.AutoWireViewModel="True"
-             Background="BlanchedAlmond"
-             Height="223" Width="270">
-    <Grid>
-        <Border Margin="10" Background="{Binding BackgroundColor}">
-            <Grid>
-                <Grid.ColumnDefinitions>
-                    <ColumnDefinition/>
-                    <ColumnDefinition/>
-                </Grid.ColumnDefinitions>
-                <StackPanel Grid.Column="0" VerticalAlignment="Top" HorizontalAlignment="Left" Orientation="Vertical">
-                    <Label Content="写入:" Foreground="Black"></Label>
-                    <TextBlock Text="{Binding Data}" Foreground="Black" Margin="5"/>
-                </StackPanel>
-                <StackPanel Grid.Column="1" VerticalAlignment="Top" HorizontalAlignment="Right" Orientation="Vertical">
-                    <Label Content="结果:" Foreground="Black"></Label>
-                    <RichTextBox Margin="5" Width="80" Height="auto" Foreground="Black" >
-                        <RichTextBox.Document>
-                            <FlowDocument>
-                                <Paragraph >
-                                    <Run Text="{Binding Res_write}">
-                                    </Run>
-                                </Paragraph>
-                            </FlowDocument>
-                        </RichTextBox.Document>
-                    </RichTextBox>
-                </StackPanel>
-            </Grid>
-        </Border>
-    </Grid>
-</UserControl>

+ 0 - 28
Toolkit/View/TcpWrite.xaml.cs

@@ -1,28 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using System.Windows;
-using System.Windows.Controls;
-using System.Windows.Data;
-using System.Windows.Documents;
-using System.Windows.Input;
-using System.Windows.Media;
-using System.Windows.Media.Imaging;
-using System.Windows.Navigation;
-using System.Windows.Shapes;
-
-namespace Toolkit.View
-{
-    /// <summary>
-    /// TcpWrite.xaml 的交互逻辑
-    /// </summary>
-    public partial class TcpWrite : UserControl
-    {
-        public TcpWrite()
-        {
-            InitializeComponent();
-        }
-    }
-}

+ 0 - 37
Toolkit/View/WritePcl.xaml

@@ -1,37 +0,0 @@
-<UserControl x:Class="Toolkit.View.WritePcl"
-             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
-             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
-             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
-             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
-             xmlns:local="clr-namespace:Toolkit.View"
-             mc:Ignorable="d" 
-             d:DesignHeight="450" d:DesignWidth="800">
-    <Grid>
-        <Border Margin="40">
-            <Grid>
-                <Grid.ColumnDefinitions>
-                    <ColumnDefinition/>
-                    <ColumnDefinition/>
-                </Grid.ColumnDefinitions>
-                <StackPanel Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Left" Orientation="Horizontal">
-                    <Label Content="读取:" Foreground="White"></Label>
-                    <TextBlock Text="{Binding data}" Foreground="White" Margin="5"/>
-                </StackPanel>
-                <StackPanel Grid.Column="1" VerticalAlignment="Center" HorizontalAlignment="Right" Orientation="Horizontal">
-                    <Label Content="结果:" Foreground="White"></Label>
-                    <RichTextBox Margin="5" Width="150" Height="auto" Foreground="Black" >
-                        <RichTextBox.Document>
-                            <FlowDocument>
-                                <Paragraph >
-                                    <Run Text="{Binding res}">
-                                    </Run>
-                                </Paragraph>
-                            </FlowDocument>
-                        </RichTextBox.Document>
-                    </RichTextBox>
-
-                </StackPanel>
-            </Grid>
-        </Border>
-    </Grid>
-</UserControl>

+ 0 - 28
Toolkit/View/WritePcl.xaml.cs

@@ -1,28 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using System.Windows;
-using System.Windows.Controls;
-using System.Windows.Data;
-using System.Windows.Documents;
-using System.Windows.Input;
-using System.Windows.Media;
-using System.Windows.Media.Imaging;
-using System.Windows.Navigation;
-using System.Windows.Shapes;
-
-namespace Toolkit.View
-{
-    /// <summary>
-    /// WritePcl.xaml 的交互逻辑
-    /// </summary>
-    public partial class WritePcl : UserControl
-    {
-        public WritePcl()
-        {
-            InitializeComponent();
-        }
-    }
-}

+ 252 - 65
Toolkit/ViewMode/MainWindowViewMode.cs

@@ -1,4 +1,7 @@
-using Prism.Mvvm;
+using log4net.Core;
+using Prism.Events;
+using Prism.Ioc;
+using Prism.Mvvm;
 using Prism.Regions;
 using System;
 using System.Collections.Generic;
@@ -8,110 +11,294 @@ using System.Linq;
 using System.Net;
 using System.Net.Sockets;
 using System.Reflection;
+using System.Reflection.Emit;
 using System.Text;
 using System.Threading;
 using System.Threading.Tasks;
+using System.Windows;
 using System.Windows.Controls;
+using System.Windows.Interop;
 using System.Windows.Media;
+using System.Windows.Media.Media3D;
+using Toolkit.Core;
+using Toolkit.Event;
 using Toolkit.Log4;
 using Toolkit.Tcp;
-using Toolkit.View;
+using TouchSocket.Core;
+using TouchSocket.Sockets;
 
 namespace Toolkit.ViewMode
 {
     public class MainWindowViewMode : BindableBase
     {
+        private BgCommunicate bgCommunicate;
+        private ClientCommunicate clientCommunicate;
+        EventAggregator _eventAggregator;
+        private Management mana_gement;
+        private  string _Errstr="";
+        private SolidColorBrush _rushes= Brushes.Red;
+        private int SengState=0;
+        private int errCount=0;
+        private Stepenum stepenum= Stepenum.RecvPD;
+        public string Errstr { get => _Errstr; set { SetProperty(ref _Errstr, value); } }
+        public SolidColorBrush Rushes { get => _rushes; set { SetProperty(ref _rushes, value); } }
+
+        public MainWindowViewMode(IRegionManager regionManager, EventAggregator eventAggregator, IContainerProvider container)
+        {
+
 
-        private ObservableCollection<UserControl> items = new ObservableCollection<UserControl>();
-        public ObservableCollection<UserControl> Items { get => items; set => items = value; }
 
+            mana_gement = container.Resolve<Management>();
+            //string ss=";ver:1.0;packinfo:1/1;tasktype:821;positions:F;dep_name:广州分行1;taskstatus:0;datetime:2025-06-25;phone:12345678901;deal_name:gan0001;recv_date:2025-06-27;suminfo:[amount<500>currcycode<CNY>];client_name:gan0011;items:[amount<500>currcycode<CNY>itdetail<100|5>];seqid:c47367c30df7485d89ca2923b33128a2;taskid:242ad029597a483f989a64f74caffe4a;tasknum:062500011;totalpack:1;packno:1;";
+            //string datsssa = mana_gement.MsgSplit(ss);
 
-        public List<ToolBase.ToolBase> ToolBases = new List<ToolBase.ToolBase>();
-        public MainWindowViewMode(IRegionManager regionManager) 
+            clientCommunicate = new ClientCommunicate();
+            clientCommunicate.ConnectedEvent += ClientCommunicate_ConnectedEvent;
+            clientCommunicate.ReceivedEvent += ClientCommunicate_ReceivedEvent;
+            clientCommunicate.DisconnectedEvent += ClientCommunicate_DisconnectedEvent;
+            clientCommunicate.ConnectAsync();
+            _eventAggregator = eventAggregator;
+
+
+        }
+        private void ClientCommunicate_DisconnectedEvent(Guid arg1, object arg2, DisconnectEventArgs arg3)
         {
-           
-            TcpTrigger trigger = new TcpTrigger();
-            Items.Add(trigger);
-            ToolBases.Add((TcpTriggerViewMode)trigger.DataContext);
+            _Errstr = "打印机断开";
+            Rushes = Brushes.Red;
+            LogHelper.Info("打印机断开!");
 
-            TcpWrite tcpWrite= new TcpWrite();
-            Items.Add(tcpWrite);
-            ToolBases.Add((TcpWriteViewMode)tcpWrite.DataContext);
+            if ( bgCommunicate != null ) bgCommunicate.Dispose();
+        }
 
+        private async void ClientCommunicate_ReceivedEvent(Guid arg1, object arg2, ReceivedDataEventArgs e)
+        {
+            try
+            {
+                string msg=Encoding.UTF8.GetString(e.ByteBlock.Buffer, 0, e.ByteBlock.Len);
+               // e.ByteBlock.Clear();
+                LogHelper.Info("打印机返回消息:" + msg);
+                await ReceivedForPrint(msg);
+            }
+            catch ( Exception ex )
+            {
+                LogHelper.error.Error(ex.ToString());
+            }
 
+        }
+
+        private void ClientCommunicate_ConnectedEvent(Guid arg1, object arg2, ConnectedEventArgs arg3)
+        {
+            ITcpClient socketClient = arg2 as ITcpClient;
+            LogHelper.Info($"[{socketClient.IP}]已连接打印机!");
+            bgCommunicate = new BgCommunicate();
+            bgCommunicate.ConnectedEvent += BgCommunicate_ConnectedEvent;
+            bgCommunicate.ReceivedEvent += BgCommunicate_ReceivedEvent;
+            bgCommunicate.StartListening();
+            Rushes = Brushes.Green;
+        }
+
+        private void BgCommunicate_ReceivedEvent(SocketClient arg1, string arg2)
+        {
+            LogHelper.Info("收到PLC数据" + arg2);
+            Errstr = "";
+            SendMsgToPrint(arg2);
+        }
+
+        private void BgCommunicate_ConnectedEvent(TouchSocket.Sockets.SocketClient arg1, TouchSocket.Sockets.ConnectedEventArgs arg2)
+        {
+
+            LogHelper.Info($"[{arg1.ServicePort}][{arg1.IP}]已连接!");
+        }
 
+        private async void SendMsgToPrint(string msg)
+        {
+            
+            if ( msg != "GetMessage" )
+            {
+              stepenum = Stepenum.RecvPD;
+              await   SendMsgToPrintData(msg);
+            }
+            else
+            {
+              await  SendMsgToGetPrintState();
+            }
+        }
 
-            Task.Run(()=> 
+        private async Task SendMsgToPrintData(string msg)
+        {
+            try
             {
-                TcpTriggerViewMode tcpTrigger=( TcpTriggerViewMode ) ToolBases[0];
-                TcpWriteViewMode  Write=( TcpWriteViewMode ) ToolBases[1];
-                //string ss=" ;ver:1.0;tasktype:821;positions:B;dep_name:广东分行(小面额压力);taskstatus:0;datetime:2025-04-25;phone:13719220892;deal_name:pan892;recv_date:2025-04-25;client_name:tan892;items:[amount<10>currcycode<CNY>itdetail<5|2>];seqid:f804668a132247359f829dce37f7cdf9;taskid:51ee718cfa1a4b30b6dfde13e70982b4;tasknum:C2025033992;totalpack:1;packno:1;";
-                //string datsssa = Write.MsgSplit(ss);
-                Stopwatch stopwatch = new Stopwatch();
-                while ( true) 
+                if ( stepenum == Stepenum.RecvPD )
                 {
-                    try
+                    string data= mana_gement.MsgSplit(msg);
+                    if ( data != "Err" )
                     {
-                        
-                        if ( tcpTrigger.SendStrs.Count != 0 && Write.client.socket.Connected)
+                        LogHelper.Info("发送Outdata");
+                        clientCommunicate.Send("outdata");
+                        LogHelper.Info("发送Outdata");
+                        byte []res=mana_gement.GetData(data);
+                        LogHelper.Info("发送数据" + data);
+                        clientCommunicate.Send(res);
+                        LogHelper.Info("发送数据完成");
+                        stepenum = Stepenum.SendData;
+                    }
+                }
+            }
+            catch ( Exception ex )
+            {
+               
+                LogHelper.error.Error("发送打印机消息错误:Data", ex);
+
+            }
+        }
+
+        private async Task SendMsgToGetPrintState(bool isrun=true)
+        {
+            try
+            {
+                if ( isrun )
+                {
+                    LogHelper.Info("fun22");
+                    clientCommunicate.Send("fun");
+                    clientCommunicate.Send("22");
+                    LogHelper.Info("fun22完成");
+                }
+                LogHelper.Info("fun25");
+                clientCommunicate.Send("fun");
+                clientCommunicate.Send("25");
+                LogHelper.Info("fun25完成");
+            }
+            catch ( Exception ex )
+            {
+               
+
+                LogHelper.error.Error("发送打印机消息错误:fun", ex);
+
+            }
+        }
+       
+        private async Task ReceivedForPrint(string msg)
+        {
+            try
+            {
+
+                switch ( msg )
+                {
+                    case "*T#":
+                        LogHelper.Info("打印机返回消息:已收到数据");
+                        if(stepenum== Stepenum.SendData)
+                        stepenum = Stepenum.RecvTD;
+                        break;
+                    case "*P#":
+                        LogHelper.Info("打印机返回消息:已打印数据");
+                        if ( stepenum == Stepenum.RecvTD )
                         {
-                            stopwatch.Restart();
-                            
-                            Write.Tdata = tcpTrigger.SendStrs[ 0 ];
-                            if ( Write.Tdata == "GetMessage" ) 
+                            stepenum = Stepenum.RecvPD;
+                            await SendMsgToGetPrintState(false);
+                            errCount = 0;
+                        }
+                        else 
+                        {
+                            if ( stepenum == Stepenum.SendData )
                             {
-                                if ( !Write.GetMessage() ) 
+                                if ( errCount < 3 )
                                 {
-                                    Write.client.socket.Close();
-                                    LogHelper.Info("打印机断开");
+                                    stepenum = Stepenum.RecvPD;
+                                    await SendMsgToGetPrintState(false);
                                 }
+                                errCount++;
                                 
-                                ToolBases[ 0 ].SendStrs.RemoveAt(0);
-                                continue;
                             }
-                            if ( Write.SendMsg(tcpTrigger) )
-                            {
-                                ToolBases[ 0 ].SendStrs.RemoveAt(0);
-                               
-                            }
-                        }
-                        if ( !Write.client.socket.Connected)
-                        {
-                            
-                                Thread.Sleep(10);
-                                tcpTrigger.TcpServerStop();
-                                Write.client.socket.Close();
-                                LogHelper.Info("打印机断开");
-                                Write.client.Connect();
-                                if ( Write.client.socket.Connected )
-                                {
-                                    LogHelper.Info("打印机连接成功");
-                                    tcpTrigger.server.Start();
-                                }
-                            
                         }
-                       
-                    }
-                    catch(Exception e) 
-                    {
-                       
-                        LogHelper.Info(e.Message);
-                        Thread.Sleep(3000);
-                    }
-                    Thread.Sleep(50);
-                }
+                        break;
+                    case "*M#":
+                        Errstr = "打印机返回消息:数据宽度超出";
+                        LogHelper.Info("打印机返回消息:数据宽度超出");
+                        break;
+                    case "*F#":
+                        Errstr = "打印机返回消息:发送数据失败";
+                        LogHelper.Info("打印机返回消息:发送数据失败");
+                        break;
+                    case "*W#":
+                        Errstr = "打印机返回消息:故障";
+                        LogHelper.Info("打印机返回消息:故障");
+                        break;
+                    case "*L#":
+                        Errstr = "打印机返回消息:超出设定段数";
+                        LogHelper.Info("打印机返回消息:超出设定段数");
+                        break;
 
-            });
+                    default:
+                        if ( msg.Contains("OKhp") )
+                        {
+                            LogHelper.Info("打印机返回消息:OKhp");
+                            if ( msg.Contains("fun") )
+                            {
+                                msg.Remove(0, msg.IndexOf("OKhp"));
+                            }
+                            string []strs=msg.Split(',');
+                            PlcMsg plcMsg = new PlcMsg();
+                            if ( strs[ 4 ] == "0" )
+                            {
+                                plcMsg.printer = "0";
+                            }
+                            else
+                            {
+                                plcMsg.printer = "1";
+                            }
+                            if ( strs[ 5 ] == "0" )
+                            {
+                                plcMsg.printer = "1";
+                            }
+                            else
+                            {
+                                plcMsg.printer = "0";
+                            }
 
+                            int ribbon=Convert.ToInt32(strs[ 29 ]);
+                            if ( ribbon > 30 )
+                            {
+                                plcMsg.ribbon = "0";
+                            }
+                            if ( ribbon < 30 )
+                            {
+                                plcMsg.ribbon = "0";
+                            }
 
-            
+                            if ( ribbon <= 1 )
+                            {
+                                plcMsg.ribbon = "2";
+                            }
 
+                            Type personType = plcMsg.GetType();
 
-           
+                            PropertyInfo[] properties = plcMsg.GetType().GetProperties();
 
+                            StringBuilder builder= new StringBuilder();
+                            for ( int j = 0; j < properties.Length - 1; j++ )
+                            {
+                                builder.Append(properties[ j ].Name + ":" + properties[ j ].GetValue(plcMsg) + ",");
+                            }
+                            builder.Append(properties[ properties.Length - 1 ].Name + ":" + properties[ properties.Length - 1 ].GetValue(plcMsg));
 
+                            string sss=builder.ToString();
+                            LogHelper.Info("发送给Plc:"+sss);
+                            bgCommunicate.Send(builder.ToString());
+                            break;
+                        }
+                        break;
+                }
+            }
+            catch ( Exception ex )
+            {
 
+               
+                LogHelper.error.Error("解析打印机消息错误", ex);
 
+            }
         }
+
+
+
     }
 }

+ 0 - 73
Toolkit/ViewMode/TcpTriggerViewMode.cs

@@ -1,73 +0,0 @@
-using Prism.Events;
-using Prism.Mvvm;
-using Prism.Regions;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using System.Windows.Media;
-using Toolkit.Event;
-using Toolkit.Log4;
-using Toolkit.Tcp;
-
-namespace Toolkit.ViewMode
-{
-    public class TcpTriggerViewMode:ToolBase.ToolBase
-    {
-
-        private string data = "0";
-        private string res = "0";
-
-        public string Data { get => data; set { SetProperty(ref data, value); } }
-        public TCPServer server = new TCPServer();
-        public string Res
-        {
-            get => res;
-            set
-            {
-                SetProperty(ref res, value);
-               
-            }
-        }
-
-        
-
-        public TcpTriggerViewMode(IEventAggregator eventAggregator, IRegionManager regionManager) 
-        {
-            server.Start();
-            TCPServer.eventAggregator = eventAggregator;
-            eventAggregator.GetEvent<TcpServerMsg>().Subscribe(TcpServerUse);
-            LogHelper.Info("订阅服务器消息");
-
-        }
-
-        public void TcpServerUse(string Msg) 
-        {
-            BackgroundColor = Brushes.White;
-            this.Data = Msg;
-            if (Msg != null && Msg.Length > 1)
-            {
-                LogHelper.Info("收到订阅消息:"+ Msg);
-                SendStrs.Add(Msg);
-                this.Tres = Msg;
-                LogHelper.Info(Msg);
-                this.Res = "OK";
-                BackgroundColor = Brushes.Green;
-            }
-            else
-            {
-                LogHelper.Info("收到订阅消息:错误" );
-                BackgroundColor = Brushes.Red;
-            }
-        
-        }
-
-
-        public void TcpServerStop() 
-        {
-        server?.Stop();
-        }
-        
-    }
-}

+ 0 - 749
Toolkit/ViewMode/TcpWriteViewMode.cs

@@ -1,749 +0,0 @@
-using Microsoft.SqlServer.Server;
-using Prism.Mvvm;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Net.Sockets;
-using System.Reflection;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using System.Windows;
-using System.Windows.Controls;
-using System.Windows.Media;
-using Toolkit.Log4;
-using Toolkit.Tcp;
-using Toolkit.View;
-using static Toolkit.Tcp.TCPServer;
-
-namespace Toolkit.ViewMode
-{
-    public class TcpWriteViewMode : ToolBase.ToolBase
-    {
-
-        private string data = "0";
-        private string res = "0";
-
-        public string Data { get => data; set { SetProperty(ref data, value); } }
-
-        public string Res_write
-        {
-            get => res;
-            set
-            {
-                SetProperty(ref res, value);
-
-            }
-        }
-
-
-
-        public TCPClient client = new TCPClient();
-
-        Task task;
-        public TcpWriteViewMode()
-        {
-            int a = 0;
-            
-        }
-        public bool SendMsg(TcpTriggerViewMode tcpTrigger)
-        {
-          
-            try
-            {
-
-                BackgroundColor = Brushes.White;
-                string data = MsgSplit(this.Tdata);
-                this.Data =data;
-                if (data != "Err")
-                {
-
-                    string str;
-                   
-                    str = client.SendLinux(data);
-                    LogHelper.Info(str);
-                    // str = client.ReceiveVarData(client.socket);
-
-                    bool isagain=true;
-                    while (true)
-                    {
-                        str = client.ReceiveVarData(client.socket);
-
-                        if (str != "未收到数据" && str != "未连接")
-                        {
-
-                            if (str == "*T#")
-                            {
-                                isagain = true;
-                                LogHelper.Info(str);
-                                break;
-                            }
-                        }
-                        if ( str == "未连接" ) 
-                        {
-                            LogHelper.Info(str);
-                            tcpTrigger.TcpServerStop();
-                            return false;
-                        }
-                        if ( str == "未收到数据"&& !isagain ) 
-                        {
-                            isagain = false;
-                            LogHelper.Info(str);
-                            SendNg();
-                            return false;
-                        }
-                    }
-                    while (true)
-                    {
-                        str = client.ReceiveVarData(client.socket);
-
-                        if (str != "未收到数据" && str != "未连接")
-                        {
-
-                            if (str == "*P#")
-                            {
-                                isagain = true;
-                                LogHelper.Info(str);
-                                break;
-                            }
-                        }
-                        if ( str == "未连接" )
-                        {
-                            tcpTrigger.TcpServerStop();
-                            return false;
-                        }
-                        if ( str == "未收到数据" )
-                        {
-                            if ( tcpTrigger.SendStrs.Count > 1 )
-                            {
-                                LogHelper.Info("未收到打印完成信号");
-                                return true;
-                            }
-                        }
-                    }
-
-                    SendNetCmd(client.socket,"25");
-                    while ( true )
-                    {
-                        str = client.ReceiveVarData(client.socket);
-
-                        if ( str != "未收到数据" && str != "未连接" )
-                        {
-
-                            if ( str == "fun" )
-                            {
-                                isagain = true;
-                                LogHelper.Info(str);
-                                break;
-                            }
-                        }
-
-                        if ( str == "未连接" )
-                        {
-                            tcpTrigger.TcpServerStop();
-                            return false;
-                        }
-                        if ( str == "未收到数据" && !isagain )
-                        {
-                            isagain = false;
-                            LogHelper.Info(str);
-                            SendNg();
-                            return false;
-                        }
-                    }
-
-                    while ( true )
-                    {
-                        str = client.ReceiveVarData(client.socket);
-
-                        if ( str != "未收到数据" && str != "未连接" )
-                        {
-
-                            if ( str == "25" )
-                            {
-                                isagain = true;
-                                LogHelper.Info(str);
-                                break;
-                            }
-                        }
-                        if ( str == "未连接" )
-                        {
-                            tcpTrigger.TcpServerStop();
-                            return false;
-                        }
-                        if ( str == "未收到数据" && !isagain )
-                        {
-                            isagain = false;
-                            LogHelper.Info(str);
-                            SendNg();
-                            return false;
-                        }
-                    }
-                    int again=0;
-                    while ( true )
-                    {
-                        str = client.ReceiveVarData(client.socket);
-
-                        if ( str != "未收到数据" && str != "未连接" )
-                        {
-
-                            if ( str .Contains( "OKhp") )
-                            {
-                                isagain = true;
-                                string []strs=str.Split(',');
-                                PlcMsg plcMsg = new PlcMsg();
-                                if ( strs[ 4 ] == "0" )
-                                {
-                                    plcMsg.printer = "0";
-                                }
-                                else 
-                                {
-                                    plcMsg.printer = "1";
-                                }
-                                if ( strs[ 5 ] == "0" )
-                                {
-                                    Thread.Sleep(1000);
-                                    SendNetCmd(client.socket, "25");
-                                    again++;
-                                    if ( again < 3 )
-                                    {
-                                        continue;
-                                    }
-                                    plcMsg.printer = "1";
-                                }
-                                else
-                                {
-                                    plcMsg.printer = "0";
-                                }
-                                int ribbon=Convert.ToInt32(strs[ 29 ]);
-                                if ( ribbon > 30 )
-                                {
-                                    plcMsg.ribbon = "0";
-                                }
-                                if ( ribbon < 30 )
-                                {
-                                    plcMsg.ribbon = "0";
-                                }
-
-                                if ( ribbon <=1 )
-                                {
-                                    plcMsg.ribbon = "2";
-                                }
-
-                                Type personType = plcMsg.GetType();
-
-                                PropertyInfo[] properties = plcMsg.GetType().GetProperties();
-
-                                 StringBuilder builder= new StringBuilder();
-                                    for ( int j = 0; j < properties.Length-1; j++ )
-                                    {
-                                    builder.Append(properties[ j ].Name + ":" + properties[ j ].GetValue(plcMsg)+",");  
-                                    }
-                                builder.Append(properties[ properties.Length-1 ].Name + ":" + properties[ properties.Length - 1 ].GetValue(plcMsg));
-
-                                string sss=builder.ToString();
-                                TCPServer.clientList[ 0 ].SendMessage(builder.ToString());
-                                LogHelper.Info(sss);
-                                break;
-                            }
-                        }
-
-                        if ( str == "未连接" )
-                        {
-                            tcpTrigger.TcpServerStop();
-                            return false;
-                        }
-                        if ( str == "未收到数据" && !isagain )
-                        {
-                            isagain = false;
-                            LogHelper.Info(str);
-                            SendNg();
-                            return false;
-                        }
-                    }
-
-
-                    Res_write = str;
-                    BackgroundColor = Brushes.Green;                    
-                }
-                else 
-                {
-                    BackgroundColor = Brushes.Red;
-                }
-            }
-            catch 
-            {
-                BackgroundColor = Brushes.Red;
-            }
-
-
-            return true;
-        }
-
-        public bool SendNetCmd(Socket internetSocket, string cmd)
-        {
-            if ( SendVarData(internetSocket, Encoding.UTF8.GetBytes("fun")) != -1 )
-            {
-                SendVarData(internetSocket, Encoding.UTF8.GetBytes(cmd));
-                return true;
-            }
-            else 
-            {
-                return false;
-            }
-        }
-        public int SendVarData(Socket s, byte[] data)
-        {
- 
-            if ( s == null )
-                return -1;
-            string datas = "";
-            try
-            {
-                int total = 0;
-                int size = data.Length;
-                int dataleft = size;
-                int sent;
-                byte[] datasize = new byte[4];
-                datasize = BitConverter.GetBytes(size);
-                s.SendTimeout = 1000;
-                sent = s.Send(datasize);
-                datas = "";
-                while ( total < size )
-                {
-                    sent = s.Send(data, total, dataleft, SocketFlags.None);
-                    total += sent;
-                    dataleft -= sent;
-                }
-                
-                return total;
-            }
-            catch
-            {
-               
-                return -1;
-            }
-        }
-
-        public bool GetMessage() 
-        {
-            string  str;
-            try
-            {
-                SendNetCmd(client.socket, "22");
-                Thread.Sleep(100);
-            }
-            catch 
-            {
-                LogHelper.Info("打印机故障");
-            }
-           SendNetCmd(client.socket, "25");
-       
-            while ( true )
-            {
-                str = client.ReceiveVarData(client.socket);
-
-                if ( str != "未收到数据" && str != "未连接" )
-                {
-
-                    if ( str == "fun" )
-                    {
-                        LogHelper.Info(str);
-                        break;
-                    }
-                }
-
-                if ( str == "未连接" )
-                {
-                   
-                    return false;
-                }
-                if ( str == "未收到数据" )
-                {
-                    return false;
-                }
-            }
-
-            while ( true )
-            {
-                str = client.ReceiveVarData(client.socket);
-
-                if ( str != "未收到数据" && str != "未连接" )
-                {
-
-                    if ( str == "25" )
-                    {
-                        LogHelper.Info(str);
-                        break;
-                    }
-                }
-                if ( str == "未连接" )
-                {
-                    
-                    return false;
-                }
-                if ( str == "未收到数据" )
-                {
-                    return false;
-                }
-            }
-            int again=0;
-            while ( true )
-            {
-                str = client.ReceiveVarData(client.socket);
-
-                if ( str != "未收到数据" && str != "未连接" )
-                {
-
-                    if ( str.Contains("OKhp") )
-                    {
-                        string []strs=str.Split(',');
-                        PlcMsg plcMsg = new PlcMsg();
-                        if ( strs[ 4 ] == "0" )
-                        {
-                            plcMsg.printer = "0";
-                        }
-                        else
-                        {
-                            plcMsg.printer = "1";
-                        }
-                        if ( strs[ 5 ] == "0" )
-                        {
-                            if( again !=0)
-                            Thread.Sleep(1000);
-                            SendNetCmd(client.socket, "25");
-                            again++;
-                            if ( again < 3 ) 
-                            {
-                                continue;
-                            }
-                            plcMsg.printer = "1";
-                        }
-                        else
-                        {
-                            plcMsg.printer = "0";
-                        }
-                       
-                        int ribbon=Convert.ToInt32(strs[ 29 ]);
-                        if ( ribbon > 30 )
-                        {
-                            plcMsg.ribbon = "0";
-                        }
-                        if ( ribbon < 30 )
-                        {
-                            plcMsg.ribbon = "0";
-                        }
-
-                        if ( ribbon <= 1 )
-                        {
-                            plcMsg.ribbon = "2";
-                        }
-
-                        Type personType = plcMsg.GetType();
-
-                        PropertyInfo[] properties = plcMsg.GetType().GetProperties();
-
-                        StringBuilder builder= new StringBuilder();
-                        for ( int j = 0; j < properties.Length - 1; j++ )
-                        {
-                            builder.Append(properties[ j ].Name + ":" + properties[ j ].GetValue(plcMsg) + ",");
-                        }
-                        builder.Append(properties[ properties.Length - 1 ].Name + ":" + properties[ properties.Length - 1 ].GetValue(plcMsg));
-
-                        string sss=builder.ToString();
-                        TCPServer.clientList[ 0 ].SendMessage(builder.ToString());
-                        
-                        break;
-                    }
-                }
-
-                if ( str == "未连接" )
-                {
-                    
-                    return false;
-                }
-                if ( str == "未收到数据" )
-                {
-                    return false;
-                }
-            }
-
-
-            return true;
-        }
-
-        public void SendNg() 
-        {
-
-            PlcMsg plcMsg = new PlcMsg();
-           
-            plcMsg.printer = "1";
-           
-            Type personType = plcMsg.GetType();
-
-            PropertyInfo[] properties = plcMsg.GetType().GetProperties();
-
-            StringBuilder builder= new StringBuilder();
-            for ( int j = 0; j < properties.Length - 1; j++ )
-            {
-                builder.Append(properties[ j ].Name + ":" + properties[ j ].GetValue(plcMsg) + ",");
-            }
-            builder.Append(properties[ properties.Length - 1 ].Name + ":" + properties[ properties.Length - 1 ].GetValue(plcMsg));
-
-            string sss=builder.ToString();
-            TCPServer.clientList[ 0 ].SendMessage(builder.ToString());
-            LogHelper.Info(sss);
-
-        }
-        public bool GetConnect()
-        {
-            Thread.Sleep(20);
-            string  str;
-            client.socket.SendTimeout = 100;
-            SendNetCmd(client.socket, "25");
-
-            while ( true )
-            {
-                client.socket.ReceiveTimeout = 100;
-                str = client.ReceiveVarData(client.socket);
-
-                if ( str != "未收到数据" && str != "未连接" )
-                {
-
-                    if ( str == "fun" )
-                    {
-                        
-                        break;
-                    }
-                }
-
-                if ( str == "未连接" )
-                {
-
-                    return false;
-                }
-                if ( str == "未收到数据" )
-                {
-                    return false;
-                }
-            }
-
-            while ( true )
-            {
-                str = client.ReceiveVarData(client.socket);
-
-                if ( str != "未收到数据" && str != "未连接" )
-                {
-
-                    if ( str == "25" )
-                    {
-                        
-                        break;
-                    }
-                }
-                if ( str == "未连接" )
-                {
-
-                    return false;
-                }
-                if ( str == "未收到数据" )
-                {
-                    return false;
-                }
-            }
-            int again=0;
-            while ( true )
-            {
-                str = client.ReceiveVarData(client.socket);
-
-                if ( str != "未收到数据" && str != "未连接" )
-                {
-
-                    if ( str.Contains("OKhp") )
-                    {
-                        
-                        break;
-                    }
-                }
-
-                if ( str == "未连接" )
-                {
-
-                    return false;
-                }
-                if ( str == "未收到数据" )
-                {
-                    return false;
-                }
-            }
-
-            Thread.Sleep(20);
-            return true;
-        }
-        public string MsgSplit(string str)
-        {
-
-           StringBuilder sb = new StringBuilder();
-            try
-            {
-
-                str = str.Trim();
-                string[] strs = str.Split(';');
-
-                MesMsg msg = new MesMsg();
-
-                Type personType = msg.GetType();
-
-                PropertyInfo[] properties = msg.GetType().GetProperties();
-
-                for (int i = 0; i < strs.Length; i++)
-                {
-                    for (int j = 0; j < properties.Length; j++)
-                    {
-                        string temp=strs[ i ].Split(':')[ 0 ].ToString();
-                        if (temp.Trim() == properties[j].Name)
-                        {
-                            string []splits=strs[ i ].Split(':');
-                            string splitst="";
-                            //if ( splits.Length > 2 )
-                            //{
-                            //    string[] newArray = new string[splits.Length - 1];
-                            //    Array.Copy(splits, 1, newArray, 0, newArray.Length);
-                            //    splits[ 0 ] = "";
-                            //    splitst = string.Join(":", newArray);
-                               
-                            //}
-                            //else 
-                            //{
-                                splitst = strs[ i ].Split(':')[ 1 ];
-                           // }
-                            properties[ j ].SetValue(msg, splitst);
-                            break;
-                        }
-                    }
-                }
-
-
-                sb.Append(msg.tasknum +":|:");
-                sb.Append(msg.client_name + ":|:");
-                sb.Append(msg.datetime + ":|:");
-                sb.Append(msg.phone + ":|:");
-                string[] items = msg.items.Trim().Split(']');
-                string amount = "";
-                string amountT="0";
-                for (int i = 0; i < 4; i++)
-                {
-                    if ( items.Length > i )
-                    {
-                        if ( items[ i ].Length == 0 )
-                        {
-                            sb.Append(" " + ":|:");
-                            sb.Append(" " + ":|:");
-                            sb.Append(" " + ":|:");
-                            sb.Append(" " + ":|:");
-                            continue;
-                        }
-                        int startindex = items[i].IndexOf("<") + 1;
-                        int stopindex = items[i].IndexOf(">") - startindex;
-                        amount = items[ i ].Substring(startindex, stopindex);
-                        items[ i ] = items[ i ].Substring(items[ i ].IndexOf(">") + 1);
-                        startindex = items[ i ].IndexOf("<") + 1;
-                        stopindex = items[ i ].IndexOf(">") - startindex;
-                        string currcycode = items[i].Substring(startindex, stopindex);
-                        //items:[amount<300>currcycode<USD>itdetail<100 | 1,50 | 4 >][...];
-                        items[ i ] = items[ i ].Substring(items[ i ].IndexOf(">") + 1);
-                        string[] itdetail = items[i].Split(',');
-                        for ( int j = 0; j < itdetail.Length; j++ )
-                        {
-                            if(j!=0)
-                            i++;
-                            sb.Append(currcycode + ":|:");
-                            startindex = itdetail[ j ].IndexOf("<") + 1;
-                            stopindex = itdetail[ j ].IndexOf("|") - startindex;
-                            sb.Append((itdetail[ j ].Substring(startindex, stopindex)) + ":|:");
-                            int num = Convert.ToInt32(itdetail[j].Substring(startindex, stopindex));
-
-                            startindex = itdetail[ j ].IndexOf("|") + 1;
-                            stopindex = itdetail[ j ].IndexOf(">");
-                            if ( stopindex == -1 )
-                            {
-
-                                if ( itdetail[ j ].Substring(startindex) == "?" )
-                                {
-                                    sb.Append("?:|:");
-                                    sb.Append("?:|:");
-                                }
-                                else
-                                {
-                                    int count = Convert.ToInt32(itdetail[ j ].Substring(startindex));
-                                    sb.Append(count + ":|:");
-                                    sb.Append(num * count + ":|:");
-                                }
-                            }
-                            else
-                            {
-
-                                if ( itdetail[ j ].Substring(startindex, stopindex - startindex) == "?" )
-                                {
-                                    sb.Append("?:|:");
-                                    sb.Append("?:|:");
-
-                                }
-                                else 
-                                {
-                                    int count = Convert.ToInt32(itdetail[ j ].Substring(startindex, stopindex - startindex));
-                                    sb.Append(count + ":|:");
-                                    sb.Append(num * count + ":|:");
-                                }
-                                    
-                                
-                                
-                                
-                         
-                            }
-                        }
-                        if ( amount == "?" )
-                        {
-                            amountT ="?";
-                        }
-                        else 
-                        {
-                            amountT = (Convert.ToDouble(amount)+ Convert.ToDouble(amountT)).ToString();
-                        }
-                        
-                    }
-                    else 
-                    {
-                        sb.Append(" " + ":|:");
-                        sb.Append(" " + ":|:");
-                        sb.Append(" " + ":|:");
-                        sb.Append(" " + ":|:");
-                    }
-                }
-                sb.Append(amountT.ToString() + ":|:");
-                sb.Append(msg.recv_date + ":|:");
-                sb.Append(msg.deal_name + ":|:");
-                sb.Append(msg.tasknum + ":|:");
-                sb.Append(msg.dep_name + ":|:");
-                sb.Append(msg.packno + ":|:");
-                sb.Append(msg.totalpack + ":|:");
-                if ( msg.taskstatus == "0" )
-                {
-                    sb.Append("正常");
-                }
-                else 
-                {
-                    sb.Append("异常");
-                }
-            }
-            catch
-            {
-                return "Err";
-            }
-
-
-            return sb.ToString();
-        }
-
-    }
-}

+ 8 - 2
Toolkit/packages.config

@@ -5,8 +5,14 @@
   <package id="Prism.Core" version="8.1.97" targetFramework="net472" />
   <package id="Prism.Unity" version="8.1.97" targetFramework="net472" />
   <package id="Prism.Wpf" version="8.1.97" targetFramework="net472" />
-  <package id="System.Runtime.CompilerServices.Unsafe" version="4.5.2" targetFramework="net472" />
-  <package id="System.Threading.Tasks.Extensions" version="4.5.2" targetFramework="net472" />
+  <package id="System.Buffers" version="4.5.1" targetFramework="net472" />
+  <package id="System.Memory" version="4.5.5" targetFramework="net472" />
+  <package id="System.Numerics.Vectors" version="4.5.0" targetFramework="net472" />
+  <package id="System.Runtime.CompilerServices.Unsafe" version="4.5.3" targetFramework="net472" />
+  <package id="System.Threading.Tasks.Extensions" version="4.5.4" targetFramework="net472" />
+  <package id="System.ValueTuple" version="4.6.1" targetFramework="net472" />
+  <package id="TouchSocket" version="2.0.15" targetFramework="net472" />
+  <package id="TouchSocket.Core" version="2.0.15" targetFramework="net472" />
   <package id="Unity.Abstractions" version="5.11.7" targetFramework="net472" />
   <package id="Unity.Container" version="5.11.11" targetFramework="net472" />
 </packages>