1.整理程序集

2.更改名称与图标
master
zhangxy 3 weeks ago
parent 5d94176a0a
commit f55f6d5e16

@ -1,28 +0,0 @@
<Window x:Class="SocketExample.ClientWindow"
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:SocketExample"
mc:Ignorable="d"
Title="ClientWindow" Height="450" Width="800">
<Grid>
<StackPanel x:Name="InformationPanel" Margin="0,72,400,10" >
<TextBlock x:Name="InfoTextBlock_Client" TextWrapping="Wrap" Text="" Height="352"/>
</StackPanel>
<StackPanel Margin="0,0,0,375" Orientation="Horizontal">
<Label Content="IP地址" Height="30" Margin="40 8 10 0"/>
<TextBox TextWrapping="Wrap" x:Name="IPtextbox" Text="127.0.0.1" Width="200" Height="30" Margin="0 8 10 0"/>
<Label Content="端口号" Height="30" Margin="40 8 10 0"/>
<TextBox TextWrapping="Wrap" Text="8999" x:Name="Porttextbox" Width="200" Height="30" Margin="0 8 10 0"/>
<Button Content="链接" Height="30" Margin="30 8 10 0" Click="Button_Click"/>
<Button Content="清空" Height="30" Margin="30 8 10 0"/>
</StackPanel>
<StackPanel Margin="400,72,0,10">
<TextBox TextWrapping="Wrap" x:Name="MessageTextBox_Client" Text="请输入需要发送的内容" Width="250" Height="100" Margin="10,72,0,10"/>
<Button Content="发送" Margin="10,20,0,10" Width="250" Click="Button_Click_Send" />
</StackPanel>
</Grid>
</Window>

@ -1,115 +0,0 @@
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
{
/// <summary>
/// ClientWindow.xaml 的交互逻辑
/// </summary>
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";
});
}
}
// 关闭连接
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

@ -1,67 +0,0 @@
<Window x:Class="SocketExample.MultiClientsWindow"
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:SocketExample"
mc:Ignorable="d"
Title="MultiClientsWindow" Height="450" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Orientation="Horizontal" Margin="10">
<TextBlock Text="Panel生成数量:" VerticalAlignment="Center" Margin="0,0,10,0"/>
<TextBox x:Name="CountTextBox" Width="100" Margin="0,0,10,0"/>
<Button Content="生成" Click="GenerateButton_Click" Padding="10,5"/>
<Button Content="清空" Click="ClearButton_Click" Padding="10,5" Margin="10 0 0 0"/>
</StackPanel>
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto">
<ItemsControl x:Name="PanelContainer">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal"></WrapPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical" Margin="5 5 5 5" Width="370" Height="400">
<Border Width="Auto" Background="LightSkyBlue" >
<TextBlock Width="Auto" Text="{Binding Text}"></TextBlock>
</Border>
<StackPanel Orientation="Horizontal" Width="360">
<Label Content="IP地址" Height="30" Margin="10 8 0 0"/>
<TextBox TextWrapping="Wrap" x:Name="IPtextbox" Text="{Binding IPtext}" Width="75" Height="30" Margin="10 8 0 0"/>
<Label Content="端口号" Height="30" Margin="10 8 0 0"/>
<TextBox TextWrapping="Wrap" Text="{Binding Porttext}" x:Name="Porttextbox" MinWidth="40" Height="30" Margin="10 8 0 0"/>
<Button Content="链接" Height="30" Margin="10 8 0 0" Command="{Binding _linkcomn}"/>
<Button Content="清空" Height="30" Margin="10 8 0 0" Command="{Binding _clearcomn}"/>
<Button Content="断开" Height="30" Margin="10 8 10 0" Command="{Binding _disconnectcomn}"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Width="360" Margin="0,5,0,5" Height="250">
<Border Height="Auto" Width="200" BorderBrush="Black" BorderThickness="0.5" Margin="5,5,10,0" >
<ScrollViewer VerticalScrollBarVisibility="Auto">
<TextBlock x:Name="InfoTextBlock_Client" TextWrapping="Wrap" Text="{Binding Infotext}" Height="Auto" Width="Auto" Margin="5,5,5,5"></TextBlock>
</ScrollViewer>
</Border>
<StackPanel Orientation="Vertical" Margin="0,5,0,0" Width="140">
<TextBox TextWrapping="Wrap" x:Name="MessageTextBox_Client" Text="{Binding MessageText}" Height="200" Margin="0,0,0,10"/>
<Button Content="发送" Width="50" HorizontalAlignment="Center" Command="{Binding _sendcomn}" />
</StackPanel>
</StackPanel>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>
</Window>

