Exemplo n.º 1
0
        public List<Peer> ResolveByPeerName(string peerName)
        {
            try
            {
                if (string.IsNullOrEmpty(peerName))
                    throw new ArgumentException("Cannot have a null or empty peer name.");

                PeerNameResolver resolver = new PeerNameResolver();
                PeerNameRecordCollection resolvedName = resolver.Resolve(new PeerName(peerName, PeerNameType.Unsecured),
                    Cloud.AllLinkLocal);
                
                List<Peer> foundPeers = new List<Peer>();
                foreach (PeerNameRecord foundItem in resolvedName)
                {
                    Peer peer = new Peer(){
                        PeerName = foundItem.PeerName.Classifier,
                        PeerHostName = foundItem.PeerName.PeerHostName,
                        Comments = foundItem.Comment
                    };

                    foundPeers.Add(peer);
                }

                return foundPeers;
            }
            catch (PeerToPeerException px)
            {
                throw new Exception(px.InnerException.Message);
            }
        }     
Exemplo n.º 2
0
        public List<PeerInfo> ResolveByPeerHostName(string peerHostName)
        {
            try
            {
                if (string.IsNullOrEmpty(peerHostName))
                    throw new ArgumentException("Cannot have a null or empty host peer name.");

                PeerNameResolver resolver = new PeerNameResolver();
                List<PeerInfo> foundPeers = new List<PeerInfo>();
                var resolvedName = resolver.Resolve(new PeerName(peerHostName, PeerNameType.Unsecured), Cloud.AllLinkLocal);                
                foreach (var foundItem in resolvedName)
                {
                    foreach (var endPointInfo in foundItem.EndPointCollection)
                    {
                        PeerInfo peerInfo = new PeerInfo(foundItem.PeerName.PeerHostName, foundItem.PeerName.Classifier,endPointInfo.Port);
                        peerInfo.Comment = foundItem.Comment;
                        foundPeers.Add(peerInfo);
                    }

                }
                return foundPeers;
               
            }
            catch (PeerToPeerException px)
            {
                throw new Exception(px.InnerException.Message);
            }

        }        
Exemplo n.º 3
0
        public PnrpManager()
        { 
             _resolver = new PeerNameResolver();

             InitializeRegistrations();
             InitializeClouds();
             this.CurrentScope = PnrpScope.All;
             
        }
Exemplo n.º 4
0
        public PeerNameResult ResolveHostName(string hostPeerName)
        {
            if (string.IsNullOrEmpty(hostPeerName))
                throw new ArgumentException("Cannot have a null or empty host peer name.");

            PeerNameResolver resolver = new PeerNameResolver();
            
            var results = resolver.Resolve(new PeerName(hostPeerName, PeerNameType.Unsecured),Cloud.Global);

            if (results == null || results.Count == 0)
                throw new PeerToPeerException(string.Format("Unable to resolve {0}", hostPeerName));

            return new PeerNameResult(results[0].PeerName.PeerHostName, results[0].EndPointCollection[0].Port);
        }
Exemplo n.º 5
0
 private void btnSearch_Click(object sender, EventArgs e)
 {
     this.richTxtSearchResult.Clear();
     PeerName searchSeed = new PeerName("0." + txtSearch.Text);
     PeerNameResolver resolver = new PeerNameResolver();
     PeerNameRecordCollection recordCollection = resolver.Resolve(searchSeed);
     foreach (PeerNameRecord record in recordCollection) {
         foreach (var endPoint in record.EndPointCollection) {
             if (endPoint.AddressFamily.Equals(AddressFamily.InterNetwork)) {
                 this.richTxtSearchResult.AppendText("\n" + endPoint.ToString() + ";" + Encoding.UTF8.GetString(record.Data));
             }
         }
     }
 }
