Skip to content

Commit cb9e49b

Browse files
author
panwenbo
committed
v2.8.4 优化TCP工具和对应设置参数;
1 parent 22a5906 commit cb9e49b

File tree

16 files changed

+574
-280
lines changed

16 files changed

+574
-280
lines changed

One.Core/Helpers/NetHelpers/AsyncTCPClient.cs

Lines changed: 33 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
using System;
2+
using System.Diagnostics;
23
using System.Linq;
34
using System.Net;
45
using System.Net.Sockets;
56
using System.Threading;
7+
using System.Threading.Tasks;
68

79
namespace One.Core.Helpers.NetHelpers
810
{
@@ -23,7 +25,7 @@ public class AsyncTCPClient : BaseHelper
2325
public Action<byte[]> SendAction;
2426
public Action<byte[]> OnConnected;
2527
public Action<byte[]> OnDisConnected;
26-
28+
public Action<bool> OnConnectedBool;
2729
public CancellationToken cancellationToken = default;
2830

2931
/// <summary> 暂时不起作用 </summary>
@@ -36,7 +38,7 @@ public AsyncTCPClient(Action<string> logAction) : base(logAction)
3638
/// <summary> 初始化作为客户端并连接 </summary>
3739
/// <param name="ip"> </param>
3840
/// <param name="port"> </param>
39-
public bool InitClient(IPAddress ip, int port)
41+
public void Connect(IPAddress ip, int port)
4042
{
4143
try
4244
{
@@ -47,22 +49,23 @@ public bool InitClient(IPAddress ip, int port)
4749
SocketAsyncEventArgs e = new SocketAsyncEventArgs();
4850
e.RemoteEndPoint = ipEndPoint;
4951
e.UserToken = socket;
52+
5053
e.Completed += new EventHandler<SocketAsyncEventArgs>(ConnectComplete);
51-
e.SetBuffer(System.Text.Encoding.UTF8.GetBytes("Hello!"));
54+
//e.SetBuffer(System.Text.Encoding.UTF8.GetBytes("Hello!"));//发这个会出意外,本地打印log就行
5255

53-
var willRaiseEvent = socket.ConnectAsync(e);
56+
var pending = socket.ConnectAsync(e);
5457

55-
if (!willRaiseEvent)//暂时没发现有什么用
58+
var a = $"{socket.LocalEndPoint.ToString()} connecting......";
59+
var info = System.Text.Encoding.UTF8.GetBytes(a);
60+
OnConnected?.Invoke(info);
61+
if (!pending)//同步的走这里
5662
{
5763
ConnectComplete(this, e);
5864
}
59-
60-
return true;
6165
}
6266
catch (Exception ex)
6367
{
6468
WriteLog(ex.ToString());
65-
return false;
6669
}
6770
}
6871

@@ -77,10 +80,16 @@ private void ConnectComplete(object sender, SocketAsyncEventArgs e)
7780
{
7881
//客户端自己的Socket,也可以直接用最开始的socket
7982
var localClientSocket = e.ConnectSocket;//连接的 Socket 对象。
83+
8084
var addressFamily = localClientSocket.AddressFamily.ToString();
81-
// var a = localClientSocket.LocalEndPoint.ToString();
85+
86+
OnConnectedBool?.Invoke(localClientSocket.Connected);
87+
Debug.WriteLine("Status:" + localClientSocket.Connected);
88+
8289
var a = $"{localClientSocket.LocalEndPoint.ToString()} connected!";
8390

91+
Debug.WriteLine(localClientSocket.RemoteEndPoint.ToString());
92+
8493
var info = System.Text.Encoding.UTF8.GetBytes(a);
8594
OnConnected?.Invoke(info);
8695

@@ -91,9 +100,13 @@ private void ConnectComplete(object sender, SocketAsyncEventArgs e)
91100
}
92101
catch (Exception ex)
93102
{
94-
WriteLog($"连接失败 => {ex}");
103+
OnConnectedBool?.Invoke(false);
95104

96-
// throw;
105+
var a = $"{e.RemoteEndPoint.ToString()} connect failed!";
106+
107+
var info = System.Text.Encoding.UTF8.GetBytes(a);
108+
OnConnected?.Invoke(info);
109+
WriteLog($"连接失败 => {ex}");
97110
}
98111
}
99112

