TcpServer.cs
9.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
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
using OnlineStore;
using System;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections.Concurrent;
namespace OnlineStore.Common
{
public class TcpServer
{
// public static readonly ILog LOGGER = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// 接受消息时的间隔
/// </summary>
public static int ReviceMsgMS = 10;
private Thread m_serverThread;
private Socket m_serverSocket;
public delegate void ReviceMsg(TcpClientBean client, string Msg);
public event ReviceMsg ReviceMsgEvent;
private delegate void ReceiveMessageDelegate(TcpClientBean client);
public event AcceptClientDelegate AcceptClientEvent;
public delegate void AcceptClientDelegate(TcpClientBean client);
ReceiveMessageDelegate receiveMessageDelegate;
private bool isRun = true;
private int serverPort = 0;
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
{
isRun = true;
m_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, m_serverPort);
this.serverPort = m_serverPort;
m_serverSocket.Bind(localEndPoint);
m_serverSocket.Listen(10);
m_serverThread = new Thread(new ThreadStart(ReceiveAccept));
m_serverThread.Start();
LogUtil.info( " Server start listen : " + m_serverPort);
logLocalIp();
//this.AddRunningInfo(">> " + DateTime.Now.ToString() + " Server started.");
}
catch (SocketException se)
{
throw new Exception(se.Message);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 停止服务
/// </summary>
public void Stop()
{
try
{
isRun = false;
m_serverThread.Interrupt(); // 线程终止
m_serverSocket.Close(); // Socket Close
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private void ReceiveAccept()
{
while (isRun)
{
TcpClientBean client = new TcpClientBean();
try
{
client.ClientSocket = m_serverSocket.Accept();
IPEndPoint clientipe = (IPEndPoint)client.ClientSocket.RemoteEndPoint;
client.AddStr = clientipe.Address.ToString()+":"+clientipe.Port.ToString();
LogUtil.info( "["+serverPort+"]有新的客户端链接上:[" + client.AddStr+"]");
AcceptClientEvent?.Invoke(client);
receiveMessageDelegate = new ReceiveMessageDelegate(ReceiveMessages);
receiveMessageDelegate.BeginInvoke(client, ReceiveMessagesCallback, "");
}
catch (Exception ex)
{
LogUtil.error( "ReceiveAccept方法,客户端【"+client.AddStr+"】:" + ex.Message);
//throw new Exception(ex.Message);
}
}
}
// private StringBuilder sb = new StringBuilder(); //这个是用来保存:接收到了的,但是还没有结束的消息
private int receiveBufferSize = 1024;
private string terminateString = "\r";
public void ReceiveMessages(TcpClientBean client) //这个函数会被以线程方式运行
{
try
{
StringBuilder sb = new StringBuilder();
Socket socket = (Socket)client.ClientSocket;
while (true)
{
byte[] buffer = new byte[receiveBufferSize]; //buffer大小,此处为1024
int receivedSize = socket.Receive(buffer);
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(client, sb.ToString());//找到了消息结束符,触发消息接收完成事件
sb = new StringBuilder();
i += rnFixLength;
}
}
else
{
sb.Append(rawMsg[i]);
i++;
}
}
}
Thread.Sleep(ReviceMsgMS);
}
}
catch (SocketException e)
{
LogUtil.error("客户端{" + client.AddStr + "]:" + e.ToString(), 106);
}
catch (Exception ex)
{
LogUtil.error("客户端{" + client.AddStr + "]:" + ex.ToString(), 105);
}
}
//private void ReceiveMessages(Client client)
//{
// try
// {
// while (true)
// {
// byte[] receiveBuffer = new byte[1024];
// //int size = ;
// int size = client.ClientSocket.Receive(receiveBuffer);
// string strReceiveData = Encoding.ASCII.GetString(receiveBuffer, 0, size);
// if (!string.IsNullOrEmpty(strReceiveData))
// {
// LogUtil.info(LOGGER, "收到数据:" + strReceiveData);
// // this.AddRunningInfo(">> Receive data from [" + client.ClientSocket.RemoteEndPoint.ToString()+ "]:" + strReceiveData);
// string strSendData = "OK. The content is:" + strReceiveData;
// //LogUtil.info(LOGGER, "OK. The content is:" + strReceiveData);
// int sendBufferSize = Encoding.Unicode.GetByteCount(strSendData);
// byte[] sendBuffer = new byte[sendBufferSize];
// sendBuffer = Encoding.Unicode.GetBytes(strSendData);
// client.ClientSocket.Send(sendBuffer);
// }
// }
// }
// catch (SocketException e)
// {
// LogUtil.error(LOGGER, e.ToString());
// }
// catch (Exception ex)
// {
// LOGGER.Error(ex.ToString());
// }
//}
private void ReceiveMessagesCallback(IAsyncResult AR)
{
try
{
receiveMessageDelegate.EndInvoke(AR);
}
catch (Exception ex)
{
LogUtil.error(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;
}
}
/// <summary>
/// 客户端会话信息类
/// </summary>
public class TcpClientBean
{
Socket m_clientSocket;
public TcpClientBean() { }
public string AddStr = "";
public Socket ClientSocket
{
get { return m_clientSocket; }
set { this.m_clientSocket = value; }
}
}
}