Exemplo n.º 6
0
        public void ResolvePeerName(string peerId)
        {
            if (string.IsNullOrEmpty(_username))
            {
                throw new ArgumentNullException(nameof(_username));
            }

            System.Net.PeerToPeer.PeerNameResolver resolver = new System.Net.PeerToPeer.PeerNameResolver();
            //PeerNameResolver resolvered = new PeerNameResolver(_username);
            var result = resolver.Resolve(new PeerName(peerId, PeerNameType.Unsecured), Cloud.AllLinkLocal);
            //var resulted = resolvered.ResolvePeerName

            //if (result.Any())
            //    PeerEndPointCollection = new PeerEndPointsCollection(result[0].PeerName, result[0].EndPointCollection);
        }
        public void ResolvePeerName()
        {
            if (string.IsNullOrEmpty(_username))
            {
                throw new ArgumentNullException(nameof(_username));
            }

            System.Net.PeerToPeer.PeerNameResolver resolver = new System.Net.PeerToPeer.PeerNameResolver();
            var result = resolver.Resolve(new PeerName(_username), Cloud.AllLinkLocal);

            if (result.Any())
            {
                PeerEndPointCollection = new PeerEndPointsCollection(result[0].PeerName, result[0].EndPointCollection);
            }
        }
Exemplo n.º 8
0
        // Обновление равноправных участников
        public void RefreshHosts()
        {
            logger.Info("КТО: пользователь {0}. ЧТО: попытка обновления хостов. РЕЗУЛЬТАТ: в процессе",
                LocalPeer.DisplayString);

            // Создание распознавателя и добавление обработчиков событий
            var resolver = new PeerNameResolver();
            resolver.ResolveProgressChanged += resolver_ResolveProgressChanged;
            resolver.ResolveCompleted += resolver_ResolveCompleted;

            // Подготовка к добавлению новых пиров
            PeerList.Clear();

            // Запустить процесс преобразования незащищенных имен пиров асинхронно
            resolver.ResolveAsync(new PeerName("0.P2P_Checksum"), 1);
        }
Exemplo n.º 9
0
 public void ContineCancelCallback(object state)
 {
     Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId,
                                       "ContineCancelCallback called");
     try
     {
         if (m_CompletedOrException)
         {
             Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId,
                                               "ContinueCancelCallback detected (before acquiring lock) that another thread has already called completed event - so returning without calling cancel");
             return;
         }
         lock (m_Lock)
         {
             if (m_Cancelled)
             {
                 Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId,
                                                   "ContinueCancelCallback detected (after acquiring lock) that cancel has already been called");
                 return;
             }
             if (m_CompletedOrException)
             {
                 Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId,
                                                   "ContinueCancelCallback detected (after acquiring lock) that another thread has already called completed event - so returning without calling cancel");
                 return;
             }
             else
             {
                 Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId,
                                                   "ContinueCancelCallback is proceeding to close the handle and call the Completed callback with Cancelled = true");
             }
             m_Cancelled = true;
             m_SafePeerNameEndResolve.Dispose();
         }
         PeerNameResolver parent = m_PeerNameResolverWeakReference.Target as PeerNameResolver;
         if (parent != null)
         {
             ResolveCompletedEventArgs e = new ResolveCompletedEventArgs(null, null, true, m_AsyncOp.UserSuppliedState);
             parent.PrepareToRaiseCompletedEvent(m_AsyncOp, e);
         }
     }
     catch
     {
         Logging.P2PTraceSource.TraceEvent(TraceEventType.Critical, m_TraceEventId, "Exception while cancelling the call ");
         throw;
     }
 }
Exemplo n.º 10
0
        static void Main(string[] args)
        {
            Console.Write("Peer Classifier to Resolve: ");
            string classifier = Console.ReadLine();
            
            PeerNameResolver resolver = new PeerNameResolver();

            Console.Write("Please wait. Resolving...");

            try
            {
                //records = resolver.Resolve(new PeerName(classifier, PeerNameType.Unsecured));
                //DisplayResults();

                resolver.ResolveCompleted += new EventHandler<ResolveCompletedEventArgs>(resolver_ResolveCompleted);
                resolver.ResolveProgressChanged += new EventHandler<ResolveProgressChangedEventArgs>(resolver_ResolveProgressChanged);
                resolver.ResolveAsync(new PeerName(classifier, PeerNameType.Unsecured), Guid.NewGuid());

                while (isRunning)
                {
                    Thread.Sleep(1000);
                    //Console.Write(".");
                }

            }
            catch (PeerToPeerException ex)
            {
                Console.WriteLine("PeerToPeer Exception: {0}", ex.Message);
               
            }

            Console.WriteLine();
            Console.WriteLine("Press Enter to Exit...");
            Console.ReadLine();

            
        }
