1.新增监听后连接生成界面,断连去掉界面

2.修改前存档
master
zhangxy 5 days ago
parent 72cad5efd3
commit c1838474f3

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
<Costura />
</Weavers>

@ -0,0 +1,83 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using TouchSocket;
using TouchSocket.Core;
using TouchSocket.Sockets;
using static SocketExample.TCPWindowV2;
namespace SocketExample
{
public class MyTouchClass
{
public void ConnectedSend()
{
try
{
//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 72 72 0D");//获取功率状态
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 07 D0 D7 0D");//获取1000ms内标签信息
client.Send(data);
Thread.Sleep(1000);
GPIOthread = new Thread(new ThreadStart(delegate ()
{
while (true) { byte[] data = strToToHexByte("AA 55 00 81 81 0D"); client.Send(data); Thread.Sleep(1000); }
}));
GPIOthread.Start();//心跳获取GPIO状态
}
catch (Exception ex)
{
Infotext += $"连接时报错,错误内容:{ex}\n";
}
}
public sealed class MySessionClient : TcpSessionClient
{
protected override async Task OnTcpReceived(ReceivedDataEventArgs e)
{
//此处逻辑单线程处理。
//此处处理数据功能相当于Received委托。
var mes = e.ByteBlock.Span.ToString(Encoding.UTF8);
Console.WriteLine($"已接收到信息:{mes}");
await base.OnTcpReceived(e);
}
}
}
}

