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
|
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Threading;
namespace Hazel.Udp
{
partial class UdpConnection
{
/// <summary>
/// Class to hold packet data
/// </summary>
public class PingPacket : IRecyclable
{
private static readonly ObjectPool<PingPacket> PacketPool = new ObjectPool<PingPacket>(() => new PingPacket());
public readonly Stopwatch Stopwatch = new Stopwatch();
internal static PingPacket GetObject()
{
return PacketPool.GetObject();
}
public void Recycle()
{
Stopwatch.Stop();
PacketPool.PutObject(this);
}
}
internal ConcurrentDictionary<ushort, PingPacket> activePingPackets = new ConcurrentDictionary<ushort, PingPacket>();
/// <summary>
/// The interval from data being received or transmitted to a keepalive packet being sent in milliseconds.
/// </summary>
/// <remarks>
/// <para>
/// Keepalive packets serve to close connections when an endpoint abruptly disconnects and to ensure than any
/// NAT devices do not close their translation for our argument. By ensuring there is regular contact the
/// connection can detect and prevent these issues.
/// </para>
/// <para>
/// The default value is 10 seconds, set to System.Threading.Timeout.Infinite to disable keepalive packets.
/// </para>
/// </remarks>
public int KeepAliveInterval
{
get
{
return keepAliveInterval;
}
set
{
keepAliveInterval = value;
ResetKeepAliveTimer();
}
}
private int keepAliveInterval = 1500;
public int MissingPingsUntilDisconnect { get; set; } = 6;
private volatile int pingsSinceAck = 0;
/// <summary>
/// The timer creating keepalive pulses.
/// </summary>
private Timer keepAliveTimer;
/// <summary>
/// Starts the keepalive timer.
/// </summary>
protected void InitializeKeepAliveTimer()
{
keepAliveTimer = new Timer(
HandleKeepAlive,
null,
keepAliveInterval,
keepAliveInterval
);
}
private void HandleKeepAlive(object state)
{
if (this.State != ConnectionState.Connected) return;
if (this.pingsSinceAck >= this.MissingPingsUntilDisconnect)
{
this.DisposeKeepAliveTimer();
this.DisconnectInternal(HazelInternalErrors.PingsWithoutResponse, $"Sent {this.pingsSinceAck} pings that remote has not responded to.");
return;
}
try
{
this.pingsSinceAck++;
SendPing();
}
catch
{
}
}
// Pings are special, quasi-reliable packets.
// We send them to trigger responses that validate our connection is alive
// An unacked ping should never be the sole cause of a disconnect.
// Rather, the responses will reset our pingsSinceAck, enough unacked
// pings should cause a disconnect.
private void SendPing()
{
ushort id = (ushort)Interlocked.Increment(ref lastIDAllocated);
byte[] bytes = new byte[3];
bytes[0] = (byte)UdpSendOption.Ping;
bytes[1] = (byte)(id >> 8);
bytes[2] = (byte)id;
PingPacket pkt;
if (!this.activePingPackets.TryGetValue(id, out pkt))
{
pkt = PingPacket.GetObject();
if (!this.activePingPackets.TryAdd(id, pkt))
{
throw new Exception("This shouldn't be possible");
}
}
pkt.Stopwatch.Restart();
WriteBytesToConnection(bytes, bytes.Length);
Statistics.LogReliableSend(0);
}
/// <summary>
/// Resets the keepalive timer to zero.
/// </summary>
protected void ResetKeepAliveTimer()
{
try
{
keepAliveTimer?.Change(keepAliveInterval, keepAliveInterval);
}
catch { }
}
/// <summary>
/// Disposes of the keep alive timer.
/// </summary>
private void DisposeKeepAliveTimer()
{
if (this.keepAliveTimer != null)
{
this.keepAliveTimer.Dispose();
}
foreach (var kvp in activePingPackets)
{
if (this.activePingPackets.TryRemove(kvp.Key, out var pkt))
{
pkt.Recycle();
}
}
}
}
}
|