Exemplo n.º 11
0
        void Init()
        {
            StringBuilder str = new StringBuilder();
            PeerName myPeer = new PeerName("MySecurePeer", PeerNameType.Secured);
            PeerNameResolver resolver = new PeerNameResolver();
            PeerName peerName = new PeerName(classifier, PeerNameType.Secured);
            PeerNameRecordCollection results = resolver.Resolve(myPeer);

            str.AppendLine(string.Format("{0} Peers Found:", results.Count.ToString()));
            int i = 1;
       
            foreach (PeerNameRecord peer in results)
            {
                str.AppendLine(string.Format("{0} Peer:{1}", i++, peer.PeerName.ToString()));
                
                foreach (IPEndPoint ip in peer.EndPointCollection)
                {
                    str.AppendLine(string.Format("\t Endpoint: {0}, port {1}", ip.Address.ToString(),ip.Port.ToString()));
                    
                }
            }
            textBox1.Text = str.ToString();

        }
Exemplo n.º 12
0
        public void EndPointInfoAvailableCallback(object state, bool timedOut)
        {
            //------------------------------------------
            //This callback is called whenever there is an endpoint info
            //available or the resultion is completed
            //------------------------------------------
            Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId,
                                              "EndPointInfoAvailableCallback called");
            PeerNameRecord   record = null;
            SafePeerData     shEndPointInfo;
            Int32            result = 0;
            PeerNameResolver parent = null;

            if (m_Cancelled)
            {
                Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId,
                                                  "Detected that the async operation is already canceled  - before entering the lock");
                return;
            }
            lock (m_Lock)
            {
                if (m_Cancelled)
                {
                    Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId,
                                                      "Detected that the async operation is already canceled - after entering the lock");
                    return;
                }
                result = UnsafeP2PNativeMethods.PeerPnrpGetEndpoint(m_SafePeerNameEndResolve.DangerousGetHandle(), out shEndPointInfo);
                if (result != 0)
                {
                    if (result == PEER_E_NO_MORE)
                    {
                        Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId,
                                                          "Native API returned that there are no more records - resolve completed successfully");
                    }
                    m_CompletedOrException = true;
                    m_SafePeerNameEndResolve.Dispose();
                }
                else
                {
                    Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId,
                                                      "Proceeding to retrieve the endpoint information from incremental resolve");
                    try
                    {
                        unsafe
                        {
                            PEER_PNRP_ENDPOINT_INFO *pEndPointInfo = (PEER_PNRP_ENDPOINT_INFO *)shEndPointInfo.DangerousGetHandle();
                            record          = new PeerNameRecord();
                            record.PeerName = new PeerName(Marshal.PtrToStringUni(pEndPointInfo->pwszPeerName));
                            string comment = Marshal.PtrToStringUni(pEndPointInfo->pwszComment);
                            if (comment != null && comment.Length > 0)
                            {
                                record.Comment = comment;
                            }
                            if (pEndPointInfo->payLoad.cbPayload != 0)
                            {
                                record.Data = new byte[pEndPointInfo->payLoad.cbPayload];
                                Marshal.Copy(pEndPointInfo->payLoad.pbPayload, record.Data, 0, (int)pEndPointInfo->payLoad.cbPayload);
                            }
                            //record.EndPointList = new IPEndPoint[pEndPointInfo->cAddresses];
                            IntPtr ppSOCKADDRs = pEndPointInfo->ArrayOfSOCKADDRIN6Pointers;
                            for (UInt32 j = 0; j < pEndPointInfo->cAddresses; j++)
                            {
                                IntPtr pSOCKADDR = Marshal.ReadIntPtr(ppSOCKADDRs);

                                byte[] AddressFamilyBuffer = new byte[2];
                                Marshal.Copy(pSOCKADDR, AddressFamilyBuffer, 0, 2);
                                int addressFamily = 0;
#if BIGENDIAN
                                addressFamily = AddressFamilyBuffer[1] + ((int)AddressFamilyBuffer[0] << 8);
#else
                                addressFamily = AddressFamilyBuffer[0] + ((int)AddressFamilyBuffer[1] << 8);
#endif
                                byte[] buffer = new byte[((AddressFamily)addressFamily == AddressFamily.InterNetwork) ? SystemNetHelpers.IPv4AddressSize : SystemNetHelpers.IPv6AddressSize];
                                Marshal.Copy(pSOCKADDR, buffer, 0, buffer.Length);
                                IPEndPoint ipe = SystemNetHelpers.IPEndPointFromSOCKADDRBuffer(buffer);
                                record.EndPointCollection.Add(ipe);
                                ppSOCKADDRs = (IntPtr)((long)ppSOCKADDRs + Marshal.SizeOf(typeof(IntPtr)));
                            }
                        }
                    }
                    finally
                    {
                        shEndPointInfo.Dispose();
                    }
                    record.TracePeerNameRecord();
                    m_PeerNameRecordCollection.Add(record);

                    ResolveProgressChangedEventArgs resolveProgressChangedEventArgs = new ResolveProgressChangedEventArgs(
                        record, m_AsyncOp.UserSuppliedState);


                    Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId,
                                                      "Proceeding to call progress changed event callback");
                    parent = m_PeerNameResolverWeakReference.Target as PeerNameResolver;
                    if (parent != null)
                    {
                        parent.PrepareToRaiseProgressChangedEvent(m_AsyncOp, resolveProgressChangedEventArgs);
                    }
                    return;
                }
            }

            ResolveCompletedEventArgs resolveCompletedEventArgs;
            if (result == PEER_E_NO_MORE)
            {
                resolveCompletedEventArgs = new ResolveCompletedEventArgs(m_PeerNameRecordCollection,
                                                                          null, false, m_AsyncOp.UserSuppliedState);
            }
            else
            {
                PeerToPeerException ex = PeerToPeerException.CreateFromHr(SR.GetString(SR.Pnrp_ExceptionWhileResolvingAPeerName), result);
                Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId,
                                                  "Exception occurred when the native API is called to harvest an incremental resolve notification");
                resolveCompletedEventArgs = new ResolveCompletedEventArgs(null,
                                                                          ex, false, m_AsyncOp.UserSuppliedState);
            }
            parent = m_PeerNameResolverWeakReference.Target as PeerNameResolver;
            if (parent != null)
            {
                Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId,
                                                  "Proceeding to call the ResolveCompleted callback");
                parent.PrepareToRaiseCompletedEvent(m_AsyncOp, resolveCompletedEventArgs);
            }
            return;
        }
