-
Notifications
You must be signed in to change notification settings - Fork 1
/
Messenger.cs
326 lines (302 loc) · 10.6 KB
/
Messenger.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SocketSingleSend
{
class Messenger
{
class StateObject
{
public Socket workSocket;
public byte[] dataByte;
public IPEndPoint ipe;
}
public const int MAX_BYTE_SIZE = 512;
public const int MIN_BYTE_SIZE = 64;
public const int BROADCAST_INTERVAL = 3000;
private Socket socket;
public Messenger(bool udpMode)
{
if (udpMode)
{
//UDP Mdoe
socket = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp)
{
SendTimeout = 800
};
}
}
public Messenger(bool udpMode, EndPoint bindIPE, int receiveTimeout = 0)
:this(udpMode)
{
socket.Bind(bindIPE);
if (receiveTimeout != 0)
socket.ReceiveTimeout = receiveTimeout;
}
public void Close()
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
#region UtilMethod
public static byte[] ConcatByte(byte[] frontByte, byte[] laterByte)
{
byte[] allByte = new byte[frontByte.Length + laterByte.Length];
frontByte.CopyTo(allByte, 0);
laterByte.CopyTo(allByte, frontByte.Length);
return allByte;
}
public static byte[] SubByte(byte[] dataByte, int startIndex, int count)
{
byte[] partByte = new byte[count];
Array.Copy(dataByte, startIndex, partByte, 0, count);
return partByte;
}
public static byte[] SplitByte(byte[] dataByte, int splitPoint, out byte[] laterByte)
{
//return the front part
laterByte = SubByte(dataByte, splitPoint, dataByte.Length - splitPoint);
return SubByte(dataByte, 0, splitPoint);
}
#endregion
public bool UDPSend(byte[] strByte, EndPoint targetIPE, bool firstSend = true)
{
bool overMax = false;
byte[] remainByte = null;
if (strByte.Length >= MAX_BYTE_SIZE)
{
overMax = true;
if (firstSend)
{
//add byteLength to head
int totalLen = strByte.Length;
strByte = ConcatByte(CryptoUtil.IntToByte(totalLen), strByte);
#if DEBUG
Console.WriteLine("--------concat {0} Byte, ready to send first part...",
totalLen);
#endif
}
//get the front part(MAX_BYTE_SIZE) to send and save the later part
strByte = SplitByte(strByte, MAX_BYTE_SIZE, out remainByte);
}
try
{
int sendLen = socket.SendTo(strByte, SocketFlags.None, targetIPE);
if (sendLen == strByte.Length)
{
#if DEBUG
Console.WriteLine("--------success to send {0} Byte, overMax: {1}",
sendLen, overMax);
#endif
if (overMax && remainByte.Length != 0)
return UDPSend(remainByte, targetIPE, false);
else
return true;
}
}
catch (SocketException ex)
{
#if DEBUG
Console.WriteLine(ex.Message + " errorCode: " + ex.ErrorCode);
#endif
}
return false;
}
public bool UDPSend(string str, EndPoint targetIPE)
{
//Encrypt here
return UDPSend(CryptoUtil.StrToByte(CryptoUtil.Encrypt(str)), targetIPE);
}
public bool SteadySend(string str, EndPoint targetIPE)
{
int count = 3;
while (count > 0)
{
count--;
if (UDPSend(str, targetIPE))
return true;
}
return false;
}
private void BroadcastCallback(IAsyncResult ar)
{
StateObject stateObj = (StateObject)ar.AsyncState;
try
{
int sendLen = stateObj.workSocket.EndSendTo(ar);
#if DEBUG
Console.WriteLine("<<<<<<<<send one broadcast");
#endif
if (sendLen == stateObj.dataByte.Length)
Thread.Sleep(BROADCAST_INTERVAL);
stateObj.workSocket.BeginSendTo(stateObj.dataByte, 0, stateObj.dataByte.Length,
SocketFlags.None, stateObj.ipe, BroadcastCallback, stateObj);
}
catch (SocketException ex)
{
#if DEBUG
Console.WriteLine(ex.Message + " errorCode: " + ex.ErrorCode);
#endif
}
}
public void Broadcasting(string bcStr, int bc_port)
{
if (!socket.EnableBroadcast)
socket.EnableBroadcast = true;
byte[] bcByte = CryptoUtil.StrToByte(CryptoUtil.Encrypt(bcStr));
IPEndPoint bcIPE = new IPEndPoint(IPAddress.Broadcast, bc_port);
StateObject stateObj = new StateObject()
{
dataByte = bcByte,
ipe = bcIPE,
workSocket = socket
};
try
{
socket.BeginSendTo(bcByte, 0, bcByte.Length, SocketFlags.None,
bcIPE, new AsyncCallback(BroadcastCallback), stateObj);
}
catch (SocketException ex)
{
#if DEBUG
Console.WriteLine(ex.Message + " errorCode: " + ex.ErrorCode);
#endif
}
}
public byte[] UDPReceive(ref EndPoint remoteIPE, int byteSize)
{
int remainLen = 0;
if (byteSize > MAX_BYTE_SIZE)
{
remainLen = byteSize - MAX_BYTE_SIZE;
byteSize = MAX_BYTE_SIZE;
}
try
{
byte[] strByte = new byte[byteSize];
int strLen = socket.ReceiveFrom(strByte,
SocketFlags.None, ref remoteIPE);
#if DEBUG
Console.WriteLine("--------get one part with length: {0}", strLen);
#endif
if (strLen > 0)
{
strByte = SubByte(strByte, 0, strLen);
if (remainLen != 0)
{
//continue to receive and concat the remainder byte
IPAddress beforeIP = ((IPEndPoint)remoteIPE).Address;
byte[] remainByte = UDPReceive(ref remoteIPE, remainLen);
IPAddress afterIP = ((IPEndPoint)remoteIPE).Address;
if (!beforeIP.Equals(afterIP))
throw new Exception(
"Information confusion between different senders");
else
strByte = ConcatByte(strByte, remainByte);
}
return strByte;
}
}
catch (SocketException ex)
{
#if DEBUG
Console.WriteLine(ex.Message + " errorCode: " + ex.ErrorCode);
#endif
}
return null;
}
public string UDPReceive(ref EndPoint remoteIPE)
{
byte[] receiveByte = UDPReceive(ref remoteIPE, MAX_BYTE_SIZE);
if (receiveByte != null && receiveByte.Length == MAX_BYTE_SIZE)
{
//get byteLength from the head
int totalLen = CryptoUtil.ByteToInt(receiveByte);
receiveByte = SubByte(receiveByte, 4, receiveByte.Length - 4);
#if DEBUG
Console.WriteLine("--------totalLength should be: {0}", totalLen);
#endif
//continue to receive
IPAddress beforeIP = ((IPEndPoint)remoteIPE).Address;
byte[] remainByte = UDPReceive(ref remoteIPE, totalLen - receiveByte.Length);
IPAddress afterIP = ((IPEndPoint)remoteIPE).Address;
if (remainByte != null && beforeIP.Equals(afterIP))
{
//concat the remainder byte
receiveByte = ConcatByte(receiveByte, remainByte);
#if DEBUG
Console.WriteLine("--------success receive {0} Byte from: {1}",
receiveByte.Length, remoteIPE);
#endif
}
else
receiveByte = null;
}
if (receiveByte != null)
{
//Decrypt here
string msg = CryptoUtil.Decrypt(CryptoUtil.ByteToStr(receiveByte));
#if DEBUG
Console.WriteLine(">>>>>>>>get '{0}' from: {1}", msg, remoteIPE);
#endif
return msg;
}
return null;
}
public string ReceiveLastOne(ref EndPoint remoteIPE)
{
//wait to get the last Msg from the Receive Buffer
string msg = null;
do
{
msg = UDPReceive(ref remoteIPE);
} while (socket.Available != 0);
return msg;
}
public void FlushReceiveBuf()
{
//this method will only be invoked before receiving a answer
EndPoint remoteIPE = new IPEndPoint(IPAddress.Any, 0);
//clean up the Receive Buffer
while (socket.Available != 0)
{
UDPReceive(ref remoteIPE);
}
}
public string ReceiveBroadcast(ref EndPoint remoteIPE)
{
if (!socket.EnableBroadcast)
socket.EnableBroadcast = true;
try
{
int byteSize = (MAX_BYTE_SIZE < MIN_BYTE_SIZE) ? MIN_BYTE_SIZE : MAX_BYTE_SIZE;
byte[] receiveByte = new byte[byteSize];
int receiveLen = socket.ReceiveFrom(receiveByte,
SocketFlags.None, ref remoteIPE);
if (receiveLen > 0)
{
string bcMsg = CryptoUtil.Decrypt(CryptoUtil.ByteToStr(
receiveByte, receiveLen));
#if DEBUG
Console.WriteLine(">>>>>>>>get broadcast '{0}' from: {1}",
bcMsg, remoteIPE);
#endif
return bcMsg;
}
}
catch (SocketException ex)
{
#if DEBUG
Console.WriteLine(ex.Message + " errorCode: " + ex.ErrorCode);
#endif
}
return null;
}
}
}