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
|
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace Hazel.Udp
{
/// <summary>
/// Listens for new UDP connections and creates UdpConnections for them.
/// </summary>
/// <inheritdoc />
public class UdpConnectionListener : NetworkConnectionListener
{
private const int SendReceiveBufferSize = 1024 * 1024;
private const int BufferSize = ushort.MaxValue;
private Socket socket;
private ILogger Logger;
private Timer reliablePacketTimer;
private ConcurrentDictionary<EndPoint, UdpServerConnection> allConnections = new ConcurrentDictionary<EndPoint, UdpServerConnection>();
public override double AveragePing => this.allConnections.Values.Sum(c => c.AveragePingMs) / this.allConnections.Count;
public override int ConnectionCount { get { return this.allConnections.Count; } }
public override int ReceiveQueueLength => throw new NotImplementedException();
public override int SendQueueLength => throw new NotImplementedException();
/// <summary>
/// Creates a new UdpConnectionListener for the given <see cref="IPAddress"/>, port and <see cref="IPMode"/>.
/// </summary>
/// <param name="endPoint">The endpoint to listen on.</param>
public UdpConnectionListener(IPEndPoint endPoint, IPMode ipMode = IPMode.IPv4, ILogger logger = null)
{
this.Logger = logger;
this.EndPoint = endPoint;
this.IPMode = ipMode;
this.socket = UdpConnection.CreateSocket(this.IPMode);
socket.ReceiveBufferSize = SendReceiveBufferSize;
socket.SendBufferSize = SendReceiveBufferSize;
reliablePacketTimer = new Timer(ManageReliablePackets, null, 100, Timeout.Infinite);
}
~UdpConnectionListener()
{
this.Dispose(false);
}
private void ManageReliablePackets(object state)
{
foreach (var kvp in this.allConnections)
{
var sock = kvp.Value;
sock.ManageReliablePackets();
}
try
{
this.reliablePacketTimer.Change(100, Timeout.Infinite);
}
catch { }
}
/// <inheritdoc />
public override void Start()
{
try
{
socket.Bind(EndPoint);
}
catch (SocketException e)
{
throw new HazelException("Could not start listening as a SocketException occurred", e);
}
StartListeningForData();
}
/// <summary>
/// Instructs the listener to begin listening.
/// </summary>
private void StartListeningForData()
{
EndPoint remoteEP = EndPoint;
MessageReader message = null;
try
{
message = MessageReader.GetSized(this.ReceiveBufferSize);
socket.BeginReceiveFrom(message.Buffer, 0, message.Buffer.Length, SocketFlags.None, ref remoteEP, ReadCallback, message);
}
catch (SocketException sx)
{
message?.Recycle();
this.Logger?.WriteError("Socket Ex in StartListening: " + sx.Message);
Thread.Sleep(10);
StartListeningForData();
return;
}
catch (Exception ex)
{
message.Recycle();
this.Logger?.WriteError("Stopped due to: " + ex.Message);
return;
}
}
void ReadCallback(IAsyncResult result)
{
var message = (MessageReader)result.AsyncState;
int bytesReceived;
EndPoint remoteEndPoint = new IPEndPoint(this.EndPoint.Address, this.EndPoint.Port);
//End the receive operation
try
{
bytesReceived = socket.EndReceiveFrom(result, ref remoteEndPoint);
message.Offset = 0;
message.Length = bytesReceived;
}
catch (ObjectDisposedException)
{
message.Recycle();
return;
}
catch (SocketException sx)
{
message.Recycle();
if (sx.SocketErrorCode == SocketError.NotConnected)
{
this.InvokeInternalError(HazelInternalErrors.ConnectionDisconnected);
return;
}
// Client no longer reachable, pretend it didn't happen
// TODO should this not inform the connection this client is lost???
// This thread suggests the IP is not passed out from WinSoc so maybe not possible
// http://stackoverflow.com/questions/2576926/python-socket-error-on-udp-data-receive-10054
this.Logger?.WriteError($"Socket Ex {sx.SocketErrorCode} in ReadCallback: {sx.Message}");
Thread.Sleep(10);
StartListeningForData();
return;
}
catch (Exception ex)
{
// Idk, maybe a null ref after dispose?
message.Recycle();
this.Logger?.WriteError("Stopped due to: " + ex.Message);
return;
}
// I'm a little concerned about a infinite loop here, but it seems like it's possible
// to get 0 bytes read on UDP without the socket being shut down.
if (bytesReceived == 0)
{
message.Recycle();
this.Logger?.WriteInfo("Received 0 bytes");
Thread.Sleep(10);
StartListeningForData();
return;
}
//Begin receiving again
StartListeningForData();
bool aware = true;
bool isHello = message.Buffer[0] == (byte)UdpSendOption.Hello;
// If we're aware of this connection use the one already
// If this is a new client then connect with them!
UdpServerConnection connection;
if (!this.allConnections.TryGetValue(remoteEndPoint, out connection))
{
lock (this.allConnections)
{
if (!this.allConnections.TryGetValue(remoteEndPoint, out connection))
{
// Check for malformed connection attempts
if (!isHello)
{
message.Recycle();
return;
}
if (AcceptConnection != null)
{
if (!AcceptConnection((IPEndPoint)remoteEndPoint, message.Buffer, out var response))
{
message.Recycle();
if (response != null)
{
SendData(response, response.Length, remoteEndPoint);
}
return;
}
}
aware = false;
connection = new UdpServerConnection(this, (IPEndPoint)remoteEndPoint, this.IPMode, this.Logger);
if (!this.allConnections.TryAdd(remoteEndPoint, connection))
{
throw new HazelException("Failed to add a connection. This should never happen.");
}
}
}
}
// If it's a new connection invoke the NewConnection event.
// This needs to happen before handling the message because in localhost scenarios, the ACK and
// subsequent messages can happen before the NewConnection event sets up OnDataRecieved handlers
if (!aware)
{
// Skip header and hello byte;
message.Offset = 4;
message.Length = bytesReceived - 4;
message.Position = 0;
InvokeNewConnection(message, connection);
}
// Inform the connection of the buffer (new connections need to send an ack back to client)
connection.HandleReceive(message, bytesReceived);
}
#if DEBUG
public int TestDropRate = -1;
private int dropCounter = 0;
#endif
/// <summary>
/// Sends data from the listener socket.
/// </summary>
/// <param name="bytes">The bytes to send.</param>
/// <param name="endPoint">The endpoint to send to.</param>
internal void SendData(byte[] bytes, int length, EndPoint endPoint)
{
if (length > bytes.Length) return;
#if DEBUG
if (TestDropRate > 0)
{
if (Interlocked.Increment(ref dropCounter) % TestDropRate == 0)
{
return;
}
}
#endif
try
{
socket.BeginSendTo(
bytes,
0,
length,
SocketFlags.None,
endPoint,
SendCallback,
null);
this.Statistics.AddBytesSent(length);
}
catch (SocketException e)
{
this.Logger?.WriteError("Could not send data as a SocketException occurred: " + e);
}
catch (ObjectDisposedException)
{
//Keep alive timer probably ran, ignore
return;
}
}
private void SendCallback(IAsyncResult result)
{
try
{
socket.EndSendTo(result);
}
catch { }
}
/// <summary>
/// Sends data from the listener socket.
/// </summary>
/// <param name="bytes">The bytes to send.</param>
/// <param name="endPoint">The endpoint to send to.</param>
internal void SendDataSync(byte[] bytes, int length, EndPoint endPoint)
{
try
{
socket.SendTo(
bytes,
0,
length,
SocketFlags.None,
endPoint
);
this.Statistics.AddBytesSent(length);
}
catch { }
}
/// <summary>
/// Removes a virtual connection from the list.
/// </summary>
/// <param name="endPoint">The endpoint of the virtual connection.</param>
internal void RemoveConnectionTo(EndPoint endPoint)
{
this.allConnections.TryRemove(endPoint, out var conn);
}
/// <inheritdoc />
protected override void Dispose(bool disposing)
{
foreach (var kvp in this.allConnections)
{
kvp.Value.Dispose();
}
try { this.socket.Shutdown(SocketShutdown.Both); } catch { }
try { this.socket.Close(); } catch { }
try { this.socket.Dispose(); } catch { }
this.reliablePacketTimer.Dispose();
base.Dispose(disposing);
}
}
}
|