UdpServer.cs
5.4 KB
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
using OnlineStore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace OnlineStore.Common
{
public class UdpServer
{
// public static readonly ILog LOGGER = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private Thread m_serverThread;
private Socket udpServer;
public delegate void ReviceMsg(EndPoint address, string Msg);
/// <summary>
/// 接受到数据事件
/// </summary>
public event ReviceMsg ReviceMsgEvent;
private bool isRun = true;
private void logLocalIp()
{
string[] addresses = GetLocalAddresses();
string iplist = $"本机IP"+":[";
if (addresses.Length > 0)
{
for (int i = 0; i < addresses.Length; i++)
{
if (addresses.Length != 0)
{
iplist = iplist + " " + addresses[i];
}
}
}
LogUtil.info( iplist + "]");
}
/// <summary>
/// 开始服务
/// </summary>
public void Start(int m_serverPort)
{
try
{
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, m_serverPort);//定义一网络端点
udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//定义一个Socket
udpServer.Bind(ipep);//Socket与本地的一个终结点相关联
m_serverThread = new Thread(new ThreadStart(ReceiveData));
m_serverThread.Start();
logLocalIp();
isRun = true;
}
catch (Exception ex)
{
LogUtil.error("启动udpserver出错:" + ex.ToString());
}
}
/// <summary>
/// 停止服务
/// </summary>
public void Stop()
{
try
{
isRun = false;
m_serverThread.Interrupt(); // 线程终止
udpServer.Close(); // Socket Close
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private StringBuilder sb = new StringBuilder(); //这个是用来保存:接收到了的,但是还没有结束的消息
private int receiveBufferSize = 1024;
private string terminateString = "\r";
private void ReceiveData()
{
try
{
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);//定义要发送的计算机的地址
EndPoint Remote = (EndPoint)(sender);//
while (true)
{
byte[] buffer = new byte[receiveBufferSize];
int receivedSize = udpServer.ReceiveFrom(buffer, ref Remote);
if (receivedSize > 0)
{
string rawMsg = Encoding.ASCII.GetString(buffer, 0, receivedSize);
int rnFixLength = terminateString.Length; //这个是指消息结束符的长度,此处为\r\n
for (int i = 0; i < rawMsg.Length; ) //遍历接收到的整个buffer文本
{
if (i <= rawMsg.Length - rnFixLength)
{
if (rawMsg.Substring(i, rnFixLength) != terminateString)//非消息结束符,则加入sb
{
sb.Append(rawMsg[i]);
i++;
}
else
{
this.ReviceMsgEvent.Invoke(Remote, sb.ToString());//找到了消息结束符,触发消息接收完成事件
sb = new StringBuilder();
i += rnFixLength;
}
}
else
{
sb.Append(rawMsg[i]);
i++;
}
}
}
Thread.Sleep(500);
}
}
catch (Exception ex)
{
LogUtil.error("启动udpserver出错:" + ex.ToString());
}
}
/// <summary>
/// 获取本机地址列表
/// </summary>
public string[] GetLocalAddresses()
{
// 获取主机名
string strHostName = Dns.GetHostName();
// 根据主机名进行查找
IPHostEntry iphostentry = Dns.GetHostEntry(strHostName);
string[] retval = new string[iphostentry.AddressList.Length];
int i = 0;
foreach (IPAddress ipaddress in iphostentry.AddressList)
{
if (ipaddress.AddressFamily != AddressFamily.InterNetworkV6)
{
retval[i] = ipaddress.ToString();
i++;
}
}
return retval;
}
}
}