UdpServer.cs
5.9 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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
using OnlineStore;
using DL.Utils;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace DL.Com
{
public class UdpServer
{
static readonly ILog log = LogManager.GetLogger(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 int serverPort;
private void logLocalIp()
{
string[] addresses = GetLocalAddresses();
string iplist = crc.GetString("Res0038","本机IP:[");
if (addresses.Length > 0)
{
for (int i = 0; i < addresses.Length; i++)
{
if (addresses.Length != 0)
{
iplist = iplist + " " + addresses[i];
}
}
}
LogUtil.Info(iplist + "]",log);
}
public UdpServer(int m_serverPort)
{
serverPort = m_serverPort;
}
/// <summary>
/// 开始服务
/// </summary>
public bool Start()
{
try
{
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 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;
return true;
}
catch (Exception ex)
{
LogUtil.Error("启动udpserver出错" ,log,ex);
}
return false;
}
/// <summary>
/// 停止服务
/// </summary>
public bool Stop()
{
try
{
isRun = false;
m_serverThread.Interrupt(); // 线程终止
udpServer.Close(); // Socket Close
return true;
}
catch (Exception ex)
{
LogUtil.Error("Stop Udpserver出错",log,ex);
}
return false;
}
private StringBuilder sb = new StringBuilder(); //这个是用来保存:接收到了的,但是还没有结束的消息
private int receiveBufferSize = 1024;
/// <summary>
/// 结束符
/// </summary>
public 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出错:" ,log,ex);
}
}
/// <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;
}
public bool IsOnline(string addr = "")
{
return isRun;
}
public string GetAddr()
{
return $"{string.Join(",",GetLocalAddresses())}:{serverPort}";
}
}
}