@@ -104,6 +117,7 @@ public void ReleaseClient()
104117
try
105118
{
106119
socket.Shutdown(SocketShutdown.Both);
120+
OnConnectedBool?.Invoke(false);
107121

108122
var a = $"{socket.LocalEndPoint} disconnected!";
109123
var info = System.Text.Encoding.UTF8.GetBytes(a);
@@ -114,17 +128,20 @@ public void ReleaseClient()
114128
catch (Exception ex)
115129
{
116130
WriteLog(ex.ToString());
117-
throw ex;
131+
throw;
118132
}
119133
}
120134

121135
public async void SendData(byte[] data)
122136
{
123137
try
124138
{
125-
// int count = sckClient.Send(data);
126-
//Console.WriteLine("发送数据长度为:" + count);
139+
if (!socket.Connected)
140+
{
141+
OnConnectedBool?.Invoke(false);
127142

143+
return;
144+
}
128145
int bytesSent = 0;
129146
while (bytesSent < data.Length)
130147
{
@@ -161,7 +178,9 @@ private async void Receive()
161178
}
162179
catch (Exception ex)
163180
{
181+
//不能上抛
164182
WriteLog(ex.ToString());
183+
//throw ex;
165184
}
166185
}
167186
}

One.Toolbox/Component/SerialPortComponent.cs

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -25,17 +25,15 @@ internal class SerialPortComponent : BaseVM
2525

2626
private static readonly object objLock = new object();
2727

28-
private SerialportSettingVM SerialportSetting { get; set; }
28+
private SerialportSettingModel SerialportSetting { get; set; }
2929

3030
/// <summary> 初始化串口各个触发函数 </summary>
3131
public SerialPortComponent()
3232
{
3333
//声明接收到事件
3434
serialPort.DataReceived += Serial_DataReceived;
35-
36-
new Thread(ReadData).Start();
3735

38-
36+
new Thread(ReadData).Start();
3937
}
4038

4139
/// <summary> 刷新串口对象 </summary>
@@ -92,7 +90,7 @@ private void refreshSerialDevice()
9290
serialPort = new SerialPort();
9391
//声明接收到事件
9492
serialPort.DataReceived += Serial_DataReceived;
95-
93+
9694
WriteTraceLog($"[refreshSerialDevice]done");
9795
}
9896

@@ -118,7 +116,7 @@ public bool IsOpen()
118116
}
119117

120118
/// <summary> 开启串口 </summary>
121-
public void Open(SerialportSettingVM serialportParams)
119+
public void Open(SerialportSettingModel serialportParams)
122120
{
123121
string temp = serialPort.PortName;
124122
WriteTraceLog($"[UartOpen]refreshSerialDevice");
@@ -157,7 +155,7 @@ public void SendData(byte[] data)
157155
if (data.Length == 0)
158156
return;
159157
serialPort.Write(data, 0, data.Length);
160-
158+
161159
UartDataSent(data, EventArgs.Empty);//回调
162160
}
163161

