Network Library Documentation
Loading...
Searching...
No Matches
NetworkMonitor Class Reference

NetworkMonitor is responsible for actively monitoring network quality metrics such as latency, jitter, packet loss, bandwidth, and throughput. It provides real-time updates to the UI. More...

Inheritance diagram for NetworkMonitor:

Public Member Functions

void OnPingResponse (int id)
 Handles a received ping response, calculates latency and jitter in ms.
void StartBandwidthTest ()
 Initiates a bandwidth test by sending a large byte array.
void StartThroughputTest ()
 Starts a throughput test by sending 100 UDP packets.
void OnThroughputResposne (int pcktId, int DataSize)
 Called when a response for a throughput packet is received.
float GetLossPercent ()
float GetAverageRTT ()
float GetJitter ()

Private Member Functions

void Start ()
 Subscribes to client events and starts monitoring after connection.
void StartMonitor ()
 Starts the latency monitor coroutine.
void StopMonitoring ()
 Stops all monitoring coroutines and cleanups.
IEnumerator PingCoroutine ()
 Coroutine that repeatedly sends latency packets and calculate packet loss.
void SendPing ()
 Sends a latency packet and tracks its send time.
void CalculateLoss ()
 Calculates packet loss percentage and updates the UI.
void CleanOldPings ()
 Removes pings that have exceeded the timeout.
float Average (List< float > list)
 Calculates the average of values in float list.
float CalculateJitter ()
 Calculates jitter based on differences in RTT samples.
void OnBandwidthResponse ()
 Called when the server replies to a bandwidth test; calculates and displays bandwidth.
IEnumerator stopThroughput ()
 Coroutine that stops the throughput test after a fixed time - 5s if not completed.
void ThroughputCalculate ()
 Finalizes throughput test and updates the UI with results.

Private Attributes

float pingInterval = 1f
 Interval in seconds between pings sent to measure latency.
float pingTimeout = 5f
 Timeout in seconds after which a ping is considered lost.
Text MonitorText1
 UI Text element displaying packet loss, average latency, and jitter.
Text MonitorText2
 UI Text element displaying bandwidth test result.
Text MonitorText3
 UI Text element displaying throughput test result.
int sentPackets = 0
 Total number of latency packets sent.
int receivedResponses = 0
 Total number of latency responses received.
int sentPacketsInterval = 0
 Number of latency packets sent during the current interval.
int receivedResponsesInterval = 0
 Number of responses received during the current interval.
HashSet< int > awaitingResponses = new()
 Set of IDs for which responses are still pending.
Dictionary< int, float > sentTimes = new()
 Dictionary storing the send time for each packet ID.
List< float > latencySamples = new()
 List of recent round-trip time (RTT) samples for calculating average latency and jitter.
float lastLossPercent = 0f
 Last calculated packet loss percentage.
float lastJitter = 0f
 Last calculated jitter value.
float bandwidthClientStartTime
 Timestamp when the bandwidth test started.
int BandwidthDataSize
 Size in bytes of the bandwidth test data.
Coroutine pingCoroutine
 Coroutine reference for the ping routine.
Coroutine throughputTimeoutRoutine
 Coroutine reference for the throughput timeout logic.
float ThroughputStartTime
int ThroughputSentSize = 0
int ThroughputReceivedSize = 0
bool isThroughputRunning = false
int ThroughputPacketsReceived = 0

Detailed Description

NetworkMonitor is responsible for actively monitoring network quality metrics such as latency, jitter, packet loss, bandwidth, and throughput. It provides real-time updates to the UI.

Definition at line 10 of file NetworkMonitor.cs.

Member Function Documentation

◆ Average()

float NetworkMonitor.Average ( List< float > list)
private

Calculates the average of values in float list.

Definition at line 208 of file NetworkMonitor.cs.

209 {
210 float sum = 0f;
211 foreach (float entry in list)
212 sum += entry;
213 return sum / list.Count;
214 }

◆ CalculateJitter()

float NetworkMonitor.CalculateJitter ( )
private

Calculates jitter based on differences in RTT samples.

Definition at line 218 of file NetworkMonitor.cs.

219 {
220 if (latencySamples.Count < 2) return 0f;
221
222 float totalDiff = 0f;
223 for (int i = 1; i < latencySamples.Count; i++)
224 totalDiff += Mathf.Abs(latencySamples[i] - latencySamples[i - 1]);
225 return totalDiff / (latencySamples.Count - 1);
226 }
List< float > latencySamples
List of recent round-trip time (RTT) samples for calculating average latency and jitter.

◆ CalculateLoss()

void NetworkMonitor.CalculateLoss ( )
private

Calculates packet loss percentage and updates the UI.

Definition at line 165 of file NetworkMonitor.cs.

