wxr
2024-12-02 ea0b1e8e5f43c5fd0a7d479e25ede3b8cbea464a
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
 
namespace HDL_ON.DAL.DriverLayer
{
    //class AsyncUdpServer
    /// <summary>
    /// UdpClient 实现异步UDP服务器
    /// </summary>
    public class AsyncUdpServer
    {
        #region Fields
        /// <summary>
        /// 服务器程序允许的最大客户端连接数
        /// </summary>
        private int _maxClient;
 
        /// <summary>
        /// 当前的连接的客户端数
        /// </summary>
        //private int _clientCount;
 
        /// <summary>
        /// 服务器使用的异步UdpClient
        /// </summary>
        private UdpClient _server;
 
        /// <summary>
        /// 客户端会话列表
        /// </summary>
        //private List<AsyncUDPState> _clients;
 
        private bool disposed = false;
 
        /// <summary>
        /// 数据接受缓冲区
        /// </summary>
        private byte[] _recvBuffer;
 
        #endregion
 
        #region Properties
 
        /// <summary>
        /// 服务器是否正在运行
        /// </summary>
        public bool IsRunning { get; private set; }
        /// <summary>
        /// 监听的IP地址
        /// </summary>
        public IPAddress Address { get; private set; }
        /// <summary>
        /// 监听的端口
        /// </summary>
        public int Port { get; private set; }
        /// <summary>
        /// 通信使用的编码
        /// </summary>
        public Encoding Encoding { get; set; }
 
        #endregion
 
        #region 构造函数
 
        /// <summary>
        /// 异步UdpClient UDP服务器
        /// </summary>
        /// <param name="listenPort">监听的端口</param>
        public AsyncUdpServer(int listenPort)
            : this(IPAddress.Any, listenPort, 10240)
        {
        }
 
        /// <summary>
        /// 异步UdpClient UDP服务器
        /// </summary>
        /// <param name="localEP">监听的终结点</param>
        public AsyncUdpServer(IPEndPoint localEP)
            : this(localEP.Address, localEP.Port, 10240)
        {
        }
 
        /// <summary>
        /// 异步UdpClient UDP服务器
        /// </summary>
        /// <param name="localIPAddress">监听的IP地址</param>
        /// <param name="listenPort">监听的端口</param>
        /// <param name="maxClient">最大客户端数量</param>
        public AsyncUdpServer(IPAddress localIPAddress, int listenPort, int maxClient)
        {
            this.Address = localIPAddress;
            this.Port = listenPort;
            this.Encoding = Encoding.Default;
 
            _maxClient = maxClient;
            //_clients = new List<AsyncUDPSocketState>();
            _server = new UdpClient(new IPEndPoint(this.Address, this.Port));
            uint IOC_IN = 0x80000000;
            uint IOC_VENDOR = 0x18000000;
            uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
 
            _server.Client.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);
 
            _recvBuffer = new byte[_server.Client.ReceiveBufferSize];
        }
 
        #endregion
 
        #region Method
        /// <summary>
        /// 启动服务器
        /// </summary>
        /// <returns>异步TCP服务器</returns>
        public void Start()
        {
            try
            {
                if (!IsRunning)
                {
                    IsRunning = true;
                    _server.EnableBroadcast = true;
                    _server.BeginReceive(ReceiveDataAsync, null);
                }
            }
            catch (Exception e) { }
        }
 
        /// <summary>
        /// 停止服务器
        /// </summary>
        public void Stop()
        {
            try
            {
                //if (IsRunning)
                {
                    IsRunning = false;
                    _server.Close();
                    //TODO 关闭对所有客户端的连接
 
                }
            }
            catch (Exception e) { }
        }
 
        /// <summary>
        /// 接收数据的方法
        /// </summary>
        /// <param name="ar"></param>
        private void ReceiveDataAsync(IAsyncResult ar)
        {
            bool isReceive = false;
            try
            {
                var udpState = new AsyncUDPState();
                IPEndPoint remote = null;
                udpState.buffer = _server.EndReceive(ar, ref remote); ;
                udpState.remote = remote;
                udpState.udpClient = _server;
 
                isReceive = true;
                receive();
 
                //触发数据收到事件
                RaiseDataReceived(udpState);
            }
            catch (Exception)
            {
                //TODO 处理异常
                RaiseOtherException(null);
            }
            finally
            {
                if (!isReceive)
                {
                    receive();
                }
            }
        }
 
        void receive()
        {
            if (IsRunning && _server != null)
            {
                int count = 10;
                while (0 < count--)
                {
                    try
                    {
                        _server.BeginReceive(ReceiveDataAsync, null);
                        break;
                    }
                    catch (Exception e)
                    {
                        System.Threading.Thread.Sleep(100);
                    }
                }
            }
 
        }
 
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="remote"></param>
        public void Send(byte[] data, IPEndPoint remote)
        {
            try
            {
                RaisePrepareSend(null);
                _server.BeginSend(data, data.Length, remote, new AsyncCallback(SendCallback), null);
            }
            catch (Exception)
            {
                //TODO 异常处理
                RaiseOtherException(null);
            }
        }
 