@ -1,212 +0,0 @@
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
{
/// <summary>
/// MultiClientsWindow.xaml 的交互逻辑
/// </summary>
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<PanelItem> items = new List<PanelItem>();
private void GenerateButton_Click(object sender, RoutedEventArgs e)//添加客户端框体
{
if (int.TryParse(CountTextBox.Text, out int count) && count > 0)
{
//var items = new List<PanelItem>();
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;
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 172 KiB

@ -7,11 +7,11 @@ using System.Windows;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("SocketExample")]
[assembly: AssemblyTitle("RFIDMultMonitor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SocketExample")]
[assembly: AssemblyProduct("RFIDMultMonitor")]
[assembly: AssemblyCopyright("Copyright © 2025")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

@ -7,7 +7,7 @@
<ProjectGuid>{7E4E4E45-2FB2-4346-A101-4863BCDF50F9}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>SocketExample</RootNamespace>
<AssemblyName>SocketExample</AssemblyName>
<AssemblyName>RFIDMultiMonitor</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
@ -16,6 +16,21 @@
<Deterministic>true</Deterministic>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
@ -38,6 +53,9 @@
<WarningLevel>4</WarningLevel>
<LangVersion>preview</LangVersion>
</PropertyGroup>
<PropertyGroup>
<ApplicationIcon>Pictogrammers-Material-Monitor-eye.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<Reference Include="BouncyCastle.Cryptography, Version=2.0.0.0, Culture=neutral, PublicKeyToken=072edcf4a5328938, processorArchitecture=MSIL">
<HintPath>..\packages\BouncyCastle.Cryptography.2.5.1\lib\net461\BouncyCastle.Cryptography.dll</HintPath>
@ -145,7 +163,7 @@
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ClientWindow.xaml">
<Page Include="BackUP\ClientWindow.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
@ -160,7 +178,7 @@
<Compile Include="BackUP\TCPWindowV2-BackUp.xaml.cs">
<DependentUpon>TCPWindowV2-BackUp.xaml</DependentUpon>
</Compile>
<Compile Include="ClientWindow.xaml.cs">
<Compile Include="BackUP\ClientWindow.xaml.cs">
<DependentUpon>ClientWindow.xaml</DependentUpon>
</Compile>
<Compile Include="MainWindow.xaml.cs">
@ -171,15 +189,15 @@
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="TCPWindow.xaml">
<Page Include="BackUP\TCPWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="TouchSocketWindow.xaml">
<Page Include="BackUP\TouchSocketWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="MultiClientsWindow.xaml">
<Page Include="BackUP\MultiClientsWindow.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
@ -188,13 +206,13 @@
<Compile Include="TCPWindowV2.xaml.cs">
<DependentUpon>TCPWindowV2.xaml</DependentUpon>
</Compile>
<Compile Include="TCPWindow.xaml.cs">
<Compile Include="BackUP\TCPWindow.xaml.cs">
<DependentUpon>TCPWindow.xaml</DependentUpon>
</Compile>
<Compile Include="TouchSocketWindow.xaml.cs">
<Compile Include="BackUP\TouchSocketWindow.xaml.cs">
<DependentUpon>TouchSocketWindow.xaml</DependentUpon>
</Compile>
<Compile Include="MultiClientsWindow.xaml.cs">
<Compile Include="BackUP\MultiClientsWindow.xaml.cs">
<DependentUpon>MultiClientsWindow.xaml</DependentUpon>
</Compile>
<Compile Include="Properties\AssemblyInfo.cs">
@ -226,6 +244,21 @@
<ItemGroup>
<Analyzer Include="..\packages\TouchSocket.Core.3.1.2\analyzers\dotnet\cs\TouchSocket.Core.SourceGenerator.dll" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.8">
<Visible>False</Visible>
<ProductName>Microsoft .NET Framework 4.8 %28x86 和 x64%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<ItemGroup>
<Resource Include="Pictogrammers-Material-Monitor-eye.ico" />
</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">

@ -1,214 +0,0 @@
<Window x:Class="SocketExample.TCPWindow"
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:SocketExample"
mc:Ignorable="d"
Title="MultiClientsWindow" Height="450" Width="800">
<Window.Resources>
<Style x:Key="SocketButton" TargetType="Button" BasedOn="{StaticResource BaseButtonStyle}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="ButtonBorder" CornerRadius="3">
<Border.Background>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Color="#FF4A90E2" Offset="0"/>
<GradientStop Color="#FF1E62D0" Offset="1"/>
</LinearGradientBrush>
</Border.Background>
<ContentPresenter HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="ButtonBorder" Property="Background">
<Setter.Value>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Color="#FF5D9CEC" Offset="0"/>
<GradientStop Color="#FF2D76DB" Offset="1"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="ButtonBorder" Property="Background">
<Setter.Value>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Color="#FF3D7BC8" Offset="0"/>
<GradientStop Color="#FF0D4BB6" Offset="1"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Orientation="Horizontal" Margin="10" Height="30">
<TextBlock Text="Panel生成数量:" VerticalAlignment="Center" Margin="0,0,10,0"/>
<TextBox x:Name="CountTextBox" Width="100" Margin="0,0,10,0" VerticalAlignment="Center"/>
<Button Content="生成" Click="GenerateButton_Click" Width="50" Margin="10 0 0 0" Style="{StaticResource SocketButton}"/>
<Button Content="清空" Click="ClearButton_Click" Width="50" Margin="10 0 0 0" Style="{StaticResource SocketButton}"/>
</StackPanel>
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto">
<ItemsControl x:Name="PanelContainer">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal"></WrapPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderThickness="1" BorderBrush="Black" Margin="1">
<StackPanel Orientation="Vertical" Margin="5 5 5 5" Width="360" >
<Border Width="Auto" Background="LightSkyBlue" >
<TextBlock Width="Auto" Text="{Binding Text}"></TextBlock>
</Border>
<StackPanel Orientation="Horizontal" Width="350">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<Label Content="IP地址" Height="30" Margin="10 8 0 0"/>
<TextBox TextWrapping="Wrap" x:Name="IPtextbox" Text="{Binding IPtext}" Width="75" Height="30" Margin="5 8 0 0"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Label Content="端口号" Height="30" Margin="10 8 0 0"/>
<TextBox TextWrapping="Wrap" Text="{Binding Porttext}" x:Name="Porttextbox" Width="45" Height="30" Margin="5 8 0 0"/>
</StackPanel>
</StackPanel>
<Ellipse Width="20" Height="20" Fill="{Binding StateColour}" Margin="30 8 0 0"/>
<Label Height="30" Content="{Binding LinkState}" Margin="2 8 0 0"></Label>
<Button Content="连接" Height="30" Margin="10 8 0 0" Command="{Binding _linkcomn}" Style="{StaticResource SocketButton}"/>
<Button Content="清空" Height="30" Margin="10 8 0 0" Command="{Binding _clearcomn}" Style="{StaticResource SocketButton}"/>
<Button Content="断开" Height="30" Margin="10 8 10 0" Command="{Binding _disconnectcomn}" Style="{StaticResource SocketButton}"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Width="350" Margin="0,5,0,5" Height="100">
<Border Height="Auto" Width="200" BorderBrush="Black" BorderThickness="0.5" Margin="5,5,10,0" >
<ScrollViewer VerticalScrollBarVisibility="Auto">
<TextBlock x:Name="InfoTextBlock_Client" TextWrapping="Wrap" Text="{Binding Infotext}" Height="Auto" Width="Auto" Margin="5,5,5,5"></TextBlock>
</ScrollViewer>
</Border>
<StackPanel Orientation="Vertical" Margin="0,5,0,0" Width="130">
<TextBlock Text="请输入需要发送的内容:"></TextBlock>
<TextBox TextWrapping="Wrap" x:Name="MessageTextBox_Client" Text="{Binding MessageText}" Height="50" Margin="0,0,0,5"/>
<Button Content="发送" Width="50" HorizontalAlignment="Center" Command="{Binding _sendcomn}" Style="{StaticResource SocketButton}"/>
</StackPanel>
</StackPanel>
<Border BorderBrush="Black" BorderThickness="0.5">
<StackPanel Orientation="Vertical">
<Label Content="{Binding EPCASC}"></Label>
<Label Content="{Binding EPCinfo}"></Label>
</StackPanel>
</Border>
<Border BorderBrush="Black" BorderThickness="0.5">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Label Grid.Column="0" Content="RSSI" HorizontalAlignment="Left"/>
<Label Grid.Column="1" Content="Count" HorizontalAlignment="Center"/>
<Label Grid.Column="2" Content="Time" HorizontalAlignment="Right" Margin="0 0 20 0"/>
<Label Grid.Column="0" Grid.Row="1" Content="{Binding RSSIinfo}" HorizontalAlignment="Left"/>
<Label Grid.Column="1" Grid.Row="1" Content="{Binding Countinfo}" HorizontalAlignment="Center"/>
<Label Grid.Column="2" Grid.Row="1" Content="{Binding Timeinfo}" HorizontalAlignment="Right"/>
</Grid>
</Border>
<Border BorderBrush="Black" BorderThickness="0.5">
<Grid Margin="0 0 0 2">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Label Grid.Row="0" HorizontalAlignment="Center" Content="GPIO状态"></Label>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0" Orientation="Horizontal">
<Label Content="GPIO1" HorizontalAlignment="Left"/>
<Border BorderBrush="Black" BorderThickness="0.5">
<Label Content="{Binding GPIO1}"></Label>
</Border>
</StackPanel>
<StackPanel Grid.Column="1" Orientation="Horizontal">
<Label Content="GPIO2" HorizontalAlignment="Left"/>
<Border BorderBrush="Black" BorderThickness="0.5">
<Label Content="{Binding GPIO2}"></Label>
</Border>
</StackPanel>
<StackPanel Grid.Column="2" Orientation="Horizontal">
<Label Content="GPIO3" HorizontalAlignment="Left"/>
<Border BorderBrush="Black" BorderThickness="0.5">
<Label Content="{Binding GPIO3}"></Label>
</Border>
</StackPanel>
<StackPanel Grid.Column="3" Orientation="Horizontal">
<Label Content="GPIO4" HorizontalAlignment="Left"/>
<Border BorderBrush="Black" BorderThickness="0.5">
<Label Content="{Binding GPIO4}"></Label>
</Border>
</StackPanel>
</Grid>
</Grid>
</Border>
<Border BorderBrush="Black" BorderThickness="0.5">
<Grid Margin="0 0 0 2">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Label Grid.Row="0" Content="版本信息" HorizontalAlignment="Center"/>
<StackPanel Grid.Row="1" Orientation="Horizontal">
<Label Content="模块型号:" HorizontalAlignment="Left"/>
<Label Content="{Binding moduleInfo}"></Label>
</StackPanel>
<StackPanel Grid.Row="2" Orientation="Horizontal">
<Label Content="主板硬件号:" HorizontalAlignment="Left"/>
<Label Content="{Binding motherboardHardware}"></Label>
</StackPanel>
<StackPanel Grid.Row="3" Orientation="Horizontal">
<Label Content="主板固件号:" HorizontalAlignment="Left"/>
<Label Content="{Binding motherboardFirmware}"></Label>
</StackPanel>
</Grid>
</Border>
</StackPanel>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>
</Window>

@ -1,592 +0,0 @@
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
{
/// <summary>
/// MultiClientsWindow.xaml 的交互逻辑
/// </summary>
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":
List<TagInfo>taglist = 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<PanelItem> items = new List<PanelItem>();//客户端组件列表
private void GenerateButton_Click(object sender, RoutedEventArgs e)//添加客户端框体
{
if (int.TryParse(CountTextBox.Text, out int count) && count > 0)
{
//var items = new List<PanelItem>();
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<TagInfo> GetTagInfos(byte[] AutoDealReportData)
{
List<TagInfo> tagInfoList = new List<TagInfo>();
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;
}
/// <summary>
/// 将byte数组转换成十六进制字符串 //e.g. { 0x01, 0x01} ---> " 01 01"
/// </summary>
/// <param name="bytes">byte数组</param>
/// <param name="iLen">数组长度</param>
/// <returns>十六进制字符串</returns>
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;
}
}
}

@ -6,7 +6,7 @@
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
xmlns:local="clr-namespace:SocketExample"
mc:Ignorable="d"
Title="RFID读写器多终端监控软件v1.03" Height="450" Width="800">
Title="RFID读写器多终端监控软件v1.031" Height="450" Width="800">
<Window.Resources>
<Style x:Key="SocketButton" TargetType="Button" BasedOn="{StaticResource BaseButtonStyle}">

@ -1,114 +0,0 @@
<Window x:Class="SocketExample.TouchSocketWindow"
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:SocketExample"
mc:Ignorable="d"
Title="MultiClientsWindow" Height="450" Width="800">
<Window.Resources>
<Style x:Key="SocketButton" TargetType="Button" BasedOn="{StaticResource BaseButtonStyle}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="ButtonBorder" CornerRadius="3">
<Border.Background>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Color="#FF4A90E2" Offset="0"/>
<GradientStop Color="#FF1E62D0" Offset="1"/>
</LinearGradientBrush>
</Border.Background>
<ContentPresenter HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="ButtonBorder" Property="Background">
<Setter.Value>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Color="#FF5D9CEC" Offset="0"/>
<GradientStop Color="#FF2D76DB" Offset="1"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="ButtonBorder" Property="Background">
<Setter.Value>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Color="#FF3D7BC8" Offset="0"/>
<GradientStop Color="#FF0D4BB6" Offset="1"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Orientation="Horizontal" Margin="10" Height="30">
<TextBlock Text="Panel生成数量:" VerticalAlignment="Center" Margin="0,0,10,0"/>
<TextBox x:Name="CountTextBox" Width="100" Margin="0,0,10,0" VerticalAlignment="Center"/>
<Button Content="生成" Click="GenerateButton_Click" Width="50" Margin="10 0 0 0" Style="{StaticResource SocketButton}"/>
<Button Content="清空" Click="ClearButton_Click" Width="50" Margin="10 0 0 0" Style="{StaticResource SocketButton}"/>
</StackPanel>
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto">
<ItemsControl x:Name="PanelContainer">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal"></WrapPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderThickness="1" BorderBrush="Black" Margin="1">
<StackPanel Orientation="Vertical" Margin="5 5 5 5" Width="360" Height="390">
<Border Width="Auto" Background="LightSkyBlue" >
<TextBlock Width="Auto" Text="{Binding Text}"></TextBlock>
</Border>
<StackPanel Orientation="Horizontal" Width="350">
<Label Content="IP地址" Height="30" Margin="10 8 0 0"/>
<TextBox TextWrapping="Wrap" x:Name="IPtextbox" Text="{Binding IPtext}" Width="75" Height="30" Margin="5 8 0 0"/>
<Label Content="端口号" Height="30" Margin="10 8 0 0"/>
<TextBox TextWrapping="Wrap" Text="{Binding Porttext}" x:Name="Porttextbox" Width="40" Height="30" Margin="5 8 0 0"/>
<Button Content="链接" Height="30" Margin="10 8 0 0" Command="{Binding _linkcomn}" Style="{StaticResource SocketButton}"/>
<Button Content="清空" Height="30" Margin="10 8 0 0" Command="{Binding _clearcomn}" Style="{StaticResource SocketButton}"/>
<Button Content="断开" Height="30" Margin="10 8 10 0" Command="{Binding _disconnectcomn}" Style="{StaticResource SocketButton}"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Width="350" Margin="0,5,0,5" Height="300">
<Border Height="Auto" Width="200" BorderBrush="Black" BorderThickness="0.5" Margin="5,5,10,0" >
<ScrollViewer VerticalScrollBarVisibility="Auto">
<TextBlock x:Name="InfoTextBlock_Client" TextWrapping="Wrap" Text="{Binding Infotext}" Height="Auto" Width="Auto" Margin="5,5,5,5"></TextBlock>
</ScrollViewer>
</Border>
<StackPanel Orientation="Vertical" Margin="0,5,0,0" Width="130">
<TextBlock Text="请输入需要发送的内容:"></TextBlock>
<TextBox TextWrapping="Wrap" x:Name="MessageTextBox_Client" Text="{Binding MessageText}" Height="250" Margin="0,0,0,5"/>
<Button Content="发送" Width="50" HorizontalAlignment="Center" Command="{Binding _sendcomn}" Style="{StaticResource SocketButton}"/>
</StackPanel>
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>
</Window>

@ -1,199 +0,0 @@
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
{
/// <summary>
/// MultiClientsWindow.xaml 的交互逻辑
/// </summary>
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<PanelItem> items = new List<PanelItem>();
private void GenerateButton_Click(object sender, RoutedEventArgs e)//添加客户端框体
{
if (int.TryParse(CountTextBox.Text, out int count) && count > 0)
{
//var items = new List<PanelItem>();
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;
}
}
}
Loading…
Cancel
Save