166 {
168 if (sentPacketsInterval > 0) {
169 lastLossPercent = (float)lost / sentPacketsInterval * 100f;
170 } else {
171 lastLossPercent = 0f;
172 }
173
174 float avgRtt;
175 if (latencySamples.Count > 0) {
176 avgRtt = Average(latencySamples);
177 } else {
178 avgRtt = 0f;
179 }
180 MonitorText1.text = ($"[NetworkMonitor] Packet Loss: {lastLossPercent:F2}% | Avg RTT: {avgRtt:F2} ms | Jitter: {lastJitter:F2} ms");
183
184 /*
185 File.AppendAllText(pingLog, avgRtt.ToString() + "\n");
186 File.AppendAllText(jitterLog, lastJitter.ToString() + "\n");
187 File.AppendAllText(packetLossLog, lastLossPercent.ToString() + "\n"); */
188 }
float Average(List< float > list)
Calculates the average of values in float list.
int receivedResponsesInterval
Number of responses received during the current interval.
int sentPacketsInterval
Number of latency packets sent during the current interval.
float lastLossPercent
Last calculated packet loss percentage.

◆ CleanOldPings()

void NetworkMonitor.CleanOldPings ( )
private

Removes pings that have exceeded the timeout.

Definition at line 192 of file NetworkMonitor.cs.

193 {
194 float now = Time.time;
195 List<int> expired = new();
196 foreach (var sent in sentTimes) {
197 if (now - sent.Value > pingTimeout)
198 expired.Add(sent.Key);
199 }
200 foreach (int id in expired) {
201 awaitingResponses.Remove(id);
202 sentTimes.Remove(id);
203 }
204 }
float pingTimeout
Timeout in seconds after which a ping is considered lost.
HashSet< int > awaitingResponses
Set of IDs for which responses are still pending.
Dictionary< int, float > sentTimes
Dictionary storing the send time for each packet ID.

◆ GetAverageRTT()

float NetworkMonitor.GetAverageRTT ( )

Definition at line 324 of file NetworkMonitor.cs.

325 {
326 float avgRtt;
327 if (latencySamples.Count > 0) {
328 avgRtt = Average(latencySamples);
329 } else {
330 avgRtt = 0f;
331 }
332 return avgRtt;
333 }

◆ GetJitter()

float NetworkMonitor.GetJitter ( )

Definition at line 334 of file NetworkMonitor.cs.

334 {
335 return lastJitter ;
336 }
float lastJitter
Last calculated jitter value.

◆ GetLossPercent()

float NetworkMonitor.GetLossPercent ( )

Definition at line 320 of file NetworkMonitor.cs.

321 {
322 return lastLossPercent;
323 }

◆ OnBandwidthResponse()

void NetworkMonitor.OnBandwidthResponse ( )
private

Called when the server replies to a bandwidth test; calculates and displays bandwidth.

Definition at line 242 of file NetworkMonitor.cs.

243 {
244 float TimeReply = Time.realtimeSinceStartup;
245 float duration = TimeReply - bandwidthClientStartTime;
246 float bandwidthMbps = (BandwidthDataSize * 8f) / duration / 1_000_000f;
247 MonitorText2.text = ($"[BandwidthTest] {bandwidthMbps:F2} Mbps");
248 // File.AppendAllText(bandwidthLog, bandwidthMbps.ToString() + "\n");
249 }
float bandwidthClientStartTime
Timestamp when the bandwidth test started.
int BandwidthDataSize
Size in bytes of the bandwidth test data.

◆ OnPingResponse()

void NetworkMonitor.OnPingResponse ( int id)

Handles a received ping response, calculates latency and jitter in ms.

Definition at line 146 of file NetworkMonitor.cs.

147 {
148 if (awaitingResponses.Contains(id) && sentTimes.ContainsKey(id))
149 {
150 float sentTime = sentTimes[id];
151 float rtt = (Time.time - sentTime) * 1000f;
152 latencySamples.Add(rtt);
153 if (latencySamples.Count > 10)
154 latencySamples.RemoveAt(0);
157 awaitingResponses.Remove(id);
158 sentTimes.Remove(id);
160 }
161 }
float CalculateJitter()
Calculates jitter based on differences in RTT samples.
int receivedResponses
Total number of latency responses received.

◆ OnThroughputResposne()

void NetworkMonitor.OnThroughputResposne ( int pcktId,
int DataSize )

Called when a response for a throughput packet is received.

Definition at line 287 of file NetworkMonitor.cs.

288 {
290 ThroughputReceivedSize += DataSize;
292 {
293 isThroughputRunning = false;
294 StopCoroutine(throughputTimeoutRoutine);
296 }
297 }
Coroutine throughputTimeoutRoutine
Coroutine reference for the throughput timeout logic.
void ThroughputCalculate()
Finalizes throughput test and updates the UI with results.

◆ PingCoroutine()