@ -1,5 +1,6 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\Costura.Fody.6.0.0\build\Costura.Fody.props" Condition="Exists('..\packages\Costura.Fody.6.0.0\build\Costura.Fody.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -63,6 +64,9 @@
<Reference Include="CommonServiceLocator, Version=2.0.2.0, Culture=neutral, PublicKeyToken=489b6accfaf20ef0, processorArchitecture=MSIL"> <Reference Include="CommonServiceLocator, Version=2.0.2.0, Culture=neutral, PublicKeyToken=489b6accfaf20ef0, processorArchitecture=MSIL">
<HintPath>..\packages\CommonServiceLocator.2.0.2\lib\net47\CommonServiceLocator.dll</HintPath> <HintPath>..\packages\CommonServiceLocator.2.0.2\lib\net47\CommonServiceLocator.dll</HintPath>
</Reference> </Reference>
<Reference Include="Costura, Version=6.0.0.0, Culture=neutral, PublicKeyToken=9919ef960d84173d, processorArchitecture=MSIL">
<HintPath>..\packages\Costura.Fody.6.0.0\lib\netstandard2.0\Costura.dll</HintPath>
</Reference>
<Reference Include="GalaSoft.MvvmLight, Version=5.4.1.0, Culture=neutral, PublicKeyToken=e7570ab207bcb616, processorArchitecture=MSIL"> <Reference Include="GalaSoft.MvvmLight, Version=5.4.1.0, Culture=neutral, PublicKeyToken=e7570ab207bcb616, processorArchitecture=MSIL">
<HintPath>..\packages\MvvmLightLibs.5.4.1.1\lib\net45\GalaSoft.MvvmLight.dll</HintPath> <HintPath>..\packages\MvvmLightLibs.5.4.1.1\lib\net45\GalaSoft.MvvmLight.dll</HintPath>
</Reference> </Reference>
@ -203,6 +207,7 @@
</Page> </Page>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="MyTouchClass.cs" />
<Compile Include="TCPWindowV2.xaml.cs"> <Compile Include="TCPWindowV2.xaml.cs">
<DependentUpon>TCPWindowV2.xaml</DependentUpon> <DependentUpon>TCPWindowV2.xaml</DependentUpon>
</Compile> </Compile>
@ -272,6 +277,9 @@
<ItemGroup> <ItemGroup>
<Resource Include="新增.png" /> <Resource Include="新增.png" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Resource Include="FodyWeavers.xml" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <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')" /> <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"> <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
@ -279,5 +287,10 @@
<ErrorText>这台计算机上缺少此项目引用的 NuGet 程序包。使用“NuGet 程序包还原”可下载这些程序包。有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。</ErrorText> <ErrorText>这台计算机上缺少此项目引用的 NuGet 程序包。使用“NuGet 程序包还原”可下载这些程序包。有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。</ErrorText>
</PropertyGroup> </PropertyGroup>
<Error Condition="!Exists('..\packages\System.ValueTuple.4.6.1\build\net471\System.ValueTuple.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\System.ValueTuple.4.6.1\build\net471\System.ValueTuple.targets'))" /> <Error Condition="!Exists('..\packages\System.ValueTuple.4.6.1\build\net471\System.ValueTuple.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\System.ValueTuple.4.6.1\build\net471\System.ValueTuple.targets'))" />
<Error Condition="!Exists('..\packages\Fody.6.8.2\build\Fody.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Fody.6.8.2\build\Fody.targets'))" />
<Error Condition="!Exists('..\packages\Costura.Fody.6.0.0\build\Costura.Fody.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Costura.Fody.6.0.0\build\Costura.Fody.props'))" />
<Error Condition="!Exists('..\packages\Costura.Fody.6.0.0\build\Costura.Fody.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Costura.Fody.6.0.0\build\Costura.Fody.targets'))" />
</Target> </Target>
<Import Project="..\packages\Fody.6.8.2\build\Fody.targets" Condition="Exists('..\packages\Fody.6.8.2\build\Fody.targets')" />
<Import Project="..\packages\Costura.Fody.6.0.0\build\Costura.Fody.targets" Condition="Exists('..\packages\Costura.Fody.6.0.0\build\Costura.Fody.targets')" />
</Project> </Project>

@ -105,9 +105,10 @@
<StackPanel x:Name="NewTerminal_StackPanel" Orientation="Horizontal" Margin="10 0 0 0" VerticalAlignment="Center"> <StackPanel x:Name="NewTerminal_StackPanel" Orientation="Horizontal" Margin="10 0 0 0" VerticalAlignment="Center">
<TextBlock Text="监控终端生成数量:" VerticalAlignment="Center" Margin="0,0,10,0" Foreground="White" FontSize="15" FontWeight="SemiBold"/> <TextBlock Text="监控终端生成数量:" VerticalAlignment="Center" Margin="0,0,10,0" Foreground="White" FontSize="15" FontWeight="SemiBold"/>
<TextBox x:Name="CountTextBox" Width="100" Margin="0,0,10,0" VerticalAlignment="Center" FontSize="15" FontWeight="SemiBold"/> <TextBox x:Name="CountTextBox" Width="50" Margin="0,0,10,0" VerticalAlignment="Center" FontSize="15" FontWeight="SemiBold"/>
<Button Content="生成" Click="GenerateButton_Click" Height="40" Width="50" Margin="10 0 0 0" Style="{StaticResource FlatButton}"/> <Button Content="生成" Click="GenerateButton_Click" Height="40" Width="50" Margin="10 0 0 0" Style="{StaticResource FlatButton}"/>
<Button Content="清空" Click="ClearButton_Click" Height="40" Width="50" Margin="10 0 0 0" Style="{StaticResource FlatButton}"/> <Button Content="清空" Click="ClearButton_Click" Height="40" Width="50" Margin="10 0 0 0" Style="{StaticResource FlatButton}"/>
<Button x:Name="ListenButton" Content="侦听" Click="ListenButton_Click" Height="40" Width="50" Margin="10 0 0 0" Style="{StaticResource FlatButton}"/>
</StackPanel> </StackPanel>
</Grid> </Grid>
<Grid Grid.Column="1" HorizontalAlignment="Right" Margin="0 0 10 0" VerticalAlignment="Center"> <Grid Grid.Column="1" HorizontalAlignment="Right" Margin="0 0 10 0" VerticalAlignment="Center">

@ -9,6 +9,7 @@ using System.IO;
using System.IO.Ports; using System.IO.Ports;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Net.NetworkInformation;
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
@ -36,6 +37,8 @@ using TouchSocket.Core;
using TouchSocket.Sockets; using TouchSocket.Sockets;
using ZstdSharp.Unsafe; using ZstdSharp.Unsafe;
using static SocketExample.MyTouchClass;
namespace SocketExample namespace SocketExample
{ {
/// <summary> /// <summary>
@ -49,13 +52,14 @@ namespace SocketExample
#region 变量定义 #region 变量定义
IPAddress ip; IPAddress ip;
int port; int port;
TcpClient client; ITcpClient client;
ITcpSessionClient TcpSessionClient;
public string option;//命令选项 public string option;//命令选项
public ICommand TextChangedCommand { get; } public ICommand TextChangedCommand { get; set; }
public ICommand SelectionChangedCommand { get; } public ICommand SelectionChangedCommand { get; set; }
public ICommand SendTextChangedCommand { get; } public ICommand SendTextChangedCommand { get; set; }
public ICommand GPOSelectionChangedCommand { get; } public ICommand GPOSelectionChangedCommand { get; set; }
private ObservableCollection<TagItem> _tagItems; private ObservableCollection<TagItem> _tagItems;
public ObservableCollection<TagItem> TagItems { get => _tagItems; set { _tagItems = value; OnPropertyChanged(); } } public ObservableCollection<TagItem> TagItems { get => _tagItems; set { _tagItems = value; OnPropertyChanged(); } }
@ -64,6 +68,7 @@ namespace SocketExample
public string Porttext { get; set; }//端口文本框 public string Porttext { get; set; }//端口文本框
private string _messagetext; private string _messagetext;
public string SessionID { get; set; }
public int Borderwidth { get => _borderwidth; set { _borderwidth = value; OnPropertyChanged(); } } public int Borderwidth { get => _borderwidth; set { _borderwidth = value; OnPropertyChanged(); } }
private int _borderwidth { get; set; } private int _borderwidth { get; set; }
public string MessageText { get => _messagetext; set { _messagetext = value; OnPropertyChanged(); } }//发送框 public string MessageText { get => _messagetext; set { _messagetext = value; OnPropertyChanged(); } }//发送框
@ -191,6 +196,22 @@ namespace SocketExample
public PanelItem(int index) public PanelItem(int index)
{ {
Text = $"客户端{index + 1}"; Text = $"客户端{index + 1}";
PanelInitialization();
}
public PanelItem(TcpSessionClient recieveClient)
{
Text = $"客户端{recieveClient.IP}";
TcpSessionClient = recieveClient as ITcpSessionClient;
SessionID = recieveClient.Id;
//断连事件
//TcpSessionClient.Closed = (client, e) => { try { GPIOthread.Abort(); Infotext += "已断开!\n"; StateColour = "Red"; LinkState = "未连接"; } catch (Exception ex) { Infotext += ex; } return EasyTask.CompletedTask; };
//接收事件
PanelInitialization();
}
public void PanelInitialization()//终端初始化
{
linkcomn = new LinkCommand(Button_Link);//绑定按钮的链接事件 linkcomn = new LinkCommand(Button_Link);//绑定按钮的链接事件
readcomn = new LinkCommand(Button_Read); readcomn = new LinkCommand(Button_Read);
stopreadingcomn = new LinkCommand(Button_StopReading); stopreadingcomn = new LinkCommand(Button_StopReading);
@ -232,7 +253,8 @@ namespace SocketExample
GPI2 = "低"; GPI2 = "低";
GPI3 = "低"; GPI3 = "低";
GPI4 = "低"; GPI4 = "低";
} }//终端初始化
#region 界面功能绑定定义 #region 界面功能绑定定义
public LinkCommand _powerselectchanged { get { return powerselectchanged; } } public LinkCommand _powerselectchanged { get { return powerselectchanged; } }
@ -645,12 +667,13 @@ namespace SocketExample
{ {
int number = 4; int number = 4;
int width = ((int)SystemParameters.PrimaryScreenWidth - 60) / number; int width = ((int)SystemParameters.PrimaryScreenWidth - 60) / number;
while(width<360 || width > 700){ while (width < 360 || width > 700)
{
if (width < 360) if (width < 360)
{ {
number--; number--;
} }
else if(width >700) else if (width > 700)
{ {
number++; number++;
} }
@ -1194,6 +1217,7 @@ namespace SocketExample
InitializeComponent(); InitializeComponent();
EnsureFolderExists("日志文件夹"); EnsureFolderExists("日志文件夹");
this.Closing += TCPWindowV2_Closing; this.Closing += TCPWindowV2_Closing;
PanelContainer.ItemsSource = items;
SaveWindowSettings(); SaveWindowSettings();
Buttonflag = 0; Buttonflag = 0;
} }
@ -1242,7 +1266,7 @@ namespace SocketExample
if (Buttonflag == 0) if (Buttonflag == 0)
{ {
this.WindowState = WindowState.Maximized; this.WindowState = WindowState.Maximized;
MaxMinImage.Source = new BitmapImage(new Uri(@"/取消全屏.png",UriKind.Relative)); MaxMinImage.Source = new BitmapImage(new Uri(@"/取消全屏.png", UriKind.Relative));
Buttonflag = 1; Buttonflag = 1;
} }
else else
@ -1267,7 +1291,112 @@ namespace SocketExample
PanelContainer.ItemsSource = null; PanelContainer.ItemsSource = null;
currentcount = 0; currentcount = 0;
} }
private void ListenButton_Click(object sender, RoutedEventArgs e)
{
Thread ListeningPortThread = new Thread(ListeningTheard);
ListeningPortThread.IsBackground = true;
ListeningPortThread.Start();
}
#endregion #endregion
#region 其他功能
private void ListeningTheard() //监听线程
{
IEnumerable<NetworkInterface> networkInterfaces = NetworkInterface.GetAllNetworkInterfaces()
.Where(nic => nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet // 仅以太网
&& nic.OperationalStatus == OperationalStatus.Up); // 仅已启用的接口
CreateListenConnect(networkInterfaces);
while (true)
{
IEnumerable<NetworkInterface> NewnetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces()
.Where(nic => nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet // 仅以太网
&& nic.OperationalStatus == OperationalStatus.Up); // 仅已启用的接口
var UniquenetworkInterfaces = NewnetworkInterfaces
.Where(newNic => !networkInterfaces.Any(oldNic => oldNic.Id == newNic.Id))
.ToList();
if (!UniquenetworkInterfaces.Any())
{
Thread.Sleep(1000);
continue;
}
networkInterfaces = NewnetworkInterfaces;
CreateListenConnect(UniquenetworkInterfaces);
}
}
private void CreateListenConnect(IEnumerable<NetworkInterface> networkInterfaces) //创建连接
{
foreach (var nic in networkInterfaces)
{
var ipProperties = nic.GetIPProperties();
var unicastAddresses = ipProperties.UnicastAddresses
.Where(addr => addr.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
foreach (var addr in unicastAddresses)
{
var tcpService = new TcpService();
tcpService.SetupAsync(new TouchSocketConfig()//载入配置
.SetListenIPHosts($"tcp://{addr.Address}:20108", 7790)//可以同时监听两个地址
.ConfigureContainer(a =>//容器的配置顺序应该在最前面
{
a.AddConsoleLogger();//添加一个控制台日志注入注意在maui中控制台日志不可用
})
.ConfigurePlugins(a =>
{
//a.Add();//此处可以添加插件
}));
tcpService.Connected += ListeningConnected;
tcpService.Closed += ListeningClosed;
tcpService.StartAsync();
Console.WriteLine($"网卡: {nic.Description}, IP: {addr.Address}");
MessageBox.Show($"{addr.Address}监听成功!");
}
}
}
private Task ListeningConnected(TcpSessionClient client, ConnectedEventArgs e) //连接事件
{
Application.Current.Dispatcher.Invoke(() =>
{
items.Add(new PanelItem(client));
PanelContainer.ItemsSource = null;
PanelContainer.ItemsSource = items;
});
return EasyTask.CompletedTask;
}
private Task ListeningClosed(TcpSessionClient client, ClosedEventArgs e) //断开事件
{
Application.Current.Dispatcher.Invoke(() =>
{
foreach (PanelItem item in items)
{
if (item.SessionID.Equals(client.Id))
{
try
{
items.Remove(item);
if (items.Count == 0)
break;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
PanelContainer.ItemsSource = null;
PanelContainer.ItemsSource = items;
});
return EasyTask.CompletedTask;
}
public class LinkCommand : ICommand //command方法实现 public class LinkCommand : ICommand //command方法实现
{ {
private Action _excute; private Action _excute;
@ -1529,5 +1658,6 @@ namespace SocketExample
OriginWindowState = this.WindowState; OriginWindowState = this.WindowState;
} }
#endregion
} }
} }

@ -2,6 +2,8 @@
<packages> <packages>
<package id="BouncyCastle.Cryptography" version="2.5.1" targetFramework="net48" /> <package id="BouncyCastle.Cryptography" version="2.5.1" targetFramework="net48" />
<package id="CommonServiceLocator" version="2.0.2" targetFramework="net48" /> <package id="CommonServiceLocator" version="2.0.2" targetFramework="net48" />
<package id="Costura.Fody" version="6.0.0" targetFramework="net48" developmentDependency="true" />
<package id="Fody" version="6.8.2" targetFramework="net48" developmentDependency="true" />
<package id="Google.Protobuf" version="3.30.0" targetFramework="net48" /> <package id="Google.Protobuf" version="3.30.0" targetFramework="net48" />
<package id="K4os.Compression.LZ4" version="1.3.8" targetFramework="net48" /> <package id="K4os.Compression.LZ4" version="1.3.8" targetFramework="net48" />
<package id="K4os.Compression.LZ4.Streams" version="1.3.8" targetFramework="net48" /> <package id="K4os.Compression.LZ4.Streams" version="1.3.8" targetFramework="net48" />

Loading…
Cancel
Save