Example #1
0
 public void Broadcast(byte[] data, int period, int count)
 {
     IsBroadcasting = true;
     for (int i = 0; count < 0 ? true : i < count; i++)
     {
         foreach (var ip in
                  from address in Dns.GetHostAddresses(Dns.GetHostName())
                  where address.AddressFamily == AddressFamily.InterNetwork
                  select address)
         {
             client.BindIfNecessary(ip);
             if (data == null)
             {
                 data = new byte[0];
             }
             client.Send(data);
             if (!IsBroadcasting)
             {
                 break;
             }
             if (period > 0)
             {
                 Thread.Sleep(period);
             }
         }
         if (!IsBroadcasting)
         {
             break;
         }
     }
     IsBroadcasting = false;
 }
        public void Listen(bool sempiternally)
        {
            IsListenning = true;
            var localAddresses = new List <IPAddress>();

            foreach (var ip in
                     from address in Dns.GetHostAddresses(Dns.GetHostName())
                     where address.AddressFamily == AddressFamily.InterNetwork
                     select address)
            {
                localAddresses.Add(ip);
                client.BindIfNecessary(ip);
            }
            byte[]     data = null;
            IPEndPoint sender;

            while (IsListenning)
            {
                try
                {
                    sender = client.Receive(out data);
                }
                catch (SocketException e)
                {
                    if (e.SocketErrorCode == SocketError.TimedOut && sempiternally)
                    {
                        continue;
                    }
                    else
                    {
                        break;
                    }
                }
                if (sender == null)
                {
                    break;
                }
                else if (!localAddresses.Contains(sender.Address))
                {
                    onDataHeard(sender, data);
                }
            }
            IsListenning = false;
        }