Home Forums Support Peer Discovery Issue on Mac Os Reply To: Peer Discovery Issue on Mac Os

#3388
Anonymous
Inactive

Hi mark,

public class UdpDiscovery :  IDisposable
	{
		private ILog _log;
		private UdpClient _client;
		IPEndPoint _localpt;
		int _broadcastPort = 8888;
		UdpClient _server;
		bool _requestStop;

		public UdpDiscovery (ILog log)
		{
			_log = log;

			//Create socket for broadcasting udp packets
			_localpt = new IPEndPoint (IPAddress.Any, 0);
			_client = new UdpClient ();
			_client.Client.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
			_client.Client.Bind (_localpt);
			_client.EnableBroadcast = true;

			//Server side
			var point = new IPEndPoint (IPAddress.Any, _broadcastPort);
			_server = new UdpClient ();
			_server.ExclusiveAddressUse = false;
			_server.Client.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
			_server.Client.Bind (point);
		}

		public void Signal (byte[] data)
		{
			_client.Send (data, data.Length, new IPEndPoint (IPAddress.Broadcast, _broadcastPort));
		}

		public void StartDiscover ()
		{
			_requestStop = false;
			var handle = _server.BeginReceive (new AsyncCallback (DataReceived), null);
		}

		public void StopDiscovery ()
		{
			_requestStop = true;
		}

		public event EventHandler<EventArgs<byte[]>> PeerDiscovered;

		void OnPeerDiscovered (byte[] address)
		{
			if (PeerDiscovered != null)
				PeerDiscovered (this, new EventArgs<byte[]> (address));
		}

		void DataReceived (IAsyncResult ar)
		{
			var clientEp = new IPEndPoint (IPAddress.Any, 0);
			var data = _server.EndReceive (ar, ref clientEp);		

			OnPeerDiscovered (data);

			if (!_requestStop)
				_server.BeginReceive (new AsyncCallback (DataReceived), null);
		}

		public void Dispose ()
		{
			_client.Close ();
			_server.Close ();
		}
	}

You call Signal on peer as often as you want. For example:

ThreadPool.QueueUserWorkItem ((o) => {
					while (true) {
						discovery.Signal (data);
						Thread.Sleep (1000);
					}
				});

To discover peer first call StartDiscover and subscribe to event PeerDiscovered. As soon as peer discoverd you event handler would be called and you can process you data.
Keep in mind that data shouldn’t be large than udp packet size.
Good luck!