diff --git a/SocketExample.sln b/SocketExample.sln
new file mode 100644
index 0000000..eda7d05
--- /dev/null
+++ b/SocketExample.sln
@@ -0,0 +1,25 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 17
+VisualStudioVersion = 17.13.35913.81
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RFIDmonitor", "SocketExample\RFIDmonitor.csproj", "{7E4E4E45-2FB2-4346-A101-4863BCDF50F9}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Release|Any CPU = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {7E4E4E45-2FB2-4346-A101-4863BCDF50F9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {7E4E4E45-2FB2-4346-A101-4863BCDF50F9}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {7E4E4E45-2FB2-4346-A101-4863BCDF50F9}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {7E4E4E45-2FB2-4346-A101-4863BCDF50F9}.Release|Any CPU.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ SolutionGuid = {484367ED-A45A-4CF7-89AC-DCD9BFC6E131}
+ EndGlobalSection
+EndGlobal
diff --git a/SocketExample/App.config b/SocketExample/App.config
new file mode 100644
index 0000000..abb8196
--- /dev/null
+++ b/SocketExample/App.config
@@ -0,0 +1,18 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/SocketExample/App.xaml b/SocketExample/App.xaml
new file mode 100644
index 0000000..abe739a
--- /dev/null
+++ b/SocketExample/App.xaml
@@ -0,0 +1,35 @@
+
+
+
+
+
diff --git a/SocketExample/App.xaml.cs b/SocketExample/App.xaml.cs
new file mode 100644
index 0000000..22b16a7
--- /dev/null
+++ b/SocketExample/App.xaml.cs
@@ -0,0 +1,17 @@
+using System;
+using System.Collections.Generic;
+using System.Configuration;
+using System.Data;
+using System.Linq;
+using System.Threading.Tasks;
+using System.Windows;
+
+namespace SocketExample
+{
+ ///
+ /// App.xaml 的交互逻辑
+ ///
+ public partial class App : Application
+ {
+ }
+}
diff --git a/SocketExample/ClientWindow.xaml b/SocketExample/ClientWindow.xaml
new file mode 100644
index 0000000..c13da21
--- /dev/null
+++ b/SocketExample/ClientWindow.xaml
@@ -0,0 +1,28 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/SocketExample/ClientWindow.xaml.cs b/SocketExample/ClientWindow.xaml.cs
new file mode 100644
index 0000000..e3a851e
--- /dev/null
+++ b/SocketExample/ClientWindow.xaml.cs
@@ -0,0 +1,115 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net.Sockets;
+using System.Net;
+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.Shapes;
+using System.Threading;
+
+namespace SocketExample
+{
+ ///
+ /// ClientWindow.xaml 的交互逻辑
+ ///
+ public partial class ClientWindow : Window
+ {
+ IPAddress ip;
+ int port;
+ TcpClient client;
+ NetworkStream stream;
+ Thread thread;
+ public ClientWindow()
+ {
+ InitializeComponent();
+ }
+
+ private void Button_Click(object sender, RoutedEventArgs e)
+ {
+ try
+ {
+ ip = IPAddress.Parse(IPtextbox.Text);
+ port = int.Parse(Porttextbox.Text);
+ client = new TcpClient();
+
+ // 开始监听
+ client.Connect(ip, port);
+
+ thread = new Thread(Recive);
+ thread.IsBackground = true;
+ thread.Start();
+ }
+ catch (Exception ex)
+ {
+ Dispatcher.Invoke(() =>
+ {
+ InfoTextBlock_Client.Text += $"处理请求时出错: {ex.Message}\n";
+ });
+ }
+
+ }
+
+ private void Button_Click_Send(object sender, RoutedEventArgs e)
+ {
+ try
+ {
+ string message = MessageTextBox_Client.Text;
+ // 如果发送"exit"则退出
+ if (message.ToLower() == "exit")
+ {
+ stream.Close();
+ client.Close();
+ thread.Abort();
+ }
+ else
+ {
+ byte[] data = Encoding.UTF8.GetBytes(message);
+ stream.Write(data, 0, data.Length);
+ }
+ }
+ catch (Exception ex)
+ {
+ Dispatcher.Invoke(() =>
+ {
+ InfoTextBlock_Client.Text += $"处理请求时出错: {ex.Message}\n";
+ });
+ }
+ }
+
+ void Recive()
+ {
+ stream = client.GetStream();
+ while (true)
+ {
+ // 处理客户端请求
+ try
+ {
+ // 接收响应
+ byte[] buffer = new byte[1024];
+ int bytesRead = stream.Read(buffer, 0, buffer.Length);
+ string response = Encoding.UTF8.GetString(buffer, 0, bytesRead);
+ Dispatcher.Invoke(() =>
+ {
+ this.InfoTextBlock_Client.Text += $"服务器响应: {response}\n";
+ });
+ }
+ catch (Exception ex)
+ {
+ Dispatcher.Invoke(() =>
+ {
+ InfoTextBlock_Client.Text += $"处理请求时出错: {ex.Message}\n";
+ });
+ }
+ }
+ // 关闭连接
+ }
+ }
+}
diff --git a/SocketExample/MainWindow.xaml b/SocketExample/MainWindow.xaml
new file mode 100644
index 0000000..29b84ed
--- /dev/null
+++ b/SocketExample/MainWindow.xaml
@@ -0,0 +1,29 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/SocketExample/MainWindow.xaml.cs b/SocketExample/MainWindow.xaml.cs
new file mode 100644
index 0000000..e7ebc85
--- /dev/null
+++ b/SocketExample/MainWindow.xaml.cs
@@ -0,0 +1,173 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Net.Sockets;
+using System.Net;
+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;
+using System.Threading;
+using System.IO;
+using System.Data.SqlClient;
+using MySql.Data.MySqlClient;
+
+namespace SocketExample
+{
+ ///
+ /// MainWindow.xaml 的交互逻辑
+ ///
+ public partial class MainWindow : Window
+ {
+ IPAddress ip;
+ int port;
+ string path;
+ public MainWindow()
+ {
+ path = "C:\\Users\\Administrator\\source\\repos\\SocketExample\\SocketExample\\bin\\Debug\\config.txt";
+ InitializeComponent();
+ }
+
+ private void Button_Click(object sender, RoutedEventArgs e)
+ {
+ ip = IPAddress.Parse(IPtextbox.Text);
+ port = int.Parse(Porttextbox.Text);
+
+ // 创建TCPListener
+ TcpListener server = new TcpListener(ip, port);
+
+ // 开始监听
+
+ server.Start();
+ InfoTextBlock.Text += "正在监听...\n";
+
+ Thread thread = new Thread(Listen);
+ thread.IsBackground = true;
+ thread.Start(server);
+ }
+ TcpClient client;
+ void Listen(object o)
+ {
+ TcpListener socketWatch = o as TcpListener;
+ while (true)
+ {
+ // 接受客户端连接,进程会一直在这等待,直到客户端链接才会继续下一步。
+ client = socketWatch.AcceptTcpClient();
+ Dispatcher.Invoke(() => {
+ InfoTextBlock.Text += "客户端已连接!\n";
+ });
+
+ Thread thread = new Thread(Recive);
+ thread.IsBackground = true;
+ thread.Start(client);
+
+ }
+ }
+
+ void Recive(Object o)
+ {
+ TcpClient tcpClient = o as TcpClient;
+ NetworkStream stream = tcpClient.GetStream();
+
+ while (true)
+ {
+ // 处理客户端请求
+ try
+ {
+ // 读取客户端消息
+ byte[] buffer = new byte[1024];
+ int bytesRead = stream.Read(buffer, 0, buffer.Length);
+ if (bytesRead == 0) {
+ Dispatcher.Invoke(() =>
+ {
+ InfoTextBlock.Text += $"客户端已断开连接\n";
+ });
+ break;
+ }
+ string request = Encoding.UTF8.GetString(buffer, 0, bytesRead);
+ Dispatcher.Invoke(() =>
+ {
+ InfoTextBlock.Text += $"接收到客户端消息: {request}\n";
+ });
+
+ // 发送响应
+ string response = $"服务器已收到你的消息: {request}";
+ byte[] responseBytes = Encoding.UTF8.GetBytes(response);
+ stream.Write(responseBytes, 0, responseBytes.Length);
+ Dispatcher.Invoke(() =>
+ {
+ InfoTextBlock.Text += "已发送响应给客户端\n";
+ });
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"处理请求时出错: {ex.Message}");
+ }
+ }
+ // 关闭连接
+ stream.Close();
+ client.Close();
+ }
+
+ private void Button_Click_Clear(object sender, RoutedEventArgs e)
+ {
+ this.InfoTextBlock.Text = string.Empty;
+ }
+
+ private void Button_Click_Create(object sender, RoutedEventArgs e)
+ {
+ ClientWindow clientWindow = new ClientWindow();
+ clientWindow.Show();
+ }
+
+ private void Button_Click_ReadFile(object sender, RoutedEventArgs e)
+ {
+ try
+ {
+ string[] ipconfig = File.ReadAllLines(path);
+ string[] ip = ipconfig[0].Split(':');
+ string[] port = ipconfig[1].Split(':');
+ InfoTextBlock.Text += ip[1];
+ InfoTextBlock.Text += port[1];
+ IPtextbox.Text = ip[1];
+ Porttextbox.Text = port[1];
+ }
+ catch(Exception ex)
+ {
+ InfoTextBlock.Text += ex.Message;
+ }
+ }
+
+ private void Button_Click_ReadSql(object sender, RoutedEventArgs e)
+ {
+ MySqlConnection conn = new MySqlConnection("server=127.0.0.1;port=3306;database=Test;user=root;password=root;");
+ MySqlCommand comn = new MySqlCommand("select * from Product",conn);
+ if (conn.State == System.Data.ConnectionState.Closed) {
+ conn.Open();
+ }
+ MySqlDataReader reader = comn.ExecuteReader();
+ try
+ {
+ if (reader.HasRows) {
+ while (reader.Read()) {
+ InfoTextBlock.Text += "" + reader["ID"] + reader["Name"] + "\n";
+ }
+ }
+ }
+ catch (Exception ex) {
+ InfoTextBlock.Text += ex.Message;
+ }
+ finally
+ {
+ conn.Close();
+ }
+ }
+ }
+}
diff --git a/SocketExample/MultiClientsWindow.xaml b/SocketExample/MultiClientsWindow.xaml
new file mode 100644
index 0000000..8bafccf
--- /dev/null
+++ b/SocketExample/MultiClientsWindow.xaml
@@ -0,0 +1,67 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/SocketExample/MultiClientsWindow.xaml.cs b/SocketExample/MultiClientsWindow.xaml.cs
new file mode 100644
index 0000000..aa1203f
--- /dev/null
+++ b/SocketExample/MultiClientsWindow.xaml.cs
@@ -0,0 +1,212 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Net;
+using System.Net.Sockets;
+using System.Runtime.CompilerServices;
+using System.Text;
+using System.Threading;
+using System.Windows;
+using System.Windows.Input;
+using System.Xml;
+
+namespace SocketExample
+{
+ ///
+ /// MultiClientsWindow.xaml 的交互逻辑
+ ///
+ public partial class MultiClientsWindow : Window
+ {
+
+ public class PanelItem:INotifyPropertyChanged //实现组件更改的接口
+ {
+ IPAddress ip;
+ int port;
+ TcpClient client;
+ NetworkStream stream;
+ Thread thread;
+ public string Text { get; set; }
+ public string IPtext { get; set; }
+ public string Porttext { get; set; }
+ public string MessageText { get; set; }
+
+ private string _infotext;
+ public string Infotext { get => _infotext; set
+ {
+ _infotext = value;
+ OnPropertyChanged(); // 通知 UI 更新
+ }
+ }
+
+ public LinkCommand linkcomn;
+
+ public LinkCommand sendcomn;
+
+ public LinkCommand disconnectcomn;
+
+ public LinkCommand clearcomn;
+
+
+ public PanelItem(int index)
+ {
+ Text = $"客户端{index + 1}";
+ linkcomn = new LinkCommand(Button_Link);//绑定按钮的链接事件
+ sendcomn = new LinkCommand(Button_Click_Send);
+ disconnectcomn = new LinkCommand(Button_disconnect);
+ clearcomn = new LinkCommand(Button_clear);
+
+ MessageText = "请输入需要发送的内容:";
+ IPtext = "127.0.0.1";//默认IP
+ Porttext = "8999";//默认端口
+ }
+
+ public LinkCommand _linkcomn { get { return linkcomn; } }
+
+ public LinkCommand _sendcomn { get { return sendcomn; } }
+
+ public LinkCommand _disconnectcomn { get { return disconnectcomn; } }
+
+ public LinkCommand _clearcomn { get { return clearcomn; } }
+
+ void Button_Link()//链接按钮的事件
+ {
+ try
+ {
+ ip = IPAddress.Parse(IPtext);
+ port = int.Parse(Porttext);
+ client = new TcpClient();
+
+ // 开始监听
+ client.Connect(ip, port);
+
+ thread = new Thread(Recive);
+ thread.IsBackground = true;
+ thread.Start();
+ Infotext += "已连接!\n";
+ }
+ catch (Exception ex)
+ {
+ Infotext += $"处理请求时出错: {ex.Message}\n";
+ }
+ }
+
+ void Button_Click_Send()//发送按钮的事件
+ {
+ try
+ {
+ string message = MessageText;
+ // 如果发送"exit"则退出
+ byte[] data = Encoding.UTF8.GetBytes(message);
+ stream.Write(data, 0, data.Length);
+ }
+ catch (Exception ex)
+ {
+ Infotext += $"处理请求时出错: {ex.Message}\n";
+ }
+ }
+
+ void Button_disconnect()
+ {
+ stream.Close();
+ client.Close();
+ thread.Abort();
+ Infotext += "已断开链接\n";
+ }
+
+ void Button_clear()
+ {
+ Infotext = string.Empty;
+ }
+
+ void Recive()//接收消息线程
+ {
+ stream = client.GetStream();
+ while (true)
+ {
+ // 处理客户端请求
+ try
+ {
+ // 接收响应
+ byte[] buffer = new byte[1024];
+ int bytesRead = stream.Read(buffer, 0, buffer.Length);
+ if (bytesRead == 0)
+ {
+ Infotext += $"服务器断开连接\n";
+ break;
+ }
+ string response = Encoding.UTF8.GetString(buffer, 0, bytesRead);
+ Infotext += $"服务器响应: {response}\n";
+ }
+ catch (Exception ex)
+ {
+ Infotext += $"处理请求时出错: {ex.Message}\n";
+ }
+ }
+ stream.Close();
+ client.Close();
+ // 关闭连接
+ }
+
+ //组件属性更改事件
+ public event PropertyChangedEventHandler PropertyChanged;
+ protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
+ {
+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
+ }
+ }
+ public MultiClientsWindow()
+ {
+ InitializeComponent();
+ }
+
+ int currentcount = 0;
+
+ List items = new List();
+
+ private void GenerateButton_Click(object sender, RoutedEventArgs e)//添加客户端框体
+ {
+ if (int.TryParse(CountTextBox.Text, out int count) && count > 0)
+ {
+ //var items = new List();
+ for (int i = 0; i < count; i++)
+ {
+ items.Add(new PanelItem(i + currentcount));
+ }
+ currentcount += count;
+ PanelContainer.ItemsSource = null;//刷新
+ PanelContainer.ItemsSource = items;
+
+ }
+ else
+ {
+ MessageBox.Show("请输入有效的正整数", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
+ }
+ }
+
+ public class LinkCommand : ICommand //command方法实现
+ {
+ private Action _excute;
+ public LinkCommand(Action action) {
+ _excute = action;
+ }
+ public event EventHandler CanExecuteChanged;
+
+ public bool CanExecute(object parameter)
+ {
+ return true;
+ }
+
+ public void Execute(object parameter)
+ {
+ _excute();
+ }
+ }
+
+ private void ClearButton_Click(object sender, RoutedEventArgs e)//清空客户端
+ {
+ items.Clear();
+ PanelContainer.ItemsSource = null;
+ currentcount = 0;
+ }
+ }
+}
diff --git a/SocketExample/Properties/AssemblyInfo.cs b/SocketExample/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..7c817eb
--- /dev/null
+++ b/SocketExample/Properties/AssemblyInfo.cs
@@ -0,0 +1,52 @@
+using System.Reflection;
+using System.Resources;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Windows;
+
+// 有关程序集的一般信息由以下
+// 控制。更改这些特性值可修改
+// 与程序集关联的信息。
+[assembly: AssemblyTitle("SocketExample")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("SocketExample")]
+[assembly: AssemblyCopyright("Copyright © 2025")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// 将 ComVisible 设置为 false 会使此程序集中的类型
+//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
+//请将此类型的 ComVisible 特性设置为 true。
+[assembly: ComVisible(false)]
+
+//若要开始生成可本地化的应用程序,请设置
+//.csproj 文件中的 CultureYouAreCodingWith
+//在 中。例如,如果你使用的是美国英语。
+//使用的是美国英语,请将 设置为 en-US。 然后取消
+//对以下 NeutralResourceLanguage 特性的注释。 更新
+//以下行中的“en-US”以匹配项目文件中的 UICulture 设置。
+
+//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
+
+
+[assembly: ThemeInfo(
+ ResourceDictionaryLocation.None, //主题特定资源词典所处位置
+ //(未在页面中找到资源时使用,
+ //或应用程序资源字典中找到时使用)
+ ResourceDictionaryLocation.SourceAssembly //常规资源词典所处位置
+ //(未在页面中找到资源时使用,
+ //、应用程序或任何主题专用资源字典中找到时使用)
+)]
+
+
+// 程序集的版本信息由下列四个值组成:
+//
+// 主版本
+// 次版本
+// 生成号
+// 修订号
+//
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/SocketExample/Properties/Resources.Designer.cs b/SocketExample/Properties/Resources.Designer.cs
new file mode 100644
index 0000000..a857095
--- /dev/null
+++ b/SocketExample/Properties/Resources.Designer.cs
@@ -0,0 +1,71 @@
+//------------------------------------------------------------------------------
+//
+// 此代码由工具生成。
+// 运行时版本: 4.0.30319.42000
+//
+// 对此文件的更改可能导致不正确的行为,如果
+// 重新生成代码,则所做更改将丢失。
+//
+//------------------------------------------------------------------------------
+
+namespace SocketExample.Properties
+{
+
+
+ ///
+ /// 强类型资源类,用于查找本地化字符串等。
+ ///
+ // 此类是由 StronglyTypedResourceBuilder
+ // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
+ // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
+ // (以 /str 作为命令选项),或重新生成 VS 项目。
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ internal class Resources
+ {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal Resources()
+ {
+ }
+
+ ///
+ /// 返回此类使用的缓存 ResourceManager 实例。
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Resources.ResourceManager ResourceManager
+ {
+ get
+ {
+ if ((resourceMan == null))
+ {
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SocketExample.Properties.Resources", typeof(Resources).Assembly);
+ resourceMan = temp;
+ }
+ return resourceMan;
+ }
+ }
+
+ ///
+ /// 重写当前线程的 CurrentUICulture 属性,对
+ /// 使用此强类型资源类的所有资源查找执行重写。
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Globalization.CultureInfo Culture
+ {
+ get
+ {
+ return resourceCulture;
+ }
+ set
+ {
+ resourceCulture = value;
+ }
+ }
+ }
+}
diff --git a/SocketExample/Properties/Resources.resx b/SocketExample/Properties/Resources.resx
new file mode 100644
index 0000000..af7dbeb
--- /dev/null
+++ b/SocketExample/Properties/Resources.resx
@@ -0,0 +1,117 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ text/microsoft-resx
+
+
+ 2.0
+
+
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
\ No newline at end of file
diff --git a/SocketExample/Properties/Settings.Designer.cs b/SocketExample/Properties/Settings.Designer.cs
new file mode 100644
index 0000000..f0f23d0
--- /dev/null
+++ b/SocketExample/Properties/Settings.Designer.cs
@@ -0,0 +1,30 @@
+//------------------------------------------------------------------------------
+//
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+//
+//------------------------------------------------------------------------------
+
+namespace SocketExample.Properties
+{
+
+
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
+ internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
+ {
+
+ private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
+
+ public static Settings Default
+ {
+ get
+ {
+ return defaultInstance;
+ }
+ }
+ }
+}
diff --git a/SocketExample/Properties/Settings.settings b/SocketExample/Properties/Settings.settings
new file mode 100644
index 0000000..033d7a5
--- /dev/null
+++ b/SocketExample/Properties/Settings.settings
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/SocketExample/RFIDmonitor.csproj b/SocketExample/RFIDmonitor.csproj
new file mode 100644
index 0000000..a2e5ac9
--- /dev/null
+++ b/SocketExample/RFIDmonitor.csproj
@@ -0,0 +1,224 @@
+
+
+
+
+ Debug
+ AnyCPU
+ {7E4E4E45-2FB2-4346-A101-4863BCDF50F9}
+ WinExe
+ SocketExample
+ SocketExample
+ v4.8
+ 512
+ {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
+ 4
+ true
+ true
+
+
+
+
+ AnyCPU
+ true
+ full
+ false
+ bin\Debug\
+ DEBUG;TRACE
+ prompt
+ 4
+ preview
+
+
+ AnyCPU
+ pdbonly
+ true
+ bin\Release\
+ TRACE
+ prompt
+ 4
+ preview
+
+
+
+ ..\packages\BouncyCastle.Cryptography.2.5.1\lib\net461\BouncyCastle.Cryptography.dll
+
+
+ ..\packages\CommonServiceLocator.2.0.2\lib\net47\CommonServiceLocator.dll
+
+
+ ..\packages\MvvmLightLibs.5.4.1.1\lib\net45\GalaSoft.MvvmLight.dll
+
+
+ ..\packages\MvvmLightLibs.5.4.1.1\lib\net45\GalaSoft.MvvmLight.Extras.dll
+
+
+ ..\packages\MvvmLightLibs.5.4.1.1\lib\net45\GalaSoft.MvvmLight.Platform.dll
+
+
+ ..\packages\Google.Protobuf.3.30.0\lib\net45\Google.Protobuf.dll
+
+
+ ..\packages\K4os.Compression.LZ4.1.3.8\lib\net462\K4os.Compression.LZ4.dll
+
+
+ ..\packages\K4os.Compression.LZ4.Streams.1.3.8\lib\net462\K4os.Compression.LZ4.Streams.dll
+
+
+ ..\packages\K4os.Hash.xxHash.1.0.8\lib\net462\K4os.Hash.xxHash.dll
+
+
+ ..\packages\Microsoft.Bcl.AsyncInterfaces.5.0.0\lib\net461\Microsoft.Bcl.AsyncInterfaces.dll
+
+
+ ..\packages\MySql.Data.9.3.0\lib\net48\MySql.Data.dll
+
+
+ ..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll
+
+
+
+ ..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll
+
+
+
+ ..\packages\System.Configuration.ConfigurationManager.8.0.0\lib\net462\System.Configuration.ConfigurationManager.dll
+
+
+
+ ..\packages\System.Diagnostics.DiagnosticSource.8.0.1\lib\net462\System.Diagnostics.DiagnosticSource.dll
+
+
+ ..\packages\System.IO.Pipelines.5.0.2\lib\net461\System.IO.Pipelines.dll
+
+
+
+ ..\packages\System.Memory.4.5.5\lib\net461\System.Memory.dll
+
+
+
+ ..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll
+
+
+ ..\packages\System.Runtime.CompilerServices.Unsafe.6.0.0\lib\net461\System.Runtime.CompilerServices.Unsafe.dll
+
+
+ ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll
+
+
+
+ ..\packages\MvvmLightLibs.5.4.1.1\lib\net45\System.Windows.Interactivity.dll
+
+
+
+
+
+
+
+
+ 4.0
+
+
+ ..\packages\TouchSocket.3.1.2\lib\net472\TouchSocket.dll
+
+
+ ..\packages\TouchSocket.Core.3.1.2\lib\net472\TouchSocket.Core.dll
+
+
+
+
+
+ ..\packages\ZstdSharp.Port.0.8.5\lib\net462\ZstdSharp.dll
+
+
+
+
+ MSBuild:Compile
+ Designer
+
+
+ Designer
+ MSBuild:Compile
+
+
+ MSBuild:Compile
+ Designer
+
+
+ App.xaml
+ Code
+
+
+ ClientWindow.xaml
+
+
+ MainWindow.xaml
+ Code
+
+
+ MSBuild:Compile
+ Designer
+
+
+ MSBuild:Compile
+ Designer
+
+
+ MSBuild:Compile
+ Designer
+
+
+ Designer
+ MSBuild:Compile
+
+
+
+
+ TCPWindowV2.xaml
+
+
+ TCPWindow.xaml
+
+
+ TouchSocketWindow.xaml
+
+
+ MultiClientsWindow.xaml
+
+
+ Code
+
+
+ True
+ True
+ Resources.resx
+
+
+ True
+ Settings.settings
+ True
+
+
+ ResXFileCodeGenerator
+ Resources.Designer.cs
+
+
+
+ SettingsSingleFileGenerator
+ Settings.Designer.cs
+
+
+
+
+
+
+
+
+
+
+
+
+ 这台计算机上缺少此项目引用的 NuGet 程序包。使用“NuGet 程序包还原”可下载这些程序包。有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。
+
+
+
+
\ No newline at end of file
diff --git a/SocketExample/TCPWindow.xaml b/SocketExample/TCPWindow.xaml
new file mode 100644
index 0000000..380fe66
--- /dev/null
+++ b/SocketExample/TCPWindow.xaml
@@ -0,0 +1,214 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/SocketExample/TCPWindow.xaml.cs b/SocketExample/TCPWindow.xaml.cs
new file mode 100644
index 0000000..85f7275
--- /dev/null
+++ b/SocketExample/TCPWindow.xaml.cs
@@ -0,0 +1,592 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Diagnostics.Eventing.Reader;
+using System.IO.Ports;
+using System.Linq;
+using System.Net;
+using System.Runtime.CompilerServices;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Input;
+using System.Xml;
+using Org.BouncyCastle.Utilities.Encoders;
+using TouchSocket.Core;
+using TouchSocket.Sockets;
+using static SocketExample.TCPWindow;
+
+namespace SocketExample
+{
+ ///
+ /// MultiClientsWindow.xaml 的交互逻辑
+ ///
+ public partial class TCPWindow : Window
+ {
+
+ public class PanelItem : INotifyPropertyChanged //实现组件更改的接口
+ {
+ IPAddress ip;
+ int port;
+ TcpClient client;
+ public string option;//命令选项
+ public string Text { get; set; }//客户端编号
+ public string IPtext { get; set; }//IP文本框
+ public string Porttext { get; set; }//端口文本框
+ public string MessageText { get; set; }//发送框
+ private string _statecolour { get; set; }//状态指示灯
+ public string StateColour { get => _statecolour; set { _statecolour = value; OnPropertyChanged(); } }
+
+ private string _linkstate;//链接状态文本
+ public string LinkState { get => _linkstate; set { _linkstate = value; OnPropertyChanged(); } }
+
+ private string _infotext;//信息框
+ public string Infotext { get => _infotext; set
+ {
+ _infotext = value;
+ OnPropertyChanged(); // 通知 UI 更新
+ }
+ }
+ private string _rssiinfo;//RSSI强度
+ public string RSSIinfo { get => _rssiinfo; set { _rssiinfo = value; OnPropertyChanged(); } }
+ private string _countinfo;//count数值
+ public string Countinfo { get => _countinfo; set { _countinfo = value; OnPropertyChanged(); } }
+ private string _timeinfo;//当前时间
+ public string Timeinfo { get => _timeinfo; set { _timeinfo = value; OnPropertyChanged(); } }
+ private string _epcinfo;//EPC信息
+ private string _epcasc;//ASC2码 EPC信息
+ public string EPCinfo { get => _epcinfo; set { _epcinfo = value; OnPropertyChanged(); } }
+ public string EPCASC { get => _epcasc; set { _epcasc = value; OnPropertyChanged(); } }
+ private string _gpio1;
+ private string _gpio2;
+ private string _gpio3;
+ private string _gpio4;//GPIO1-4状态
+ public string GPIO1 { get => _gpio1; set { _gpio1 = value; OnPropertyChanged(); } }
+ public string GPIO2 { get => _gpio2; set { _gpio2 = value; OnPropertyChanged(); } }
+ public string GPIO3 { get => _gpio3; set { _gpio3 = value; OnPropertyChanged(); } }
+ public string GPIO4 { get => _gpio4; set { _gpio4 = value; OnPropertyChanged(); } }
+
+ private string _moduleinfo;
+ private string _motherboardhardware;
+ private string _motherboardfirmware;//设备信息
+ public string moduleInfo { get => _moduleinfo; set { _moduleinfo = value; OnPropertyChanged(); } }
+ public string motherboardHardware { get => _motherboardhardware; set { _motherboardhardware = value; OnPropertyChanged(); } }
+ public string motherboardFirmware { get => _motherboardfirmware; set { _motherboardfirmware = value; OnPropertyChanged(); } }
+
+ public LinkCommand linkcomn;//链接命令
+
+ public LinkCommand sendcomn;//发送命令
+
+ public LinkCommand disconnectcomn;//断连命令
+
+ public LinkCommand clearcomn;//清空命令
+
+
+ public PanelItem(int index)
+ {
+ Text = $"客户端{index + 1}";
+ linkcomn = new LinkCommand(Button_Link);//绑定按钮的链接事件
+ sendcomn = new LinkCommand(Button_Click_Send);//绑定发送按钮的事件
+ disconnectcomn = new LinkCommand(Button_disconnect);//绑定断连按钮的事件
+ clearcomn = new LinkCommand(Button_clear);//绑定清空按钮的事件
+
+ //页面初始化
+ MessageText = string.Empty;
+ IPtext = "192.168.0.7";//默认IP
+ Porttext = "20108";//默认端口
+ StateColour = "Red";
+ LinkState = "未连接";
+ RSSIinfo = "##";
+ Countinfo = "00";
+ EPCASC = "###";
+ EPCinfo = "###";
+ GPIO1 = "低";
+ GPIO2 = "低";
+ GPIO3 = "低";
+ GPIO4 = "低";
+ }
+
+ public LinkCommand _linkcomn { get { return linkcomn; } }
+
+ public LinkCommand _sendcomn { get { return sendcomn; } }
+
+ public LinkCommand _disconnectcomn { get { return disconnectcomn; } }
+
+ public LinkCommand _clearcomn { get { return clearcomn; } }
+ private Task onSend(ITcpClient client, ReceivedDataEventArgs e)
+ {
+
+ return EasyTask.CompletedTask;
+ }
+ private Task onRecieved(ITcpClient client, ReceivedDataEventArgs e) //接收事件
+ {
+ string time = DateTime.Now.ToString();
+ string currentTime = time.Substring(10, 5);
+ var mes = e.ByteBlock.Span.ToString(Encoding.UTF8);
+ byte[] data = e.ByteBlock.Span.ToArray();
+ string hexString = BitConverter.ToString(data).Replace("-", " ");
+
+ //Infotext += $"({currentTime})客户端接收到信息:\n{mes}\n\n";
+ Infotext += $"({currentTime})客户端接收到信息:\n{hexString}\n\n";
+
+ //读取状态
+ string readStateString = hexString.Replace(" ", "");//去掉字符串中空格
+ string dataLength = readStateString.Substring(4, 2);//获取字符串中内容长度
+ string commandState = readStateString.Substring(6, 2);//获取命令
+ int i = Convert.ToInt32(dataLength, 16);
+ if (i != 0)
+ {
+ switch (commandState)
+ {
+ case "02":
+ Listtaglist = GetTagInfos(data);
+ RSSIinfo = Convert.ToInt32(readStateString.Substring(14, 2), 16).ToString();//RSSI
+ Countinfo = Convert.ToInt32(readStateString.Substring(12, 2), 16).ToString();//Count
+ Timeinfo = $" {currentTime}\n{time.Substring(0, 10)}";//获取时间
+ string Temp = readStateString.Substring(22, 34);
+
+ byte[] Tempbytes = HextoByte(Temp);//16进制转byte数组
+ EPCASC = Encoding.ASCII.GetString(Tempbytes);//byte数组转String
+ EPCinfo = hexString.Substring(33, 50);//16进制原数据
+ //Infotext += $"({currentTime})客户端接收到EPC信息:\n{EPCASC}\n\n";
+ break;
+
+ case "81":
+ //获取GPIO状态,16进制转二进制
+ string GPIOBinInfo = Convert.ToString(Convert.ToInt32(readStateString.Substring(12, 2), 16), 2).PadLeft(4, '0');
+ for (int j = 0; j < GPIOBinInfo.Length; j++)
+ {
+ //按位判断GPIO状态
+ switch (j)
+ {
+ case 0:
+ if (GPIOBinInfo.Substring(j, 1) == "1")
+ GPIO4 = "高";
+ else
+ GPIO4 = "低";
+ break;
+ case 1:
+ if (GPIOBinInfo.Substring(j, 1) == "1")
+ GPIO3 = "高";
+ else
+ GPIO3 = "低";
+ break;
+ case 2:
+ if (GPIOBinInfo.Substring(j, 1) == "1")
+ GPIO2 = "高";
+ else
+ GPIO2 = "低";
+ break;
+ case 3:
+ if (GPIOBinInfo.Substring(j, 1) == "1")
+ GPIO1 = "高";
+ else
+ GPIO1 = "低";
+ break;
+ default:
+ break;
+ }
+ }
+ break;
+ case "70":
+ //获取设备信息
+ switch (option)
+ {
+
+ case "00":
+ moduleInfo = Encoding.ASCII.GetString(HextoByte(readStateString.Substring(10, Convert.ToInt32(dataLength, 16) * 2)));
+ //Infotext += $"({currentTime})客户端接收到module信息:\n{moduleInfo}\n\n";
+ break;
+ case "03":
+ motherboardHardware = Encoding.ASCII.GetString(HextoByte(readStateString.Substring(10, Convert.ToInt32(dataLength, 16) * 2)));
+ //Infotext += $"({currentTime})客户端接收到hardware信息:\n{motherboardHardware}\n\n";
+ break;
+ case "04":
+ motherboardFirmware = Encoding.ASCII.GetString(HextoByte(readStateString.Substring(10, Convert.ToInt32(dataLength, 16) * 2)));
+ //Infotext += $"({currentTime})客户端接收到firmware信息:\n{motherboardFirmware}\n\n";
+ option = "";
+ break;
+ }
+ break;
+ default:
+ break;
+
+ }
+
+
+ }
+ else
+ {
+ switch (commandState)
+ {
+ case "02":
+ Infotext += "未读取到\n";
+ RSSIinfo = "##";//未读取到数值时清空数据为初始值
+ Countinfo = "00";
+ EPCASC = "###";
+ EPCinfo = "###";
+ Timeinfo = $" {currentTime}\n{time.Substring(0, 10)}";//获取时间
+ break;
+ }
+ }
+ return EasyTask.CompletedTask;
+ }
+
+ private Task onConnected(ITcpClient client, ConnectedEventArgs e)//连接后初始化
+ {
+ Infotext += "已连接!\n";
+ StateColour = "Green";
+ LinkState = "已连接";
+
+ byte[] data = strToToHexByte("AA 55 01 70 00 71 0D");//获取模块信息
+ option = "00";
+ client.Send(data);
+
+ Thread.Sleep(500);
+
+ data = strToToHexByte("AA 55 01 70 03 72 0D");//获取主板硬件信息
+ option = "03";
+ client.Send(data);
+
+ Thread.Sleep(500);
+
+ data = strToToHexByte("AA 55 01 70 04 75 0D");//获取主板固件信息
+ option = "04";
+ client.Send(data);
+
+ Thread.Sleep(500);
+
+ data = strToToHexByte("AA 55 00 81 81 0D");//获取GPIO状态
+ client.Send(data);
+
+ Thread.Sleep(500);
+
+ data = strToToHexByte("AA 55 02 02 03 E8 EB 0D");//获取1000ms内标签信息
+ client.Send(data);
+ return EasyTask.CompletedTask;
+ }
+
+ private static byte[] HextoByte(string Temp)
+ {
+ byte[] Tempbytes = new byte[Temp.Length / 2];//16进制转byte数组
+ for (int m = 0; m < Temp.Length; m += 2)
+ {
+ try
+ {
+ Tempbytes[m / 2] = Convert.ToByte(Temp.Substring(m, 2), 16);
+ }
+ catch (Exception excp)
+ {
+
+ }
+ }
+ return Tempbytes;
+ }
+
+ private static byte[] strToToHexByte(string hexString)//字符串转16进制
+ {
+ hexString = hexString.Replace(" ", "");
+ if ((hexString.Length % 2) != 0)
+ hexString += " ";
+ byte[] returnBytes = new byte[hexString.Length / 2];
+ for (int i = 0; i < returnBytes.Length; i++)
+ returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Trim(), 16);
+ return returnBytes;
+ }
+
+ async void Button_Link()//链接按钮的事件
+ {
+ try
+ {
+ ip = IPAddress.Parse(IPtext);
+ port = int.Parse(Porttext);
+ client = new TcpClient();
+ //连接事件
+ client.Connected += onConnected;
+ //断连事件
+ client.Closed = (client, e) => { Infotext += "已断开!\n"; StateColour = "Red"; LinkState = "未连接"; return EasyTask.CompletedTask; };
+ //接收事件
+ client.Received += onRecieved;
+
+ //设置连接属性
+ await client.SetupAsync(new TouchSocketConfig().SetRemoteIPHost($"{IPtext}:{Porttext}").ConfigureContainer(a =>
+ {
+ a.AddConsoleLogger();//添加一个日志注入
+ }));
+
+ //开启连接
+ await client.ConnectAsync();
+ }
+ catch (Exception ex)
+ {
+ Infotext += $"处理请求时出错: {ex.Message}\n";
+ }
+ }
+
+ void Button_Click_Send()//发送按钮的事件
+ {
+ try
+ {
+ string message = MessageText;
+ if (message == string.Empty)
+ {
+ MessageBox.Show("输入内容不能为空!");
+ }
+ else
+ {
+ byte[] data = Encoding.UTF8.GetBytes(message);
+ client.Send(data);//发送原始数据
+ client.Send(strToToHexByte(message));//发送16进制数据
+ }
+ }
+ catch (Exception ex)
+ {
+ Infotext += $"处理请求时出错: {ex.Message}\n";
+ }
+ }
+
+ void Button_disconnect()
+ {
+ client.Close();//断开连接
+ }
+
+ void Button_clear()
+ {
+ Infotext = string.Empty;//清空信息框
+ }
+
+ //组件属性更改事件
+ public event PropertyChangedEventHandler PropertyChanged;
+ protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
+ {
+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
+ }
+ }
+ public TCPWindow()
+ {
+ InitializeComponent();
+ }
+
+ int currentcount = 0;//目前客户端的数量
+
+ List items = new List();//客户端组件列表
+
+ private void GenerateButton_Click(object sender, RoutedEventArgs e)//添加客户端框体
+ {
+ if (int.TryParse(CountTextBox.Text, out int count) && count > 0)
+ {
+ //var items = new List();
+ for (int i = 0; i < count; i++)
+ {
+ items.Add(new PanelItem(i + currentcount));
+ }
+ currentcount += count;
+ PanelContainer.ItemsSource = null;//刷新
+ PanelContainer.ItemsSource = items;
+
+ }
+ else
+ {
+ MessageBox.Show("请输入有效的正整数", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
+ }
+ }
+
+ public class LinkCommand : ICommand //command方法实现
+ {
+ private Action _excute;
+ public LinkCommand(Action action) {
+ _excute = action;
+ }
+ public event EventHandler CanExecuteChanged;
+
+ public bool CanExecute(object parameter)
+ {
+ return true;
+ }
+
+ public void Execute(object parameter)
+ {
+ _excute();
+ }
+ }
+
+ private void ClearButton_Click(object sender, RoutedEventArgs e)//清空客户端
+ {
+ items.Clear();
+ PanelContainer.ItemsSource = null;
+ currentcount = 0;
+ }
+
+ private static List GetTagInfos(byte[] AutoDealReportData)
+ {
+ List tagInfoList = new List();
+ try
+ {
+ //mutauto.WaitOne();
+ int iFirstCountPos = 6; //第一次读取标签次数位置
+ int iFirstRSSIPos = 7; //第一次读取标签强度位置
+ int iFirstAnt = 8;
+ int iFirstPC = 9; //第一次读取标签天线位置
+ int iFirstLeftBarcketPos = 11;//EPC数据起始位置
+ UInt16 tempDataCount = 0;
+ int tempDataRSSI = 0;
+ UInt16 tempDataANT = 0;
+ int iBarcodeGroupCount = Convert.ToInt32(AutoDealReportData[5].ToString()); //标签组数
+ int iBarcodeLength = 16; //标签长度
+ int iCommonSecondFlag = 0;
+ int dataLength = Convert.ToInt32(AutoDealReportData[2].ToString());
+ for (int j = 0; j < iBarcodeGroupCount; j++)
+ {
+ //int EPCLength = dataLength - (6 * iBarcodeGroupCount);
+
+ TagInfo tag = new TagInfo();
+ byte[] tempPCByte = new byte[2]; //取出PC
+ Array.Clear(tempPCByte, 0, 2);
+ Array.Copy(AutoDealReportData, iFirstPC, tempPCByte, 0, 2);
+
+ //PC转二进制取前五位转十进制
+ int epcLength = Convert.ToInt32(Convert.ToString(Convert.ToInt64(tempPCByte[0].ToString("X"), 16), 2).PadLeft(8, '0').Substring(0, 5), 2) * 2;
+
+ //int pc = Convert.ToInt32(tempPCByte[0].ToString());
+ //int epcLength = EPCLengthByPC(pc);
+ iBarcodeLength = epcLength;
+
+ byte[] tempDataByte = new byte[epcLength];
+ Array.Clear(tempDataByte, 0, iBarcodeLength);
+ Array.Copy(AutoDealReportData, iFirstLeftBarcketPos, tempDataByte, 0, iBarcodeLength);
+
+ byte[] tempCountByte = new byte[1]; //取出标签次数
+ Array.Clear(tempCountByte, 0, 1);
+ Array.Copy(AutoDealReportData, iFirstCountPos, tempCountByte, 0, 1);
+ tempDataCount = tempCountByte[0];
+
+ byte[] tempRSSIByte = new byte[1]; //取出标签强度
+ Array.Clear(tempRSSIByte, 0, 1);
+ Array.Copy(AutoDealReportData, iFirstRSSIPos, tempRSSIByte, 0, 1);
+
+ tempDataRSSI = HexStringToNegative(bytesToHexStr(tempRSSIByte, 1));
+
+ #region add by wenjy 20220829 取出天线号
+ byte[] tempAntByte = new byte[1]; //取出天线号
+ Array.Clear(tempAntByte, 0, 1);
+ Array.Copy(AutoDealReportData, iFirstAnt, tempAntByte, 0, 1);
+ tempDataANT = tempAntByte[0];
+ #endregion
+
+ tag.Count = tempDataCount;
+ tag.RSSI = tempDataRSSI;
+ tag.EPC = tempDataByte;
+
+ //if (pc == 24)
+ //{
+ // tag.EPCstring = StringChange.bytesToHexStr(tempDataByte, tempDataByte.Length).Substring(0, 7);
+ //}
+ //else
+ //{
+ // tag.EPCstring = System.Text.Encoding.ASCII.GetString(tempDataByte);
+ //}
+ tag.EPCstring = System.Text.Encoding.ASCII.GetString(tempDataByte);
+
+ tag.PC = tempPCByte;
+ tag.Antana = tempDataANT;
+ tagInfoList.Add(tag);
+ int iBarcodeListLen = tagInfoList.Count; //特别注意,必须这样,要不然会多一条数据
+
+ iFirstCountPos = iFirstCountPos + iBarcodeLength + 5; //次数
+ iFirstRSSIPos = iFirstCountPos + 1; //强度
+ iFirstAnt = iFirstRSSIPos + 1; //天线
+ iFirstPC = iFirstAnt + 1;
+ iFirstLeftBarcketPos = iFirstLeftBarcketPos + iBarcodeLength + 5;
+
+ // LogInfo.Info("----函数调用:Device_AutoDealContent 第[" + (iCommonSecondFlag + 1) + "]次数据解析为:" + StringChange.bytesToHexStr(tempDataByte, tempDataByte.Length) + ",读取标签次数:[" + tempDataCount + "],标签信号强度:[" + tempDataRSSI + "],天线号:[" + tempDataANT + "]");
+ iCommonSecondFlag++;
+ if (iCommonSecondFlag == iBarcodeGroupCount)
+ {
+ //mutauto.ReleaseMutex();
+ return tagInfoList;
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ //LogInfo.Info("----函数调用:Device_AutoDealContent 自动处理函数异常:" + ex.ToString());
+ //mutauto.ReleaseMutex();
+ }
+ return tagInfoList;
+
+
+ }
+
+
+
+
+ public static int HexStringToNegative(string strNumber)
+ {
+
+ int iNegate = 0;
+ int iNumber = Convert.ToInt32(strNumber, 16);
+ if (iNumber > 127)
+ {
+ int iComplement = iNumber - 1;
+ string strNegate = string.Empty;
+ char[] binchar = Convert.ToString(iComplement, 2).PadLeft(8, '0').ToArray();
+ foreach (char ch in binchar)
+ {
+ if (Convert.ToInt32(ch) == 48)
+ {
+ strNegate += "1";
+ }
+ else
+ {
+ strNegate += "0";
+ }
+ }
+ iNegate = -Convert.ToInt32(strNegate, 2);
+ }
+ return iNegate;
+ }
+
+
+
+ public class TagInfo
+ {
+ public byte[] PC = new byte[2];
+
+ public int Count;
+
+ public int RSSI;
+
+ public int Antana;
+
+ public byte[] EPC;
+
+ public byte[] Data;
+
+ public string PCstring = null;
+
+ public string EPCstring = null;
+
+ public DateTime Time;
+ }
+
+ ///
+ /// 将byte数组转换成十六进制字符串 //e.g. { 0x01, 0x01} ---> " 01 01"
+ ///
+ /// byte数组
+ /// 数组长度
+ /// 十六进制字符串
+ public static string bytesToHexStr(byte[] bytes, int iLen)
+ {
+ string returnStr = "";
+ if (bytes != null)
+ {
+ for (int i = 0; i < iLen; i++)
+ {
+ returnStr += bytes[i].ToString("X2");
+ }
+ }
+ return returnStr;
+ }
+ }
+}
diff --git a/SocketExample/TCPWindowV2.xaml b/SocketExample/TCPWindowV2.xaml
new file mode 100644
index 0000000..1a8ee02
--- /dev/null
+++ b/SocketExample/TCPWindowV2.xaml
@@ -0,0 +1,239 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/SocketExample/TCPWindowV2.xaml.cs b/SocketExample/TCPWindowV2.xaml.cs
new file mode 100644
index 0000000..1c31b1f
--- /dev/null
+++ b/SocketExample/TCPWindowV2.xaml.cs
@@ -0,0 +1,658 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Diagnostics.Eventing.Reader;
+using System.IO;
+using System.IO.Ports;
+using System.Linq;
+using System.Net;
+using System.Runtime.CompilerServices;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Input;
+using System.Xml;
+using K4os.Compression.LZ4.Streams.Abstractions;
+using Org.BouncyCastle.Utilities.Encoders;
+using TouchSocket.Core;
+using TouchSocket.Sockets;
+
+namespace SocketExample
+{
+ ///
+ /// MultiClientsWindow.xaml 的交互逻辑
+ ///
+ public partial class TCPWindowV2 : Window
+ {
+
+ public class PanelItem : INotifyPropertyChanged //实现组件更改的接口
+ {
+ IPAddress ip;
+ int port;
+ TcpClient client;
+ public string option;//命令选项
+ private ObservableCollection _tagItems;
+ public ObservableCollection TagItems { get => _tagItems; set { _tagItems = value; OnPropertyChanged(); } }
+ public string Text { get; set; }//客户端编号
+ public string IPtext { get; set; }//IP文本框
+ public string Porttext { get; set; }//端口文本框
+ public string MessageText { get; set; }//发送框
+ private string _statecolour { get; set; }//状态指示灯
+ public string StateColour { get => _statecolour; set { _statecolour = value; OnPropertyChanged(); } }
+
+ private string _linkstate;//链接状态文本
+ public string LinkState { get => _linkstate; set { _linkstate = value; OnPropertyChanged(); } }
+
+ private string _infotext;//信息框
+ public string Infotext { get => _infotext; set
+ {
+ _infotext = value;
+ OnPropertyChanged(); // 通知 UI 更新
+ }
+ }
+ private string _rssiinfo;//RSSI强度
+ public string RSSIinfo { get => _rssiinfo; set { _rssiinfo = value; OnPropertyChanged(); } }
+ private string _countinfo;//count数值
+ public string Countinfo { get => _countinfo; set { _countinfo = value; OnPropertyChanged(); } }
+ private string _timeinfo;//当前时间
+ public string Timeinfo { get => _timeinfo; set { _timeinfo = value; OnPropertyChanged(); } }
+ private string _epcinfo;//EPC信息
+ private string _epcasc;//ASC2码 EPC信息
+ public string EPCinfo { get => _epcinfo; set { _epcinfo = value; OnPropertyChanged(); } }
+ public string EPCASC { get => _epcasc; set { _epcasc = value; OnPropertyChanged(); } }
+ private string _gpio1;
+ private string _gpio2;
+ private string _gpio3;
+ private string _gpio4;//GPIO1-4状态
+ public string GPIO1 { get => _gpio1; set { _gpio1 = value; OnPropertyChanged(); } }
+ public string GPIO2 { get => _gpio2; set { _gpio2 = value; OnPropertyChanged(); } }
+ public string GPIO3 { get => _gpio3; set { _gpio3 = value; OnPropertyChanged(); } }
+ public string GPIO4 { get => _gpio4; set { _gpio4 = value; OnPropertyChanged(); } }
+
+ private string _moduleinfo;
+ private string _motherboardhardware;
+ private string _motherboardfirmware;//设备信息
+ public string moduleInfo { get => _moduleinfo; set { _moduleinfo = value; OnPropertyChanged(); } }
+ public string motherboardHardware { get => _motherboardhardware; set { _motherboardhardware = value; OnPropertyChanged(); } }
+ public string motherboardFirmware { get => _motherboardfirmware; set { _motherboardfirmware = value; OnPropertyChanged(); } }
+
+ public string path;
+ public StreamWriter streamWriter;
+
+
+ public LinkCommand linkcomn;//链接命令
+
+ public LinkCommand sendcomn;//发送命令
+
+ public LinkCommand disconnectcomn;//断连命令
+
+ public LinkCommand clearcomn;//清空命令
+
+
+ public PanelItem(int index)
+ {
+ Text = $"客户端{index + 1}";
+ linkcomn = new LinkCommand(Button_Link);//绑定按钮的链接事件
+ sendcomn = new LinkCommand(Button_Click_Send);//绑定发送按钮的事件
+ disconnectcomn = new LinkCommand(Button_disconnect);//绑定断连按钮的事件
+ clearcomn = new LinkCommand(Button_clear);//绑定清空按钮的事件
+ try
+ {
+
+ path = Text + ".txt";
+ File.CreateText(path);
+
+ }
+ catch (Exception ex)
+ {
+ Infotext += ex;
+ }
+
+ //页面初始化
+ MessageText = string.Empty;
+ IPtext = "192.168.0.7";//默认IP
+ Porttext = "20108";//默认端口
+ StateColour = "Red";
+ LinkState = "未连接";
+ RSSIinfo = "##";
+ Countinfo = "00";
+ EPCASC = "###";
+ EPCinfo = "###";
+ GPIO1 = "低";
+ GPIO2 = "低";
+ GPIO3 = "低";
+ GPIO4 = "低";
+ }
+
+ public LinkCommand _linkcomn { get { return linkcomn; } }
+
+ public LinkCommand _sendcomn { get { return sendcomn; } }
+
+ public LinkCommand _disconnectcomn { get { return disconnectcomn; } }
+
+ public LinkCommand _clearcomn { get { return clearcomn; } }
+ private Task onSend(ITcpClient client, ReceivedDataEventArgs e)
+ {
+
+ return EasyTask.CompletedTask;
+ }
+
+
+ private Task onRecieved(ITcpClient client, ReceivedDataEventArgs e) //接收事件
+ {
+ string time = DateTime.Now.ToString();
+ string currentTime = time.Substring(10, time.Length-10);
+ var mes = e.ByteBlock.Span.ToString(Encoding.UTF8);
+ byte[] data = e.ByteBlock.Span.ToArray();
+ string hexString = BitConverter.ToString(data).Replace("-", " ");
+
+ Infotext += $"({currentTime})客户端接收到信息:\n{hexString}\n\n";
+
+ //读取状态
+ string readStateString = hexString.Replace(" ", "");//去掉字符串中空格
+ string dataLength = readStateString.Substring(4, 2);//获取字符串中内容长度
+ string commandState = readStateString.Substring(6, 2);//获取命令
+
+ int i = Convert.ToInt32(dataLength, 16);
+ if (i != 0)
+ {
+ switch (commandState)
+ {
+ case "02":
+ try
+ {
+ RSSIinfo = Convert.ToInt32(readStateString.Substring(14, 2), 16).ToString();//RSSI
+ Countinfo = Convert.ToInt32(readStateString.Substring(12, 2), 16).ToString();//Count
+ int TagNumber = Convert.ToInt32(readStateString.Substring(10,2),16);
+ Timeinfo = $"{currentTime} {time.Substring(0, 10)}";//获取时间
+
+ int startTemp = 33;
+
+ //Infotext += $"({currentTime})客户端接收到EPC信息:\n{EPCASC}\n\n";
+
+ List taglist = GetTagInfos(data);
+ ObservableCollection items = new ObservableCollection();
+ for (int j = 0; j < taglist.Count; j++)
+ {
+ int TempLength = taglist[j].EPCstring.Length * 3 -1;
+ EPCinfo = hexString.Substring(startTemp, TempLength);
+ items.Add(new TagItem(taglist[j].EPCstring, EPCinfo, taglist[j].RSSI.ToString(), taglist[j].Count.ToString(), Timeinfo));
+ startTemp += 16 + TempLength;
+ writeToTxt(path, $"EPC:{taglist[j].EPCstring}\nHEX:{EPCinfo}\nRSSI:{taglist[j].RSSI.ToString()} Count:{taglist[j].Count.ToString()} Time:{Timeinfo}\n____________________________");
+ }
+
+ TagItems = items;
+
+ }
+ catch (Exception ex) {
+ Infotext += ex;
+ }
+
+ break;
+
+ case "81":
+ //获取GPIO状态,16进制转二进制
+ string GPIOBinInfo = Convert.ToString(Convert.ToInt32(readStateString.Substring(12, 2), 16), 2).PadLeft(4, '0');
+ for (int j = 0; j < GPIOBinInfo.Length; j++)
+ {
+ //按位判断GPIO状态
+ switch (j)
+ {
+ case 0:
+ if (GPIOBinInfo.Substring(j, 1) == "1")
+ GPIO4 = "高";
+ else
+ GPIO4 = "低";
+ break;
+ case 1:
+ if (GPIOBinInfo.Substring(j, 1) == "1")
+ GPIO3 = "高";
+ else
+ GPIO3 = "低";
+ break;
+ case 2:
+ if (GPIOBinInfo.Substring(j, 1) == "1")
+ GPIO2 = "高";
+ else
+ GPIO2 = "低";
+ break;
+ case 3:
+ if (GPIOBinInfo.Substring(j, 1) == "1")
+ GPIO1 = "高";
+ else
+ GPIO1 = "低";
+ break;
+ default:
+ break;
+ }
+ }
+ break;
+ case "70":
+ //获取设备信息
+ switch (option)
+ {
+
+ case "00":
+ moduleInfo = Encoding.ASCII.GetString(HextoByte(readStateString.Substring(10, Convert.ToInt32(dataLength, 16) * 2)));
+ //Infotext += $"({currentTime})客户端接收到module信息:\n{moduleInfo}\n\n";
+ writeToTxt(path, $"模块信息:{moduleInfo}");
+ break;
+ case "03":
+ motherboardHardware = Encoding.ASCII.GetString(HextoByte(readStateString.Substring(10, Convert.ToInt32(dataLength, 16) * 2)));
+ //Infotext += $"({currentTime})客户端接收到hardware信息:\n{motherboardHardware}\n\n";
+ writeToTxt(path, $"硬件信息:{motherboardHardware}");
+ break;
+ case "04":
+ motherboardFirmware = Encoding.ASCII.GetString(HextoByte(readStateString.Substring(10, Convert.ToInt32(dataLength, 16) * 2)));
+ //Infotext += $"({currentTime})客户端接收到firmware信息:\n{motherboardFirmware}\n\n";
+ writeToTxt(path, $"固件信息:{motherboardFirmware}");
+ option = "";
+ break;
+ }
+ break;
+ default:
+ Infotext += $"default";
+ break;
+ }
+
+ //streamWriter.Close();
+ }
+ else
+ {
+ switch (commandState)
+ {
+ case "02":
+ Infotext += "未读取到\n";
+ RSSIinfo = "##";//未读取到数值时清空数据为初始值
+ Countinfo = "00";
+ EPCASC = "###";
+ EPCinfo = "###";
+ Timeinfo = $" {currentTime}\n{time.Substring(0, 10)}";//获取时间
+ break;
+ }
+ }
+
+ return EasyTask.CompletedTask;
+ }
+
+ private Task onConnected(ITcpClient client, ConnectedEventArgs e)//连接后初始化
+ {
+ Infotext += "已连接!\n";
+ StateColour = "Green";
+ LinkState = "已连接";
+ //streamWriter = new StreamWriter(path);
+
+ byte[] data = strToToHexByte("AA 55 01 70 00 71 0D");//获取模块信息
+ option = "00";
+ client.Send(data);
+
+ Thread.Sleep(500);
+
+ data = strToToHexByte("AA 55 01 70 03 72 0D");//获取主板硬件信息
+ option = "03";
+ client.Send(data);
+
+ Thread.Sleep(500);
+
+ data = strToToHexByte("AA 55 01 70 04 75 0D");//获取主板固件信息
+ option = "04";
+ client.Send(data);
+
+ Thread.Sleep(500);
+
+ data = strToToHexByte("AA 55 00 81 81 0D");//获取GPIO状态
+ client.Send(data);
+
+ Thread.Sleep(500);
+
+ data = strToToHexByte("AA 55 02 02 03 E8 EB 0D");//获取1000ms内标签信息
+ client.Send(data);
+ return EasyTask.CompletedTask;
+ }
+
+ private static byte[] HextoByte(string Temp)
+ {
+ byte[] Tempbytes = new byte[Temp.Length / 2];//16进制转byte数组
+ for (int m = 0; m < Temp.Length; m += 2)
+ {
+ try
+ {
+ Tempbytes[m / 2] = Convert.ToByte(Temp.Substring(m, 2), 16);
+ }
+ catch (Exception excp)
+ {
+
+ }
+ }
+ return Tempbytes;
+ }
+
+ private static byte[] strToToHexByte(string hexString)//字符串转16进制
+ {
+ hexString = hexString.Replace(" ", "");
+ if ((hexString.Length % 2) != 0)
+ hexString += " ";
+ byte[] returnBytes = new byte[hexString.Length / 2];
+ for (int i = 0; i < returnBytes.Length; i++)
+ returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Trim(), 16);
+ return returnBytes;
+ }
+
+ private static void writeToTxt(string path,string content)
+ {
+ StreamWriter streamWriter = new StreamWriter(path,true);
+ streamWriter.WriteLineAsync(content);
+ streamWriter.Close();
+ }
+
+ async void Button_Link()//链接按钮的事件
+ {
+ try
+ {
+ ip = IPAddress.Parse(IPtext);
+ port = int.Parse(Porttext);
+ client = new TcpClient();
+ //连接事件
+ client.Connected += onConnected;
+ //断连事件
+ client.Closed = (client, e) => { Infotext += "已断开!\n"; StateColour = "Red"; LinkState = "未连接"; streamWriter.Close(); return EasyTask.CompletedTask; };
+ //接收事件
+ client.Received += onRecieved;
+
+ //设置连接属性
+ await client.SetupAsync(new TouchSocketConfig().SetRemoteIPHost($"{IPtext}:{Porttext}").ConfigureContainer(a =>
+ {
+ a.AddConsoleLogger();//添加一个日志注入
+ }));
+
+ //开启连接
+ await client.ConnectAsync();
+ }
+ catch (Exception ex)
+ {
+ Infotext += $"处理请求时出错: {ex.Message}\n";
+ }
+ }
+
+ void Button_Click_Send()//发送按钮的事件
+ {
+ try
+ {
+ string message = MessageText;
+ if (message == string.Empty)
+ {
+ MessageBox.Show("输入内容不能为空!");
+ }
+ else
+ {
+ byte[] data = Encoding.UTF8.GetBytes(message);
+ client.Send(data);//发送原始数据
+ client.Send(strToToHexByte(message));//发送16进制数据
+ }
+ }
+ catch (Exception ex)
+ {
+ Infotext += $"处理请求时出错: {ex.Message}\n";
+ }
+ }
+
+ void Button_disconnect()
+ {
+ client.Close();//断开连接
+ }
+
+ void Button_clear()
+ {
+ Infotext = string.Empty;//清空信息框
+ }
+
+ //组件属性更改事件
+ public event PropertyChangedEventHandler PropertyChanged;
+ protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
+ {
+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
+ }
+
+ public class TagItem : INotifyPropertyChanged
+ {
+ private string _rssiinfo;//RSSI强度
+ public string RSSIinfo { get => _rssiinfo; set { _rssiinfo = value; OnPropertyChanged(); } }
+ private string _countinfo;//count数值
+ public string Countinfo { get => _countinfo; set { _countinfo = value; OnPropertyChanged(); } }
+ private string _timeinfo;//当前时间
+ public string Timeinfo { get => _timeinfo; set { _timeinfo = value; OnPropertyChanged(); } }
+ private string _epcinfo;//EPC信息
+ private string _epcasc;//ASC2码 EPC信息
+ public string EPCinfo { get => _epcinfo; set { _epcinfo = value; OnPropertyChanged(); } }
+ public string EPCASC { get => _epcasc; set { _epcasc = value; OnPropertyChanged(); } }
+
+ public TagItem(string infoEPC,string ascEPC,string RSSI,string count,string time)
+ {
+ EPCinfo = infoEPC;
+ EPCASC = ascEPC;
+ RSSIinfo = RSSI;
+ Countinfo = count;
+ Timeinfo = time;
+ }
+
+ public event PropertyChangedEventHandler PropertyChanged;
+ protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
+ {
+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
+ }
+ }
+
+ }
+ public TCPWindowV2()
+ {
+ InitializeComponent();
+ }
+
+ int currentcount = 0;//目前客户端的数量
+
+ List items = new List();//客户端组件列表
+
+ private void GenerateButton_Click(object sender, RoutedEventArgs e)//添加客户端框体
+ {
+ if (int.TryParse(CountTextBox.Text, out int count) && count > 0)
+ {
+ //var items = new List();
+ for (int i = 0; i < count; i++)
+ {
+ items.Add(new PanelItem(i + currentcount));
+ }
+ currentcount += count;
+ PanelContainer.ItemsSource = null;//刷新
+ PanelContainer.ItemsSource = items;
+
+ }
+ else
+ {
+ MessageBox.Show("请输入有效的正整数", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
+ }
+ }
+
+ public class LinkCommand : ICommand //command方法实现
+ {
+ private Action _excute;
+ public LinkCommand(Action action) {
+ _excute = action;
+ }
+ public event EventHandler CanExecuteChanged;
+
+ public bool CanExecute(object parameter)
+ {
+ return true;
+ }
+
+ public void Execute(object parameter)
+ {
+ _excute();
+ }
+ }
+
+ private void ClearButton_Click(object sender, RoutedEventArgs e)//清空客户端
+ {
+ items.Clear();
+ PanelContainer.ItemsSource = null;
+ currentcount = 0;
+ }
+
+ private static List GetTagInfos(byte[] AutoDealReportData)
+ {
+ List tagInfoList = new List();
+ try
+ {
+ int iFirstCountPos = 6; //第一次读取标签次数位置
+ int iFirstRSSIPos = 7; //第一次读取标签强度位置
+ int iFirstAnt = 8;
+ int iFirstPC = 9; //第一次读取标签天线位置
+ int iFirstLeftBarcketPos = 11;//EPC数据起始位置
+ UInt16 tempDataCount = 0;
+ int tempDataRSSI = 0;
+ UInt16 tempDataANT = 0;
+ int iBarcodeGroupCount = Convert.ToInt32(AutoDealReportData[5].ToString()); //标签组数
+ int iBarcodeLength = 16; //标签长度
+ int iCommonSecondFlag = 0;
+ int dataLength = Convert.ToInt32(AutoDealReportData[2].ToString());
+ for (int j = 0; j < iBarcodeGroupCount; j++)
+ {
+ TagInfo tag = new TagInfo();
+ byte[] tempPCByte = new byte[2]; //取出PC
+ Array.Clear(tempPCByte, 0, 2);
+ Array.Copy(AutoDealReportData, iFirstPC, tempPCByte, 0, 2);
+
+ //PC转二进制取前五位转十进制
+ int epcLength = Convert.ToInt32(Convert.ToString(Convert.ToInt64(tempPCByte[0].ToString("X"), 16), 2).PadLeft(8, '0').Substring(0, 5), 2) * 2;
+
+ iBarcodeLength = epcLength;
+
+ byte[] tempDataByte = new byte[epcLength];
+ Array.Clear(tempDataByte, 0, iBarcodeLength);
+ Array.Copy(AutoDealReportData, iFirstLeftBarcketPos, tempDataByte, 0, iBarcodeLength);
+
+ byte[] tempCountByte = new byte[1]; //取出标签次数
+ Array.Clear(tempCountByte, 0, 1);
+ Array.Copy(AutoDealReportData, iFirstCountPos, tempCountByte, 0, 1);
+ tempDataCount = tempCountByte[0];
+
+ byte[] tempRSSIByte = new byte[1]; //取出标签强度
+ Array.Clear(tempRSSIByte, 0, 1);
+ Array.Copy(AutoDealReportData, iFirstRSSIPos, tempRSSIByte, 0, 1);
+ tempDataRSSI = HexStringToNegative(bytesToHexStr(tempRSSIByte, 1));
+
+ #region add by wenjy 20220829 取出天线号
+ byte[] tempAntByte = new byte[1]; //取出天线号
+ Array.Clear(tempAntByte, 0, 1);
+ Array.Copy(AutoDealReportData, iFirstAnt, tempAntByte, 0, 1);
+ tempDataANT = tempAntByte[0];
+ #endregion
+
+ tag.Count = tempDataCount;
+ tag.RSSI = tempDataRSSI;
+ tag.EPC = tempDataByte;
+ tag.EPCstring = System.Text.Encoding.ASCII.GetString(tempDataByte);
+ tag.PC = tempPCByte;
+ tag.Antana = tempDataANT;
+ tagInfoList.Add(tag);
+ int iBarcodeListLen = tagInfoList.Count; //特别注意,必须这样,要不然会多一条数据
+
+ iFirstCountPos = iFirstCountPos + iBarcodeLength + 5; //次数
+ iFirstRSSIPos = iFirstCountPos + 1; //强度
+ iFirstAnt = iFirstRSSIPos + 1; //天线
+ iFirstPC = iFirstAnt + 1;
+ iFirstLeftBarcketPos = iFirstLeftBarcketPos + iBarcodeLength + 5;
+
+ iCommonSecondFlag++;
+ if (iCommonSecondFlag == iBarcodeGroupCount)
+ {
+ //mutauto.ReleaseMutex();
+ return tagInfoList;
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ //LogInfo.Info("----函数调用:Device_AutoDealContent 自动处理函数异常:" + ex.ToString());
+ //mutauto.ReleaseMutex();
+ }
+ return tagInfoList;
+
+
+ }
+
+
+
+
+ public static int HexStringToNegative(string strNumber)
+ {
+
+ int iNegate = 0;
+ int iNumber = Convert.ToInt32(strNumber, 16);
+ if (iNumber > 127)
+ {
+ int iComplement = iNumber - 1;
+ string strNegate = string.Empty;
+ char[] binchar = Convert.ToString(iComplement, 2).PadLeft(8, '0').ToArray();
+ foreach (char ch in binchar)
+ {
+ if (Convert.ToInt32(ch) == 48)
+ {
+ strNegate += "1";
+ }
+ else
+ {
+ strNegate += "0";
+ }
+ }
+ iNegate = -Convert.ToInt32(strNegate, 2);
+ }
+ return iNegate;
+ }
+
+
+
+ public class TagInfo
+ {
+ public byte[] PC = new byte[2];
+
+ public int Count;
+
+ public int RSSI;
+
+ public int Antana;
+
+ public byte[] EPC;
+
+ public byte[] Data;
+
+ public string PCstring = null;
+
+ public string EPCstring = null;
+
+ public DateTime Time;
+ }
+
+ ///
+ /// 将byte数组转换成十六进制字符串 //e.g. { 0x01, 0x01} ---> " 01 01"
+ ///
+ /// byte数组
+ /// 数组长度
+ /// 十六进制字符串
+ public static string bytesToHexStr(byte[] bytes, int iLen)
+ {
+ string returnStr = "";
+ if (bytes != null)
+ {
+ for (int i = 0; i < iLen; i++)
+ {
+ returnStr += bytes[i].ToString("X2");
+ }
+ }
+ return returnStr;
+ }
+ }
+}
diff --git a/SocketExample/TouchSocketWindow.xaml b/SocketExample/TouchSocketWindow.xaml
new file mode 100644
index 0000000..b5f4ddf
--- /dev/null
+++ b/SocketExample/TouchSocketWindow.xaml
@@ -0,0 +1,114 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/SocketExample/TouchSocketWindow.xaml.cs b/SocketExample/TouchSocketWindow.xaml.cs
new file mode 100644
index 0000000..7520a40
--- /dev/null
+++ b/SocketExample/TouchSocketWindow.xaml.cs
@@ -0,0 +1,199 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Net;
+using System.Runtime.CompilerServices;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Input;
+using System.Xml;
+using TouchSocket.Core;
+using TouchSocket.Sockets;
+
+namespace SocketExample
+{
+ ///
+ /// MultiClientsWindow.xaml 的交互逻辑
+ ///
+ public partial class TouchSocketWindow : Window
+ {
+
+ public class PanelItem:INotifyPropertyChanged //实现组件更改的接口
+ {
+ IPAddress ip;
+ int port;
+ TcpClient client;
+ public string Text { get; set; }
+ public string IPtext { get; set; }
+ public string Porttext { get; set; }
+ public string MessageText { get; set; }
+
+ private string _infotext;
+ public string Infotext { get => _infotext; set
+ {
+ _infotext = value;
+ OnPropertyChanged(); // 通知 UI 更新
+ }
+ }
+
+ public LinkCommand linkcomn;
+
+ public LinkCommand sendcomn;
+
+ public LinkCommand disconnectcomn;
+
+ public LinkCommand clearcomn;
+
+
+ public PanelItem(int index)
+ {
+ Text = $"客户端{index + 1}";
+ linkcomn = new LinkCommand(Button_Link);//绑定按钮的链接事件
+ sendcomn = new LinkCommand(Button_Click_Send);
+ disconnectcomn = new LinkCommand(Button_disconnect);
+ clearcomn = new LinkCommand(Button_clear);
+
+ MessageText = string.Empty;
+ IPtext = "127.0.0.1";//默认IP
+ Porttext = "8999";//默认端口
+ }
+
+ public LinkCommand _linkcomn { get { return linkcomn; } }
+
+ public LinkCommand _sendcomn { get { return sendcomn; } }
+
+ public LinkCommand _disconnectcomn { get { return disconnectcomn; } }
+
+ public LinkCommand _clearcomn { get { return clearcomn; } }
+ private Task onRecieved(ITcpClient client,ReceivedDataEventArgs e)
+ {
+ string time = DateTime.Now.ToString();
+ string currentTime = time.Substring(10, 5);
+ var mes = e.ByteBlock.Span.ToString(Encoding.UTF8);
+ Infotext += $"({currentTime})客户端接收到信息:\n{mes}\n\n";
+ return EasyTask.CompletedTask;
+ }
+
+ async void Button_Link()//链接按钮的事件
+ {
+ try
+ {
+ ip = IPAddress.Parse(IPtext);
+ port = int.Parse(Porttext);
+ client = new TcpClient();
+ client.Connected = (client, e) => { Infotext += "已连接!\n"; return EasyTask.CompletedTask; };
+ client.Closed = (client, e) => { Infotext += "已断开!\n"; return EasyTask.CompletedTask; };
+ client.Received += onRecieved;
+
+ await client.SetupAsync(new TouchSocketConfig().SetRemoteIPHost($"{IPtext}:{Porttext}").ConfigureContainer(a =>
+ {
+ a.AddConsoleLogger();//添加一个日志注入
+ }));
+
+ await client.ConnectAsync();
+
+ // 开始监听
+
+ }
+ catch (Exception ex)
+ {
+ Infotext += $"处理请求时出错: {ex.Message}\n";
+ }
+ }
+
+ void Button_Click_Send()//发送按钮的事件
+ {
+ try
+ {
+ string message = MessageText;
+ if (message == string.Empty)
+ {
+ MessageBox.Show("输入内容不能为空!");
+ }
+ else
+ {
+ byte[] data = Encoding.UTF8.GetBytes(message);
+ client.Send(data);
+ }
+ }
+ catch (Exception ex)
+ {
+ Infotext += $"处理请求时出错: {ex.Message}\n";
+ }
+ }
+
+ void Button_disconnect()
+ {
+ client.Close();
+ }
+
+ void Button_clear()
+ {
+ Infotext = string.Empty;
+ }
+
+ //组件属性更改事件
+ public event PropertyChangedEventHandler PropertyChanged;
+ protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
+ {
+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
+ }
+ }
+ public TouchSocketWindow()
+ {
+ InitializeComponent();
+ }
+
+ int currentcount = 0;
+
+ List items = new List();
+
+ private void GenerateButton_Click(object sender, RoutedEventArgs e)//添加客户端框体
+ {
+ if (int.TryParse(CountTextBox.Text, out int count) && count > 0)
+ {
+ //var items = new List();
+ for (int i = 0; i < count; i++)
+ {
+ items.Add(new PanelItem(i + currentcount));
+ }
+ currentcount += count;
+ PanelContainer.ItemsSource = null;//刷新
+ PanelContainer.ItemsSource = items;
+
+ }
+ else
+ {
+ MessageBox.Show("请输入有效的正整数", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
+ }
+ }
+
+ public class LinkCommand : ICommand //command方法实现
+ {
+ private Action _excute;
+ public LinkCommand(Action action) {
+ _excute = action;
+ }
+ public event EventHandler CanExecuteChanged;
+
+ public bool CanExecute(object parameter)
+ {
+ return true;
+ }
+
+ public void Execute(object parameter)
+ {
+ _excute();
+ }
+ }
+
+ private void ClearButton_Click(object sender, RoutedEventArgs e)//清空客户端
+ {
+ items.Clear();
+ PanelContainer.ItemsSource = null;
+ currentcount = 0;
+ }
+ }
+}
diff --git a/SocketExample/packages.config b/SocketExample/packages.config
new file mode 100644
index 0000000..060714a
--- /dev/null
+++ b/SocketExample/packages.config
@@ -0,0 +1,25 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file