-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathUdpClientWrapper.cs
More file actions
98 lines (82 loc) · 2.63 KB
/
UdpClientWrapper.cs
File metadata and controls
98 lines (82 loc) · 2.63 KB
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
using System;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NetSdrClientApp.Networking;
namespace NetSdrClientApp.Networking
{
public class UdpClientWrapper : IUdpClient, IDisposable
{
private readonly IPEndPoint _localEndPoint;
private CancellationTokenSource? _cts;
private UdpClient? _udpClient;
private bool _disposed;
public event EventHandler<byte[]>? MessageReceived;
public UdpClientWrapper(int port)
{
_localEndPoint = new IPEndPoint(IPAddress.Any, port);
}
public async Task StartListeningAsync()
{
_cts = new CancellationTokenSource();
Console.WriteLine("Start listening for UDP messages...");
try
{
_udpClient = new UdpClient(_localEndPoint);
while (!_cts.Token.IsCancellationRequested)
{
UdpReceiveResult result = await _udpClient.ReceiveAsync(_cts.Token);
MessageReceived?.Invoke(this, result.Buffer);
Console.WriteLine($"Received from {result.RemoteEndPoint}");
}
}
catch (OperationCanceledException)
{
Console.WriteLine("Listening cancelled.");
}
catch (Exception ex)
{
Console.WriteLine($"Error receiving message: {ex.Message}");
}
}
public void StopListening()
{
_cts?.Cancel();
_udpClient?.Close();
Console.WriteLine("Stopped listening for UDP messages.");
}
public void Exit()
{
StopListening();
}
public override bool Equals(object? obj)
{
if (obj is not UdpClientWrapper other) return false;
return _localEndPoint.Port == other._localEndPoint.Port &&
_localEndPoint.Address.Equals(other._localEndPoint.Address);
}
public override int GetHashCode()
{
return HashCode.Combine(_localEndPoint.Address, _localEndPoint.Port);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing)
{
_cts?.Cancel();
_cts?.Dispose();
_udpClient?.Dispose();
}
_disposed = true;
}
}
}