Exemplo n.º 13
0
 internal PeerNameResolverHelper(PeerName peerName, Cloud cloud, int MaxRecords, object userState, PeerNameResolver parent, int NewTraceEventId)
 {
     m_userState  = userState;
     m_PeerName   = peerName;
     m_Cloud      = cloud;
     m_MaxRecords = MaxRecords;
     m_PeerNameResolverWeakReference = new WeakReference(parent);
     m_TraceEventId = NewTraceEventId;
     Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId, "New PeerNameResolverHelper created with TraceEventID {0}", m_TraceEventId);
     Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId,
                                       "\tPeerName: {0}, Cloud: {1}, MaxRecords: {2}, userState {3}, ParentReference {4}",
                                       m_PeerName,
                                       m_Cloud,
                                       m_MaxRecords,
                                       userState.GetHashCode(),
                                       m_PeerNameResolverWeakReference.Target.GetHashCode()
                                       );
 }
Exemplo n.º 14
0
        // 搜索资源
        private void btnSearch_Click(object sender, EventArgs e)
        {
            if (tbxSeed.Text == "")
            {
                MessageBox.Show("请先输入要寻找的种子资源名", "提示");
                return;
            }

            lstViewOnlinePeer.Items.Clear();
            // 初始化要搜索的资源名
            PeerName searchSeed = new PeerName("0." + tbxSeed.Text);
            // PeerNameResolver类是将节点名解析为PeerNameRecord的值(即将通过资源名来查找资源名所在的地址,包括IP地址和端口号)
            // PeerNameRecord用来定于云中的各个节点
            PeerNameResolver myresolver = new PeerNameResolver();

            // PeerNameRecordCollection表示PeerNameRecord元素的容器
            // Resolve方法是同步的完成解析
            // 使用同步方法可能会出现界面“假死”现象
            // 解决界面假死现象可以采用多线程或异步的方式
            // 关于多线程的知识可以参考本人博客中多线程系列我前面UDP编程中有所使用
            // 在这里就不列出多线程的使用了,朋友可以自己实现,如果有问题可以留言给我一起讨论
            PeerNameRecordCollection recordCollection = myresolver.Resolve(searchSeed);
            foreach (PeerNameRecord record in recordCollection)
            {
                foreach(IPEndPoint endpoint in record.EndPointCollection)
                {
                    if (endpoint.AddressFamily.Equals(AddressFamily.InterNetwork))
                    {
                        ListViewItem item = new ListViewItem();
                        item.SubItems.Add(endpoint.ToString());
                        item.SubItems.Add(Encoding.UTF8.GetString(record.Data));
                        lstViewOnlinePeer.Items.Add(item);
                    }
                }
            }
        }