        private void SendCallback(IAsyncResult ar)
        {
            //if (ar.IsCompleted)
            {
                try
                {
                    _server.EndSend(ar);
                    //消息发送完毕事件
                    RaiseCompletedSend(null);
                }
                catch (Exception)
                {
                    //TODO 数据发送失败事件
                    RaiseOtherException(null);
                }
            }
 
        }
        #endregion
 
        #region 事件
        /// <summary>
        /// 接收到数据事件
        /// </summary>
        public event EventHandler<AsyncUDPEventArgs> DataReceived;
 
        private void RaiseDataReceived(AsyncUDPState state)
        {
            if (DataReceived != null)
            {
                DataReceived(this, new AsyncUDPEventArgs(state));
            }
        }
 
        /// <summary>
        /// 发送数据前的事件
        /// </summary>
        public event EventHandler<AsyncUDPEventArgs> PrepareSend;
 
        /// <summary>
        /// 触发发送数据前的事件
        /// </summary>
        /// <param name="state"></param>
        private void RaisePrepareSend(AsyncUDPState state)
        {
            if (PrepareSend != null)
            {
                PrepareSend(this, new AsyncUDPEventArgs(state));
            }
        }
 
        /// <summary>
        /// 数据发送完毕事件
        /// </summary>
        public event EventHandler<AsyncUDPEventArgs> CompletedSend;
 
        /// <summary>
        /// 触发数据发送完毕的事件
        /// </summary>
        /// <param name="state"></param>
        private void RaiseCompletedSend(AsyncUDPState state)
        {
            if (CompletedSend != null)
            {
                CompletedSend(this, new AsyncUDPEventArgs(state));
            }
        }
 
        /// <summary>
        /// 网络错误事件
        /// </summary>
        public event EventHandler<AsyncUDPEventArgs> NetError;
        /// <summary>
        /// 触发网络错误事件
        /// </summary>
        /// <param name="state"></param>
        private void RaiseNetError(AsyncUDPState state)
        {
            if (NetError != null)
            {
                NetError(this, new AsyncUDPEventArgs(state));
            }
        }
 
        /// <summary>
        /// 异常事件
        /// </summary>
        public event EventHandler<AsyncUDPEventArgs> OtherException;
        /// <summary>
        /// 触发异常事件
        /// </summary>
        /// <param name="state"></param>
        private void RaiseOtherException(AsyncUDPState state, string descrip)
        {
            if (OtherException != null)
            {
                OtherException(this, new AsyncUDPEventArgs(descrip, state));
            }
        }
        private void RaiseOtherException(AsyncUDPState state)
        {
            RaiseOtherException(state, "");
        }
        #endregion
 
        #region Close
        /// <summary>
        /// 关闭一个与客户端之间的会话
        /// </summary>
        /// <param name="state">需要关闭的客户端会话对象</param>
        public void Close(AsyncUDPState state)
        {
            if (state != null)
            {
                //_clients.Remove(state);
                //_clientCount--;
                //TODO 触发关闭事件
            }
        }
        /// <summary>
        /// 关闭所有的客户端会话,与所有的客户端连接会断开
        /// </summary>
        public void CloseAllClient()
        {
            //foreach (AsyncUDPSocketState client in _clients)
            //{
            //    Close(client);
            //}
            //_clientCount = 0;
            //_clients.Clear();
        }
 
        #endregion
 
        #region 释放
        /// <summary>
        /// Performs application-defined tasks associated with freeing, 
        /// releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
 
        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release 
        /// both managed and unmanaged resources; <c>false</c> 
        /// to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    try
                    {
                        Stop();
                        if (_server != null)
                        {
                            _server = null;
                        }
                    }
                    catch (SocketException)
                    {
                        //TODO
                        RaiseOtherException(null);
                    }
                }
                disposed = true;
            }
        }
        #endregion
    }
}
public class AsyncUDPState
{
    // Client   socket.
    public UdpClient udpClient = null;
    // Size of receive buffer.
    public const int BufferSize = 1024;
    // Receive buffer.
    public byte[] buffer = new byte[BufferSize];
    // Received data string.
    public StringBuilder sb = new StringBuilder();
 
    public IPEndPoint remote = new IPEndPoint(IPAddress.Any, 0);
}
/// <summary>
/// UdpClient 异步UDP服务器事件参数类
/// </summary>
public class AsyncUDPEventArgs : EventArgs
{
    /// <summary>
    /// 提示信息
    /// </summary>
    public string _msg;
 
    /// <summary>
    /// 客户端状态封装类
    /// </summary>
    public AsyncUDPState _state;
 
    /// <summary>
    /// 是否已经处理过了
    /// </summary>
    public bool IsHandled { get; set; }
 
    public AsyncUDPEventArgs(string msg)
    {
        this._msg = msg;
        IsHandled = false;
    }
    public AsyncUDPEventArgs(AsyncUDPState state)
    {
        this._state = state;
        IsHandled = false;
    }
    public AsyncUDPEventArgs(string msg, AsyncUDPState state)
    {
        this._msg = msg;
        this._state = state;
        IsHandled = false;
    }
 
}