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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
|
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace Hazel.Udp
{
/// <summary>
/// Represents a client's connection to a server that uses the UDP protocol.
/// </summary>
/// <inheritdoc/>
public sealed class UdpClientConnection : UdpConnection
{
/// <summary>
/// The max size Hazel attempts to read from the network.
/// Defaults to 8096.
/// </summary>
/// <remarks>
/// 8096 is 5 times the standard modern MTU of 1500, so it's already too large imo.
/// If Hazel ever implements fragmented packets, then we might consider a larger value since combining 5
/// packets into 1 reader would be realistic and would cause reallocations. That said, Hazel is not meant
/// for transferring large contiguous blocks of data, so... please don't?
/// </remarks>
public int ReceiveBufferSize = 8096;
/// <summary>
/// The socket we're connected via.
/// </summary>
private Socket socket;
/// <summary>
/// Reset event that is triggered when the connection is marked Connected.
/// </summary>
private ManualResetEvent connectWaitLock = new ManualResetEvent(false);
private Timer reliablePacketTimer;
#if DEBUG
public event Action<byte[], int> DataSentRaw;
public event Action<byte[], int> DataReceivedRaw;
#endif
/// <summary>
/// Creates a new UdpClientConnection.
/// </summary>
/// <param name="remoteEndPoint">A <see cref="NetworkEndPoint"/> to connect to.</param>
public UdpClientConnection(ILogger logger, IPEndPoint remoteEndPoint, IPMode ipMode = IPMode.IPv4)
: base(logger)
{
this.EndPoint = remoteEndPoint;
this.IPMode = ipMode;
this.socket = CreateSocket(ipMode);
reliablePacketTimer = new Timer(ManageReliablePacketsInternal, null, 100, Timeout.Infinite);
this.InitializeKeepAliveTimer();
}
~UdpClientConnection()
{
this.Dispose(false);
}
private void ManageReliablePacketsInternal(object state)
{
base.ManageReliablePackets();
try
{
reliablePacketTimer.Change(100, Timeout.Infinite);
}
catch { }
}
/// <inheritdoc />
protected override void WriteBytesToConnection(byte[] bytes, int length)
{
#if DEBUG
if (TestLagMs > 0)
{
ThreadPool.QueueUserWorkItem(a => { Thread.Sleep(this.TestLagMs); WriteBytesToConnectionReal(bytes, length); });
}
else
#endif
{
WriteBytesToConnectionReal(bytes, length);
}
}
private void WriteBytesToConnectionReal(byte[] bytes, int length)
{
#if DEBUG
DataSentRaw?.Invoke(bytes, length);
#endif
try
{
this.Statistics.LogPacketSend(length);
socket.BeginSendTo(
bytes,
0,
length,
SocketFlags.None,
EndPoint,
HandleSendTo,
null);
}
catch (NullReferenceException) { }
catch (ObjectDisposedException)
{
// Already disposed and disconnected...
}
catch (SocketException ex)
{
DisconnectInternal(HazelInternalErrors.SocketExceptionSend, "Could not send data as a SocketException occurred: " + ex.Message);
}
}
private void HandleSendTo(IAsyncResult result)
{
try
{
socket.EndSendTo(result);
}
catch (NullReferenceException) { }
catch (ObjectDisposedException)
{
// Already disposed and disconnected...
}
catch (SocketException ex)
{
DisconnectInternal(HazelInternalErrors.SocketExceptionSend, "Could not send data as a SocketException occurred: " + ex.Message);
}
}
/// <inheritdoc />
public override void Connect(byte[] bytes = null, int timeout = 5000)
{
this.ConnectAsync(bytes);
//Wait till hello packet is acknowledged and the state is set to Connected
bool timedOut = !WaitOnConnect(timeout);
//If we timed out raise an exception
if (timedOut)
{
Dispose();
throw new HazelException("Connection attempt timed out.");
}
}
/// <inheritdoc />
public override void ConnectAsync(byte[] bytes = null)
{
this.State = ConnectionState.Connecting;
try
{
if (IPMode == IPMode.IPv4)
socket.Bind(new IPEndPoint(IPAddress.Any, 0));
else
socket.Bind(new IPEndPoint(IPAddress.IPv6Any, 0));
}
catch (SocketException e)
{
this.State = ConnectionState.NotConnected;
throw new HazelException("A SocketException occurred while binding to the port.", e);
}
try
{
StartListeningForData();
}
catch (ObjectDisposedException)
{
// If the socket's been disposed then we can just end there but make sure we're in NotConnected state.
// If we end up here I'm really lost...
this.State = ConnectionState.NotConnected;
return;
}
catch (SocketException e)
{
Dispose();
throw new HazelException("A SocketException occurred while initiating a receive operation.", e);
}
// Write bytes to the server to tell it hi (and to punch a hole in our NAT, if present)
// When acknowledged set the state to connected
SendHello(bytes, () =>
{
this.State = ConnectionState.Connected;
this.InitializeKeepAliveTimer();
});
}
/// <summary>
/// Instructs the listener to begin listening.
/// </summary>
void StartListeningForData()
{
#if DEBUG
if (this.TestLagMs > 0)
{
Thread.Sleep(this.TestLagMs);
}
#endif
var msg = MessageReader.GetSized(this.ReceiveBufferSize);//一个父message
try
{
// Buffer包含MessageWriter的整个内容,包括header
socket.BeginReceive(msg.Buffer, 0, msg.Buffer.Length, SocketFlags.None, ReadCallback, msg);
}
catch
{
msg.Recycle();
this.Dispose();
}
}
protected override void SetState(ConnectionState state)
{
try
{
// If the server disconnects you during the hello
// you can go straight from Connecting to NotConnected.
if (state == ConnectionState.Connected
|| state == ConnectionState.NotConnected)
{
connectWaitLock.Set();
}
else
{
connectWaitLock.Reset();
}
}
catch (ObjectDisposedException)
{
}
}
/// <summary>
/// Blocks until the Connection is connected.
/// </summary>
/// <param name="timeout">The number of milliseconds to wait before timing out.</param>
public bool WaitOnConnect(int timeout)
{
return connectWaitLock.WaitOne(timeout);
}
/// <summary>
/// Called when data has been received by the socket.
/// </summary>
/// <param name="result">The asyncronous operation's result.</param>
void ReadCallback(IAsyncResult result)
{
var msg = (MessageReader)result.AsyncState;
try
{
msg.Length = socket.EndReceive(result);
}
catch (SocketException e)
{
msg.Recycle();
DisconnectInternal(HazelInternalErrors.SocketExceptionReceive, "Socket exception while reading data: " + e.Message);
return;
}
catch (Exception)
{
msg.Recycle();
return;
}
//Exit if no bytes read, we've failed.
if (msg.Length == 0)
{
msg.Recycle();
DisconnectInternal(HazelInternalErrors.ReceivedZeroBytes, "Received 0 bytes");
return;
}
//Begin receiving again
try
{
StartListeningForData(); //继续接受消息。它这里没有用async await在一个while里轮询,所以需要嵌套调用
}
catch (SocketException e)
{
DisconnectInternal(HazelInternalErrors.SocketExceptionReceive, "Socket exception during receive: " + e.Message);
}
catch (ObjectDisposedException)
{
//If the socket's been disposed then we can just end there.
return;
}
#if DEBUG
if (this.TestDropRate > 0)
{
if ((this.testDropCount++ % this.TestDropRate) == 0)
{
return;
}
}
DataReceivedRaw?.Invoke(msg.Buffer, msg.Length);
#endif
//c //! 重点看这里面长什么样
HandleReceive(msg, msg.Length);
}
/// <summary>
/// Sends a disconnect message to the end point.
/// You may include optional disconnect data. The SendOption must be unreliable.
/// </summary>
protected override bool SendDisconnect(MessageWriter data = null)
{
lock (this)
{
if (this._state == ConnectionState.NotConnected) return false;
this.State = ConnectionState.NotConnected; // Use the property so we release the state lock
}
var bytes = EmptyDisconnectBytes;
if (data != null && data.Length > 0)
{
if (data.SendOption != SendOption.None) throw new ArgumentException("Disconnect messages can only be unreliable.");
bytes = data.ToByteArray(true);
bytes[0] = (byte)UdpSendOption.Disconnect;
}
try
{
socket.SendTo(
bytes,
0,
bytes.Length,
SocketFlags.None,
EndPoint);
}
catch { }
return true;
}
/// <inheritdoc />
protected override void Dispose(bool disposing)
{
if (disposing)
{
SendDisconnect();
}
try { this.socket.Shutdown(SocketShutdown.Both); } catch { }
try { this.socket.Close(); } catch { }
try { this.socket.Dispose(); } catch { }
this.reliablePacketTimer.Dispose();
this.connectWaitLock.Dispose();
base.Dispose(disposing);
}
}
}
|