一直使用UDP,觉得它的优点还是很明显的,不需要连接,速度很快。近来做一个项目,需要把它编译为Windows服务,因为程序是多线程的,而在服务中调试多线程的程序十分的麻烦,因此做了这个通用UDP。
比较好的一方面是发送的时候一个Send()函数就可以了。还有就是发送的时候有range参数,只需要修改这个参数就可以控制发送消息到不同的网段,如果都是255,所有的机器都可以收到了。
希望对大家有帮助









































































接收端:
1
using System;
2
using System.Net;
3
using System.Net.Sockets;
4
using System.Text;
5
using System.Threading;
6
using System.Diagnostics;
7
using UDPComm;
8
9
namespace UdpServer
10
{
11
/// <summary>
12
/// Summary description for Class1.
13
/// </summary>
14
class Char
15
{
16
[STAThread]
17
static void Main(string[] args)
18
{
19
try
20
{
21
Thread tRec = new Thread(new ThreadStart(UDPComm.UDP.Receiver));
22
tRec.Start();
23
UDP.UDPMsgArrived += new UDP.dlg_UDPMsgHandler(UDP_UDPMsgArrived);
24
}
25
catch (Exception ex)
26
{
27
Console.WriteLine(ex.ToString());
28
}
29
}
30
31
static void UDP_UDPMsgArrived(string receivebytes)
32
{
33
Console.WriteLine(System.DateTime.Now.ToShortTimeString()+" "+receivebytes);
34
}
35
}
36
}
37
38

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

发送端:
1
using System;
2
using System.Net;
3
using System.Net.Sockets;
4
using System.Text;
5
using System.Threading;
6
using System.Diagnostics;
7
using UDPComm;
8
9
namespace UdpServer
10
{
11
class ClientSend
12
{
13
[STAThread]
14
static void Main(string[] args)
15
{
16
try
17
{
18
Thread tSend = new Thread(new ThreadStart(s));
19
tSend.Start();
20
Console.ReadLine();
21
}
22
catch (Exception ex)
23
{
24
Console.WriteLine(ex.ToString());
25
}
26
}
27
private static void s()
28
{
29
string D = ((char)22).ToString();
30
string F = ((char)3).ToString();
31
string S = ((char)16).ToString();
32
33
for (int i=0;i<1000;i++)
34
{
35
Console.WriteLine(i.ToString());
36
UDPComm.UDP.Send("127.255.255.255", "IVIP1"+D+"250"+S+"301"+S+System.DateTime.Now.ToString("yyyyMMdd")+S+System.DateTime.Now.ToString("HHmmss")+S+"1"+S+i.ToString().PadLeft(15));
37
Thread.Sleep(1000);
38
}
39
//How to end the UDP receive thread
40
UDPComm.UDP.Send("127.255.255.255", F);
41
}
42
}
43
}
44
45

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