@@ -179,9 +177,9 @@ private void ReadData()
179177
while (true)
180178
{
181179
WaitUartReceive.WaitOne();
182-
183-
if (SerialportSetting.Timeout > 0)
184-
Thread.Sleep(SerialportSetting.Timeout);//等待时间
180+
181+
if (SerialportSetting.SendAndReceiveSettingModel.Timeout > 0)
182+
Thread.Sleep(SerialportSetting.SendAndReceiveSettingModel.Timeout);//等待时间
185183
List<byte> result = new List<byte>();
186184
while (true)//循环读
187185
{
@@ -200,19 +198,16 @@ private void ReadData()
200198
}
201199
catch { break; }//崩了?
202200

203-
if (result.Count > SerialportSetting.MaxLength)//长度超了
201+
if (result.Count > SerialportSetting.SendAndReceiveSettingModel.MaxLength)//长度超了
204202
break;
205-
206203
}
207-
204+
208205
if (result.Count > 0)
209206
{
210207
try
211208
{
212209
var r = result.ToArray();
213210
UartDataRecived(r, EventArgs.Empty);//回调事件
214-
215-
216211
}
217212
catch
218213
{ }

One.Toolbox/One.Toolbox.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
<SelfContained>false</SelfContained>
1010
<UseWPF>true</UseWPF>
1111
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
12-
<Version>2.8.3</Version>
12+
<Version>2.8.4</Version>
1313
<ImplicitUsings>enable</ImplicitUsings>
1414
<SatelliteResourceLanguages>zh-Hans;en-us</SatelliteResourceLanguages>
1515
<ApplicationIcon>Icon.ico</ApplicationIcon>

One.Toolbox/Resources/Languages/zh_CN.xaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@
8080
<system:String x:Key="SettingMs">毫秒(负数为不分包模式)</system:String>
8181
<system:String x:Key="SettingSplitByEmpty">超时时间表示空白间隔(不勾选表示从第一个字节开始算超时时间)</system:String>
8282
<system:String x:Key="SettingTerminal">终端模式(选中数据区域可直接敲键盘输出串口数据)</system:String>
83-
<system:String x:Key="SettingMaxPack">串口数据每包最大</system:String>
83+
<system:String x:Key="SettingMaxPack">数据每包最大</system:String>
8484
<system:String x:Key="SettingMaxShowPack">日志打印每最大显示长度限制</system:String>
8585
<system:String x:Key="SettingMaxShowPackWarn">!!数据过长自动截断显示,可前往设置更改长度限制!!</system:String>
8686
<system:String x:Key="SettingMaxPacksWarn">!!数据包过多自动清空,可前往设置更改此限制!!</system:String>
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
using One.Toolbox.ViewModels.Serialport;
2+
3+
namespace One.Toolbox.ViewModels.Base;
4+
5+
public partial class SendAndReceiveSettingVM : ObservableObject
6+
{
7+
[ObservableProperty]
8+
private bool hexShow;
9+
10+
[ObservableProperty]
11+
private bool hexSend;
12+
13+
[ObservableProperty]
14+
private bool withExtraEnter;
15+
16+
[ObservableProperty]
17+
private bool shortTimeInfo;
18+
19+
/// <summary> 替换不可见字符 </summary>
20+
public bool EnableSymbol { get; set; }
21+
22+
public int Timeout { get; set; }
23+
24+
public int MaxLength { get; set; }
25+
26+
public int MaxPacksAutoClear { get; set; }
27+
28+
public bool LagAutoClear { get; set; }
29+
30+
public List<QuickSendVM> QuickSendList { get; set; } = new List<QuickSendVM>();
31+
32+
public SendAndReceiveSettingVM()
33+
{
34+
//SerialportParams = new SerialportParams();
35+
}
36+
37+
public SendAndReceiveSettingModel ToModel()
38+
{
39+
SendAndReceiveSettingModel serialportSettingModel = new SendAndReceiveSettingModel();
40+
serialportSettingModel.HexShow = HexShow;
41+
serialportSettingModel.HexSend = HexSend;
42+
serialportSettingModel.WithExtraEnter = WithExtraEnter;
43+
serialportSettingModel.EnableSymbol = EnableSymbol;
44+
serialportSettingModel.Timeout = Timeout;
45+
serialportSettingModel.MaxLength = MaxLength;
46+
serialportSettingModel.MaxPacksAutoClear = MaxPacksAutoClear;
47+
serialportSettingModel.LagAutoClear = LagAutoClear;
48+
serialportSettingModel.QuickSendList = QuickSendList.Select(x => x.ToM()).ToList();
49+
serialportSettingModel.ShortTimeInfo = ShortTimeInfo;
50+
51+
return serialportSettingModel;
52+
}
53+
}
54+
55+
public class SendAndReceiveSettingModel
56+
{
57+
public bool HexShow { get; set; }
58+
public bool HexSend { get; set; }
59+
public bool WithExtraEnter { get; set; }
60+
61+
/// <summary> 替换不可见字符 </summary>
62+
public bool EnableSymbol { get; set; }
63+
64+
public int Timeout { get; set; } = 50;
65+
66+
public int MaxLength { get; set; } = 10240;
67+
68+
/// <summary> 自动清空UI,在超过此包数 </summary>
69+
public int MaxPacksAutoClear { get; set; } = 200;
70+
71+
public bool LagAutoClear { get; set; } = true;
72+
73+
public bool ShortTimeInfo { get; set; }
74+
75+
public List<QuickSendModel> QuickSendList { get; set; } = new List<QuickSendModel>();
76+
77+
public SendAndReceiveSettingVM ToVM()
78+
{
79+
SendAndReceiveSettingVM vm = new SendAndReceiveSettingVM();
80+
vm.HexShow = HexShow;
81+
vm.HexSend = HexSend;
82+
vm.WithExtraEnter = WithExtraEnter;
83+
vm.EnableSymbol = EnableSymbol;
84+
vm.Timeout = Timeout;
85+
vm.MaxLength = MaxLength;
86+
vm.MaxPacksAutoClear = MaxPacksAutoClear;
87+
vm.LagAutoClear = LagAutoClear;
88+
vm.QuickSendList = QuickSendList.Select(x => x.ToVM()).ToList();
89+
vm.ShortTimeInfo = ShortTimeInfo;
90+
91+
return vm;
92+
}
93+
}

0 commit comments

Comments
 (0)