IEnumerator NetworkMonitor.PingCoroutine ( )
private

Coroutine that repeatedly sends latency packets and calculate packet loss.

Definition at line 121 of file NetworkMonitor.cs.

122 {
123 while (true)
124 {
126 SendPing();
127 yield return new WaitForSeconds(pingInterval);
129 }
130 }
void CleanOldPings()
Removes pings that have exceeded the timeout.
void SendPing()
Sends a latency packet and tracks its send time.
void CalculateLoss()
Calculates packet loss percentage and updates the UI.
float pingInterval
Interval in seconds between pings sent to measure latency.

◆ SendPing()

void NetworkMonitor.SendPing ( )
private

Sends a latency packet and tracks its send time.

Definition at line 134 of file NetworkMonitor.cs.

135 {
136 int id = sentPackets++;
137 float timeSent = Time.time;
138 awaitingResponses.Add(id);
139 sentTimes[id] = timeSent;
141 Client.instance.MeassureRequest(id);
142 }
int sentPackets
Total number of latency packets sent.

◆ Start()

void NetworkMonitor.Start ( )
private

Subscribes to client events and starts monitoring after connection.

Definition at line 94 of file NetworkMonitor.cs.

95 {
96 Client.instance.OnPingReply += OnPingResponse;
97 Client.instance.OnConnected += StartMonitor;
98 Client.instance.OnBandwidthReply += OnBandwidthResponse;
99 Client.instance.OnThroughputReply += OnThroughputResposne;
100 Client.instance.OnDisconnected += StopMonitoring;
101 }
void StopMonitoring()
Stops all monitoring coroutines and cleanups.
void OnBandwidthResponse()
Called when the server replies to a bandwidth test; calculates and displays bandwidth.
void OnThroughputResposne(int pcktId, int DataSize)
Called when a response for a throughput packet is received.
void StartMonitor()
Starts the latency monitor coroutine.
void OnPingResponse(int id)
Handles a received ping response, calculates latency and jitter in ms.

◆ StartBandwidthTest()

void NetworkMonitor.StartBandwidthTest ( )

Initiates a bandwidth test by sending a large byte array.

Definition at line 230 of file NetworkMonitor.cs.

231 {
232 int sizeKB = 512;
233 byte[] data = new byte[sizeKB * 1024];
234 new System.Random().NextBytes(data);
235 bandwidthClientStartTime = Time.realtimeSinceStartup;
236 BandwidthDataSize = data.Length;
237 Client.instance.BandwidthRequest(data);
238 }

◆ StartMonitor()

void NetworkMonitor.StartMonitor ( )
private

Starts the latency monitor coroutine.

Definition at line 105 of file NetworkMonitor.cs.

106 {
107 pingCoroutine = StartCoroutine(PingCoroutine());
108 }
Coroutine pingCoroutine
Coroutine reference for the ping routine.
IEnumerator PingCoroutine()
Coroutine that repeatedly sends latency packets and calculate packet loss.

◆ StartThroughputTest()

void NetworkMonitor.StartThroughputTest ( )

Starts a throughput test by sending 100 UDP packets.

Definition at line 258 of file NetworkMonitor.cs.

259 {
261 {
262 Debug.LogWarning("[ThroughputTester] Test already running.");
263 return;
264 }
268 isThroughputRunning = true;
269 ThroughputStartTime = Time.realtimeSinceStartup;
270 throughputTimeoutRoutine = StartCoroutine(stopThroughput());
271 for(int i = 1; i<=100; i++)
272 {
274 {
276 break;
277 }
278 byte[] data = new byte[1024];
279 new System.Random().NextBytes(data);
280 ThroughputSentSize += data.Length;
281 Client.instance.SendThroughputData(i, data);
282 }
283 }
IEnumerator stopThroughput()
Coroutine that stops the throughput test after a fixed time - 5s if not completed.

◆ StopMonitoring()

void NetworkMonitor.StopMonitoring ( )
private

Stops all monitoring coroutines and cleanups.

Definition at line 112 of file NetworkMonitor.cs.

113 {
114 StopCoroutine(pingCoroutine);
115 if(throughputTimeoutRoutine != null)
116 StopCoroutine(throughputTimeoutRoutine);
117 }

◆ stopThroughput()

IEnumerator NetworkMonitor.stopThroughput ( )
private

Coroutine that stops the throughput test after a fixed time - 5s if not completed.

Definition at line 301 of file NetworkMonitor.cs.

302 {
303 yield return new WaitForSeconds(5);
304 isThroughputRunning = false;
306
307 }

◆ ThroughputCalculate()

void NetworkMonitor.ThroughputCalculate ( )
private

Finalizes throughput test and updates the UI with results.

Definition at line 311 of file NetworkMonitor.cs.

