public async Task BeginListeningAsync (CancellationToken token)
{
var client = new UdpClient (BroadcastEndpoint);
client.JoinMulticastGroup (BroadcastEndpoint.Address);
token.Register (() => client.Close ());
while (true) {
token.ThrowIfCancellationRequested ();
try {
var result = await client.ReceiveAsync ();
var data = Encoding.UTF8.GetString (result.Buffer);
if (data.StartsWith (Header, StringComparison.Ordinal)) {
if (ServerFound != null) {
var details = new ServerDetails {
Hostname = result.RemoteEndPoint.Address.ToString (),
Port = int.Parse (data.Substring (Header.Length))
};
LoggingService.LogInfo ("Found TunezServer at {0}", details.FullAddress);
ServerFound (this, details);
}
}
} catch (ObjectDisposedException) {
token.ThrowIfCancellationRequested ();
throw;
} catch (SocketException) {
token.ThrowIfCancellationRequested ();
// Ignore this
} catch (Exception ex) {
token.ThrowIfCancellationRequested ();
LoggingService.LogInfo ("Ignoring bad UDP {0}", ex);
}
}
}
}