1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
using FlyAd2021.Inc;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace FlyAd2021
{
/// <summary>
/// AD盒2021版,通讯模块,只负责 调用 核心模块 的Rec, Send
/// </summary>
public class FlyAd2021Comm_TcpClient : IFlyAd2021Comm
{
/// <summary>
/// IP 地址 and 端口号
/// </summary>
public string Addr { get; set; }
IPEndPoint RemoteEp => Misc.StringConverter.ToIPEndPoint(Addr);
/// <summary>
/// 是否异常
/// </summary>
public bool IsError => !string.IsNullOrEmpty(ErrMsg);
/// <summary>
/// 异常信息
/// </summary>
public string ErrMsg { get; private set; }
/// <summary>
/// 运行中
/// </summary>
public bool IsRunning { get; private set; }
/// <summary>
/// 连接成功
/// </summary>
public bool IsConnected { get; private set; }
/// <summary>
/// 接收task调用
/// </summary>
public event Action<byte[]> RecMsg;
public event PropertyChangedEventHandler PropertyChanged;
Socket sock;
CancellationTokenSource cancellation;
CancellationTokenSource cancellation_waitforSend;
public FlyAd2021Comm_TcpClient()
{
}
/// <summary>
/// 开始
/// </summary>
public void Start()
{
if (IsRunning)
return;
IsRunning = true;
cancellation = new CancellationTokenSource();
Task.Factory.StartNew(OnTask, cancellation.Token);
}
/// <summary>
/// 接收
/// </summary>
public void Stop()
{
if (!IsRunning)
return;
IsRunning = false;
cancellation.Cancel();
if (sock != null && sock.Connected)
{
sock.Close();
sock = null;
}
}
void OnTask()
{
while (!cancellation.IsCancellationRequested)
{
ConnectTask();
if (IsConnected)
{
sendBuf.Clear();
//启动发送task
Task.Factory.StartNew(SendTask, cancellation.Token);
//进入接收task
ReceiveTask();
//退出了,肯定连接断开了
}
//休息一会儿,在重连
try
{
Task.Delay(2000, cancellation.Token).Wait();
}
catch (Exception e)
{
//被打断了
break;
}
}
IsConnected = false;
}
/// <summary>
/// 连接任务
/// </summary>
void ConnectTask()
{
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Blocking = true;
//1秒内,需要收到信息
sock.ReceiveTimeout = 1000;
//1秒内,必须发送完
sock.SendTimeout = 1000;
while (!cancellation.IsCancellationRequested)
{
try
{
sock.Connect(RemoteEp);
IsConnected = true;
ErrMsg = null;
return;
}
catch (SocketException e)
{
//连接出错
//等待重试
ErrMsg = e.Message;
}
try
{
Task.Delay(2000, cancellation.Token).Wait();
}
catch (Exception e)
{
//被打断
return;
}
}
}
/// <summary>
/// 接收任务
/// </summary>
void ReceiveTask()
{
byte[] buf = new byte[0x10000];
while (!cancellation.IsCancellationRequested)
{
int len;
try
{
len = sock.Receive(buf);
if (len == 0)
{
continue;//没收到数据,继续等
}
}
catch (SocketException e)
{
if (e.SocketErrorCode == SocketError.TimedOut)
continue;//超时而已
else if ((e.SocketErrorCode == SocketError.ConnectionAborted)
|| (e.SocketErrorCode == SocketError.ConnectionRefused)
|| (e.SocketErrorCode == SocketError.ConnectionReset))
{
IsConnected = false;
return;
}
//Console.WriteLine($"ReceiveTask() {e}");
//肯定断开连接了
IsConnected = false;
break;
}
RecMsg?.Invoke(buf.Take(len).ToArray());
}
if (sock != null)
{
sock.Close();
}
IsConnected = false;
}
/// <summary>
/// 发送任务
/// </summary>
void SendTask()
{
while (!cancellation.IsCancellationRequested)
{
while (sendBuf.Count > 0)
{
int slen;
try
{
slen = sock.Send(sendBuf.ToArray());
}
catch (Exception e)
{
//连接断开了
IsConnected = false;
break;
}
if (slen > 0)
sendBuf.RemoveRange(0, slen);
else if (slen <= 0)
{
//连接断开了
IsConnected = false;
break;
}
}
//重新等 下次被呼醒
cancellation_waitforSend = new CancellationTokenSource();
try
{
Task.Delay(-1, cancellation_waitforSend.Token).Wait();
}
catch (Exception e)
{
//被打断, 有数据需要发送
}
}
}
/// <summary>
/// 无限大,发送缓存
/// </summary>
List<byte> sendBuf = new List<byte>();
/// <summary>
/// 发送数据
/// </summary>
/// <param name="msg"></param>
public void SendMsg(byte[] msg)
{
if (!IsConnected)
return;
//放入,发送缓存区
sendBuf.AddRange(msg);
//呼醒 发送task
cancellation_waitforSend.Cancel();
}
}
}