Пример #1
0
        private void UdpRecieveLoop(IAsyncResult result)
        {
            try
            {
                _udpClient.BeginReceive(UdpRecieveLoop, null);
            }
            catch
            {
                //On disposed
                return;
            }

            try
            {
                IPEndPoint remote = null;
                var        data   = _udpClient.EndReceive(result, ref remote);

                if (remote == null || data == null || data.Length == 0)
                {
                    return;
                }

                using (var mem = new MemoryStream(data))
                {
                    var bin    = new BinaryReader(mem);
                    var add    = bin.ReadBoolean();
                    var pubKey = bin.ReadBytes(bin.ReadInt32());

                    if (pubKey.Compare(PublicKey) || !TrustVerifier.VerifyTrust(pubKey))
                    {
                        return;
                    }

                    var peer = new PhonemePeer(this, pubKey, new IPEndPoint(remote.Address, NetworkPort));
                    if (add)
                    {
                        if (!_knownPeersSet.Contains(peer))
                        {
                            _knownPeersSet.Add(peer);
                            Application.Current.Dispatcher.Invoke(() => KnownPeers.Add(peer));
                            PeerJoin?.Invoke(peer);
                        }
                        peer.PerformTcpHandshake();
                    }
                    else
                    {
                        if (!_knownPeersSet.Remove(peer))
                        {
                            return;
                        }

                        var realPeer = KnownPeers.First(x => x.Equals(peer));
                        Application.Current.Dispatcher.Invoke(() => KnownPeers.Remove(realPeer));
                        PeerLeave?.Invoke(realPeer);
                    }
                }
            }
            catch (Exception e)
            {
                //Some kind of noise? Ignore this.
                Debug.WriteLine(e);
            }
        }