312 {
313 StopCoroutine(throughputTimeoutRoutine);
314 float duration = Time.realtimeSinceStartup - ThroughputStartTime;
315 float throughputMbps = (ThroughputReceivedSize * 8f) / duration / 1_000_000f;
316 MonitorText3.text = ($"[ThroughputTest] {throughputMbps:F2} Mbps, received {ThroughputPacketsReceived} / 100 packets with size 1024B");
317 /* File.AppendAllText(throughputLog, throughputMbps.ToString() + "\n");
318 File.AppendAllText("throughput.csv", $"{throughputMbps:F2};{ThroughputReceivedSize};{duration:F3}\n"); */
319 }

Member Data Documentation

◆ awaitingResponses

HashSet<int> NetworkMonitor.awaitingResponses = new()
private

Set of IDs for which responses are still pending.

Definition at line 51 of file NetworkMonitor.cs.

◆ bandwidthClientStartTime

float NetworkMonitor.bandwidthClientStartTime
private

Timestamp when the bandwidth test started.

Definition at line 71 of file NetworkMonitor.cs.

◆ BandwidthDataSize

int NetworkMonitor.BandwidthDataSize
private

Size in bytes of the bandwidth test data.

Definition at line 75 of file NetworkMonitor.cs.

◆ isThroughputRunning

bool NetworkMonitor.isThroughputRunning = false
private

Definition at line 253 of file NetworkMonitor.cs.

◆ lastJitter

float NetworkMonitor.lastJitter = 0f
private

Last calculated jitter value.

Definition at line 67 of file NetworkMonitor.cs.

◆ lastLossPercent

float NetworkMonitor.lastLossPercent = 0f
private

Last calculated packet loss percentage.

Definition at line 63 of file NetworkMonitor.cs.

◆ latencySamples

List<float> NetworkMonitor.latencySamples = new()
private

List of recent round-trip time (RTT) samples for calculating average latency and jitter.

Definition at line 59 of file NetworkMonitor.cs.

◆ MonitorText1

Text NetworkMonitor.MonitorText1
private

UI Text element displaying packet loss, average latency, and jitter.

Definition at line 23 of file NetworkMonitor.cs.

◆ MonitorText2

Text NetworkMonitor.MonitorText2
private

UI Text element displaying bandwidth test result.

Definition at line 27 of file NetworkMonitor.cs.

◆ MonitorText3

Text NetworkMonitor.MonitorText3
private

UI Text element displaying throughput test result.

Definition at line 31 of file NetworkMonitor.cs.

◆ pingCoroutine

Coroutine NetworkMonitor.pingCoroutine
private

Coroutine reference for the ping routine.

Definition at line 79 of file NetworkMonitor.cs.

◆ pingInterval

float NetworkMonitor.pingInterval = 1f
private

Interval in seconds between pings sent to measure latency.

Definition at line 15 of file NetworkMonitor.cs.

◆ pingTimeout

float NetworkMonitor.pingTimeout = 5f
private

Timeout in seconds after which a ping is considered lost.

Definition at line 19 of file NetworkMonitor.cs.

◆ receivedResponses

int NetworkMonitor.receivedResponses = 0
private

Total number of latency responses received.

Definition at line 39 of file NetworkMonitor.cs.

◆ receivedResponsesInterval

int NetworkMonitor.receivedResponsesInterval = 0
private

Number of responses received during the current interval.

Definition at line 47 of file NetworkMonitor.cs.

◆ sentPackets

int NetworkMonitor.sentPackets = 0
private

Total number of latency packets sent.

Definition at line 35 of file NetworkMonitor.cs.

◆ sentPacketsInterval

int NetworkMonitor.sentPacketsInterval = 0
private

Number of latency packets sent during the current interval.

Definition at line 43 of file NetworkMonitor.cs.

◆ sentTimes

Dictionary<int, float> NetworkMonitor.sentTimes = new()
private

Dictionary storing the send time for each packet ID.

Definition at line 55 of file NetworkMonitor.cs.

◆ ThroughputPacketsReceived

int NetworkMonitor.ThroughputPacketsReceived = 0
private

Definition at line 254 of file NetworkMonitor.cs.

◆ ThroughputReceivedSize

int NetworkMonitor.ThroughputReceivedSize = 0
private

Definition at line 252 of file NetworkMonitor.cs.

◆ ThroughputSentSize

int NetworkMonitor.ThroughputSentSize = 0
private

Definition at line 251 of file NetworkMonitor.cs.

◆ ThroughputStartTime

float NetworkMonitor.ThroughputStartTime
private

Definition at line 250 of file NetworkMonitor.cs.

◆ throughputTimeoutRoutine

Coroutine NetworkMonitor.throughputTimeoutRoutine
private

Coroutine reference for the throughput timeout logic.

Definition at line 83 of file NetworkMonitor.cs.