namespace Hazel.Udp
{
- ///
public class BroadcastPacket
{
- ///
public string Data;
-
- ///
public DateTime ReceiveTime;
-
- ///
public IPEndPoint Sender;
- ///
public BroadcastPacket(string data, IPEndPoint sender)
{
this.Data = data;
}
}
- ///
public class UdpBroadcastListener : IDisposable
{
private Socket socket;
private EndPoint endpoint;
+ private Action<string> logger;
private byte[] buffer = new byte[1024];
public bool Running { get; private set; }
///
- public UdpBroadcastListener(int port)
+ public UdpBroadcastListener(int port, Action<string> logger = null)
{
+ this.logger = logger;
this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
- this.socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
+ this.socket.EnableBroadcast = true;
+ this.socket.MulticastLoopback = false;
this.endpoint = new IPEndPoint(IPAddress.Any, port);
this.socket.Bind(this.endpoint);
}
{
if (this.Running) return;
this.Running = true;
-
+
try
{
EndPoint endpt = new IPEndPoint(IPAddress.Any, 0);
ThreadPool.QueueUserWorkItem(_ => this.HandleData(result));
}
}
- catch
+ catch (NullReferenceException) { }
+ catch (Exception e)
{
+ this.logger?.Invoke("BroadcastListener: " + e);
this.Dispose();
}
}
{
numBytes = this.socket.EndReceiveFrom(result, ref endpt);
}
- catch
+ catch (NullReferenceException)
{
+ // Already disposed
+ return;
+ }
+ catch (Exception e)
+ {
+ this.logger?.Invoke("BroadcastListener: " + e);
this.Dispose();
return;
}
- if (numBytes < 2
+ if (numBytes < 3
|| buffer[0] != 4 || buffer[1] != 2)
{
this.StartListen();
for (int i = 0; i < this.packets.Count; ++i)
{
var pkt = this.packets[i];
+ if (pkt == null || pkt.Data == null)
+ {
+ this.packets.RemoveAt(i);
+ i--;
+ continue;
+ }
+
if (pkt.Data.GetHashCode() == dataHash
&& pkt.Sender.Equals(ipEnd))
{
///
public class UdpBroadcaster : IDisposable
{
- ///
private Socket socket;
-
- ///
private byte[] data;
-
- ///
private EndPoint endpoint;
+ private Action<string> logger;
///
- public UdpBroadcaster(int port)
+ public UdpBroadcaster(int port, Action<string> logger = null)
{
+ this.logger = logger;
this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
- this.socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
+ this.socket.EnableBroadcast = true;
+ this.socket.MulticastLoopback = false;
this.endpoint = new IPEndPoint(IPAddress.Broadcast, port);
}
return;
}
- this.socket.BeginSendTo(data, 0, data.Length, SocketFlags.None, this.endpoint, (evt) => this.socket.EndSendTo(evt), null);
+ try
+ {
+ this.socket.BeginSendTo(data, 0, data.Length, SocketFlags.None, this.endpoint, this.FinishSendTo, null);
+ }
+ catch (Exception e)
+ {
+ this.logger?.Invoke("BroadcastListener: " + e);
+ }
+ }
+
+ private void FinishSendTo(IAsyncResult evt)
+ {
+ try
+ {
+ this.socket.EndSendTo(evt);
+ }
+ catch (Exception e)
+ {
+ this.logger?.Invoke("BroadcastListener: " + e);
+ }
}
///