diff --git a/LANCommander.SDK/Clients/BeaconClient.cs b/LANCommander.SDK/Clients/BeaconClient.cs index 792f8de8..3ce4b773 100644 --- a/LANCommander.SDK/Clients/BeaconClient.cs +++ b/LANCommander.SDK/Clients/BeaconClient.cs @@ -57,6 +57,12 @@ public class BeaconClient( await probeClient.BindSocketAsync(port); + // Subscribe to probe responses and forward them to our event + probeClient.OnBeaconResponse += (sender, e) => + { + OnBeaconResponse?.Invoke(sender, e); + }; + _probeClients.Add(probeClient); } catch diff --git a/LANCommander.SDK/Clients/DiscoveryProbe.cs b/LANCommander.SDK/Clients/DiscoveryProbe.cs index bc462389..364f84e9 100644 --- a/LANCommander.SDK/Clients/DiscoveryProbe.cs +++ b/LANCommander.SDK/Clients/DiscoveryProbe.cs @@ -19,9 +19,8 @@ public class DiscoveryProbe : IDisposable private bool _disposed = false; private int _port = 35891; - private readonly UdpClient _udpClient; private readonly Socket _socket; - private readonly IEnumerable _broadcastEndpoints; + private IEnumerable _broadcastEndpoints = Enumerable.Empty(); private readonly CancellationTokenSource _cancellationTokenSource; private readonly byte[] _probeId; private readonly NetworkInterface _networkInterface; @@ -34,12 +33,10 @@ public class DiscoveryProbe : IDisposable public DiscoveryProbe(NetworkInterface networkInterface) { _networkInterface = networkInterface; - _udpClient = new UdpClient(0); - _udpClient.EnableBroadcast = true; _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); + _socket.EnableBroadcast = true; - _broadcastEndpoints = networkInterface.GetBroadcastAddresses().Select(ba => new IPEndPoint(ba, _port)); _probeId = Encoding.ASCII.GetBytes(Guid.NewGuid().ToString()); _cancellationTokenSource = new CancellationTokenSource(); } @@ -50,13 +47,15 @@ public class DiscoveryProbe : IDisposable public async Task SendAsync() { foreach (var endpoint in _broadcastEndpoints) - await _udpClient.SendAsync(_probeId, _probeId.Length, endpoint); + { + await Task.Run(() => _socket.SendTo(_probeId, SocketFlags.None, endpoint)); + } } /// /// Listen for responses from beacons /// - /// Port to listen on/param> + /// Port to listen on /// Failed to bind to network interface public async Task BindSocketAsync(int port) { @@ -70,6 +69,8 @@ public class DiscoveryProbe : IDisposable if (addressInformation == null) throw new NetworkInformationException(); + _broadcastEndpoints = _networkInterface.GetBroadcastAddresses().Select(ba => new IPEndPoint(ba, _port)); + EndPoint fromEndpoint = new IPEndPoint(IPAddress.Any, 0); _socket.Bind(new IPEndPoint(addressInformation.Address, _port)); @@ -121,8 +122,6 @@ public class DiscoveryProbe : IDisposable { OnBeaconResponse = null; - _udpClient?.Close(); - _udpClient?.Dispose(); _socket?.Close(); _socket?.Dispose(); _cancellationTokenSource?.Dispose();