public static void ListenForBroadcast(int serverPort) { var fallback = new ExpFallback(100, 60 * 1000); var udpClient = new UdpClient(DISCOVERY_PORT) { Client = { ReceiveTimeout = 0 } }; IPEndPoint remoteEndpoint = null; while (true) { try { var receivedBytes = udpClient.Receive(ref remoteEndpoint); if (receivedBytes.SequenceEqual(MagicBroadcastBytes)) { var responseBytes = MagicResponseBytes .Concat(BitConverter.GetBytes(serverPort)) .Concat(Encoding.UTF8.GetBytes(Environment.MachineName)) .ToArray(); udpClient.Send(responseBytes, responseBytes.Length, remoteEndpoint); } } catch (SocketException) { Thread.Sleep(fallback.Value); fallback.Increase(); } } }
public static void SendBroadcast(Action <string, IPEndPoint> callback) { var udpClient = new UdpClient { Client = { ReceiveTimeout = 1000 } }; udpClient.Send(MagicBroadcastBytes, MagicBroadcastBytes.Length, new IPEndPoint(IPAddress.Broadcast, DISCOVERY_PORT)); var fallback = new ExpFallback(100, 60 * 1000); IPEndPoint remoteEndpoint = null; var stopwatch = new Stopwatch(); stopwatch.Start(); while (true) { try { var receivedBytes = udpClient.Receive(ref remoteEndpoint); var portIndex = MagicResponseBytes.Length; var nameIndex = portIndex + 4; if (receivedBytes.Length >= nameIndex && receivedBytes.Take(portIndex).SequenceEqual(MagicResponseBytes)) { var port = BitConverter.ToInt32(receivedBytes, portIndex); var computerName = ""; try { computerName = Encoding.UTF8.GetString(receivedBytes, nameIndex, receivedBytes.Length - nameIndex); } catch (ArgumentException) { } callback(computerName, new IPEndPoint(remoteEndpoint.Address, port)); } } catch (SocketException) { Thread.Sleep(fallback.Value); fallback.Increase(); } if (stopwatch.ElapsedMilliseconds > 10000) { return; } } }