Exemplo n.º 15
0
 public void CancelLookup(PeerName peerName)
 {
     _resolver = new PeerNameResolver();
     _resolver.ResolveAsyncCancel(peerName);
 }
Exemplo n.º 16
0
        private void RefreshButton_Click(object sender, RoutedEventArgs e)
        {
            // Создание распознавателя и добавление обработчиков событий
            PeerNameResolver resolver = new PeerNameResolver();
            resolver.ResolveProgressChanged +=
                new EventHandler<ResolveProgressChangedEventArgs>(resolver_ResolveProgressChanged);
            resolver.ResolveCompleted +=
                new EventHandler<ResolveCompletedEventArgs>(resolver_ResolveCompleted);

            // Подготовка к добавлению новых пиров
            PeerList.Items.Clear();
            RefreshButton.IsEnabled = false;

            // Преобразование незащищенных имен пиров асинхронным образом
            resolver.ResolveAsync(new PeerName("0.P2P Sample"), 1);
        }
Exemplo n.º 17
0
 internal PeerNameResolverHelper(PeerName peerName, Cloud cloud, int MaxRecords, object userState, PeerNameResolver parent, int NewTraceEventId)
 {
     m_userState = userState;
     m_PeerName = peerName;
     m_Cloud = cloud;
     m_MaxRecords = MaxRecords;
     m_PeerNameResolverWeakReference = new WeakReference(parent);
     m_TraceEventId = NewTraceEventId;
     Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId, "New PeerNameResolverHelper created with TraceEventID {0}", m_TraceEventId);
     Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId,
         "\tPeerName: {0}, Cloud: {1}, MaxRecords: {2}, userState {3}, ParentReference {4}",
         m_PeerName, 
         m_Cloud, 
         m_MaxRecords, 
         userState.GetHashCode(), 
         m_PeerNameResolverWeakReference.Target.GetHashCode()
         );
 }
Exemplo n.º 18
0
        public void LookupRegistrationAsync(PeerName peerName, EventHandler<ResolveProgressChangedEventArgs> progressChanged, EventHandler<ResolveCompletedEventArgs> completed)
        {
            if (peerName == null)
                throw new ArgumentException("Cannot have null PeerName");


            _resolver = new PeerNameResolver();

            _resolver.ResolveCompleted += new EventHandler<ResolveCompletedEventArgs>(completed);
            _resolver.ResolveProgressChanged += new EventHandler<ResolveProgressChangedEventArgs>(progressChanged);
            Debug.WriteLine(string.Format("Resolving: {0}", peerName.ToString()));
            _resolver.ResolveAsync(peerName, peerName);

        }