Beispiel #1
0
        /// <summary>
        /// Creates a PeerName and registers it along with the metadata specified as command line arguments
        /// </summary>
        private static void CreateAndPublishPeerName()
        {
            try{
                // Creates a the PeerName to register using the classifier and type provided on the command line
                PeerName peerName = new PeerName(peerNameClassifier, peerNameType);

                // Create a registration object which represents the registration of the PeerName in a Cloud
                PeerNameRegistration peerNameRegistration = new PeerNameRegistration();
                peerNameRegistration.PeerName = peerName;
                peerNameRegistration.Port     = portNumber;
                peerNameRegistration.Comment  = comment;
                peerNameRegistration.Cloud    = cloudName;
                // Since the peerNameRegistration.EndPointCollection is not specified, all (IPv4&IPv6)
                // addresses assigned to the local host will automatically be assocaited with the
                // peerNameRegistration instance.  This behavior can be control via peerNameRegistration.UseAutoEndPointSelection

                //Note: Additional information may be specified on the PeerNameRegistration object, which is not shown in this example.

                //Starting the registration means the name is published for other peers to resolve
                peerNameRegistration.Start();
                Console.WriteLine("Registration of Peer Name: {0} complete.", peerName.ToString(), cloudName);
                Console.WriteLine();

                Console.WriteLine("Press any key to stop the registration and close the program");
                Console.ReadKey();

                // Stopping the registration means the name is no longer published
                peerNameRegistration.Stop();
            } catch (Exception e) {
                Console.WriteLine("Error creating and registering the PeerName: {0} \n", e.Message);
                Console.WriteLine(e.StackTrace);
            }
        }
Beispiel #2
0
        public List <NetworkHost> Find(string name)
        {
            if (type != NetworkTypes.Client)
            {
                throw new Exception("Only allowed for client!");
            }

            var hosts = new List <NetworkHost>();

            peerNameResolver = new PeerNameResolver();
            peerName         = new PeerName(name, PeerNameType.Unsecured);
            var results = peerNameResolver.Resolve(peerName);

            foreach (var record in results)
            {
                var host = new NetworkHost(record.Comment);
                foreach (var endpoint in record.EndPointCollection)
                {
                    if (endpoint.AddressFamily == AddressFamily.InterNetwork)
                    {
                        Console.WriteLine(string.Format("Found EndPoint {0}:{1}", endpoint.Address, endpoint.Port));
                        host.endpoints.Add(endpoint);
                    }
                }

                if (host.endpoints.Count != 0)
                {
                    hosts.Add(host);
                }
            }

            return(hosts);
        }
Beispiel #3
0
        public PeerNameRegistration RegisterPeer(PeerName peerName, int port)
        {
            var peerNameRegistration = new PeerNameRegistration(peerName, port);

            peerNameRegistration.Start();
            return(peerNameRegistration);
        }
        private void btn_RegisterPeer_Click(object sender, RoutedEventArgs e)
        {
            PeerName peerName = new PeerName(txt_PeerName.Text, PeerNameType.Unsecured);

            using (PeerNameRegistration registration = new PeerNameRegistration(peerName, Int32.Parse(txt_Port.Text)))
            {
                registration.Comment = "My Comment";
                string          time    = string.Format("Peer Created at: {0}", DateTime.Now.ToString());
                UnicodeEncoding encoder = new UnicodeEncoding();
                byte[]          data    = encoder.GetBytes(time);

                try
                {
                    foreach (Cloud c in Cloud.GetAvailableClouds())
                    {
                        Console.WriteLine($"Cloud {c.Name}");
                    }
                    registration.Start();
                    Console.WriteLine("Registered");
                    Console.ReadLine();
                    //registration.Stop();
                }
                catch (PeerToPeerException ex)
                {
                    // There are other possible statndard exceptions to catch
                    // See documentation on for details
                }
            }
        }
Beispiel #5
0
        internal void Init()
        {
            // Creates a secure (not spoofable) PeerName
            //peerName = new PeerName(Application.ProductName, PeerNameType.Secured);
            peerName       = new PeerName(Application.ProductName + "." + Application.CompanyName, PeerNameType.Secured);
            pnReg          = new PeerNameRegistration();
            pnReg.PeerName = peerName;

            pnReg.Port = (int)Config.Port;

            // OPTIONAL

            // The properties set below are optional.
            // You can register a PeerName without setting these properties
            // but this properties can help identify PC
            pnReg.Comment = "up to 39 unicode char comment";
            pnReg.Data    = Encoding.UTF8.GetBytes("A data blob associated with the name"); // @TODO Add binary data for Peer2Peer Netwwork

            // OPTIONAL
            // The properties below are also optional, but will not be set (ie. are commented out) for this example

            //pnReg.IPEndPointCollection = // a list of all {IPv4/v6 address, port} pairs to associate with the peername
            //pnReg.Cloud = //the scope in which the name should be registered (local subnet, internet, etc)
            //pnReg.Cloud = Cloud.Global; // resolve in Global Network -
            pnReg.Cloud = Cloud.Global; // resolve in Global Network -
        }
Beispiel #6
0
        static void Main(string[] args)
        {
            try
            {
                if (args.Length != 1)
                {
                    Console.WriteLine("Usage: PeerNameResolver.exe <PeerNameToResolve>");
                    return;
                }

                // create a resolver object to resolve a Peer Name that was previously published
                PeerNameResolver resolver = new PeerNameResolver();
                // The Peer Name to resolve must be passed as the first command line argument to the application
                PeerName peerName = new PeerName(args[0]);
                // resolve the Peer Name - this is a network operation and will block until the resolve completes
                PeerNameRecordCollection results = resolver.Resolve(peerName);

                // Display the data returned by the resolve operation
                Console.WriteLine("Resolve operation complete.\n", peerName);
                Console.WriteLine("Results for PeerName: {0}", peerName);
                Console.WriteLine();

                int count = 1;
                foreach (PeerNameRecord record in results)
                {
                    Console.WriteLine("Record #{0} results...", count);

                    Console.Write("Comment:");
                    if (record.Comment != null)
                    {
                        Console.Write(record.Comment);
                    }
                    Console.WriteLine();

                    Console.Write("Data:");
                    if (record.Data != null)
                    {
                        //Assumes the data blob associated with the PeerName is made up of ASCII characters
                        Console.Write(System.Text.Encoding.ASCII.GetString(record.Data));
                    }
                    Console.WriteLine();

                    Console.WriteLine("Endpoints:");
                    foreach (IPEndPoint endpoint in record.EndPointCollection)
                    {
                        Console.WriteLine("\t Endpoint:{0}", endpoint);
                        Console.WriteLine();
                    }

                    count++;
                }

                Console.ReadKey();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error occured while attempting to resolve the PeerName: {0}", e.Message);
                Console.WriteLine(e.StackTrace);
            }
        }
Beispiel #7
0
 public PeerEntry(PeerName peerName, IPeerToPeerService serviceProxy, string displayString, bool buttonsEnabled)
 {
     PeerName       = peerName;
     ServiceProxy   = serviceProxy;
     DisplayString  = displayString;
     ButtonsEnabled = buttonsEnabled;
 }
Beispiel #8
0
 /// <summary>
 /// 将PNRP Name 注册到Cloud中
 /// </summary>
 public static bool registerPeer(String strMyPeerName)
 {
     try
     {
         PeerName peerName = new PeerName(strMyPeerName, PeerNameType.Unsecured);
         // 以PeerName创建PeerNameRegistration实例
         peerNameRegistration = new PeerNameRegistration(peerName, port);
         //    peerNameRegistration.PeerName = peerName;
         //IPEndPointCollection ipEndPoints = new IPEndPointCollection();
         peerNameRegistration.UseAutoEndPointSelection = true;
         // 设定PNRP Peer Name的其他描述信息
         peerNameRegistration.Comment = "PNRP Peer Name的其他描述信息";
         // 设定用PeerNameRegistration的Data描述信息
         peerNameRegistration.Data = System.Text.Encoding.UTF8.GetBytes(String.Format("描述信息,注册时间{0}", DateTime.Now.ToString()));
         // 设定用户端或Peer端点目前参与的所有连接本机的PNRP群
         // peerNameRegistration.Cloud = Cloud.AllLinkLocal;
         // 将PNRP Peer Name注册至PNRP Cloud中
         //  strAllMyPeerName = peerName.ToString();
         peerNameRegistration.Start();
         return(true);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.ToString());
         return(false);
     }
 }
Beispiel #9
0
        public void Start(string peerClassifier, int port)
        {
            PeerName peerName = new PeerName(peerClassifier, PeerNameType.Unsecured);

            _peerNameRegistration = new PeerNameRegistration(peerName, port, Cloud.Global);
            _peerNameRegistration.Start();
        }
Beispiel #10
0
        public void registerPeerName(string classifier)
        {
            PeerName peerName = new PeerName(classifier, PeerNameType.Unsecured);

            using (PeerNameRegistration registration = new PeerNameRegistration(peerName, 8080))
            {
                string timestamp = string.Format("Peer Created at: {0}", DateTime.Now.ToShortTimeString());

                registration.Comment = timestamp;

                UnicodeEncoding encoder = new UnicodeEncoding();
                byte[]          data    = encoder.GetBytes(timestamp);
                registration.Data = data;
                try
                {
                    registration.Start();
                    mRegistration = registration;
                    _stopFlag.WaitOne();
                }
                catch (PeerToPeerException ex)
                {
                    Console.WriteLine("PeerToPeer Exception: {0}", ex.Message);
                }
            }
        }
Beispiel #11
0
        private PeerName GetInputPeerName()
        {
            if (IsTargetGrobal())
            {
                string peerHostName = GetInputPeerHostName();
                if (string.IsNullOrWhiteSpace(peerHostName))
                {
                    MessageBox.Show(labelPeerHostName.Text + "を入力してください。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    tabControl1.SelectedTab = tabPageSetting;
                    textBoxPeerHostName.SelectAll();
                    textBoxPeerHostName.Focus();
                    return(null);
                }

                return(PeerName.CreateFromPeerHostName(peerHostName));
            }
            else
            {
                string classifier = GetInputClassifier();
                if (string.IsNullOrWhiteSpace(classifier))
                {
                    MessageBox.Show(labelClassifier.Text + "を入力してください。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    tabControl1.SelectedTab = tabPageSetting;
                    textBoxClassifier.SelectAll();
                    textBoxClassifier.Focus();
                    return(null);
                }

                return(new PeerName(classifier, GetSelectedPeerNameType()));
            }
        }
Beispiel #12
0
        public PeerNameRegistration CreateRegistration(PeerName peerName, int port)
        {
            if (peerName == null)              // in most cases, have a null peername does not make a lot of sense
            {
                throw new ArgumentException("Cannot have null or empty peerName");
            }

            Cloud regCloud;

            switch (_currerntScope)
            {
            case PnrpScope.Global:
                regCloud = Cloud.Global;
                break;

            case PnrpScope.LinkLocal:
                regCloud = Cloud.AllLinkLocal;
                break;

            default:
                regCloud = Cloud.Available;
                break;
            }

            PeerNameRegistration registration = new PeerNameRegistration(peerName, port, regCloud);

            registration.Comment = "Comment for " + peerName.Classifier;

            registration.Start();
            _registrations.Add(registration);
            SetScopedRegistrations(this.CurrentScope);
            ProcessRegistrations(this.CurrentScope);
            return(registration);
        }
Beispiel #13
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            // Получение конфигурационной информации из app.config
            string port        = ConfigurationManager.AppSettings["port"];
            string username    = ConfigurationManager.AppSettings["username"];
            string machineName = Environment.MachineName;
            string serviceUrl  = null;

            // Установка заголовка окна
            this.Title = string.Format("P2P приложение - {0}", username);

            //  Получение URL-адреса службы с использованием адресаIPv4
            //  и порта из конфигурационного файла
            foreach (IPAddress address in Dns.GetHostAddresses(Dns.GetHostName()))
            {
                if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    serviceUrl = string.Format("net.tcp://{0}:{1}/P2PService", address, port);
                    break;
                }
            }

            // Выполнение проверки, не является ли адрес null
            if (serviceUrl == null)
            {
                // Отображение ошибки и завершение работы приложения
                MessageBox.Show(this, "Не удается определить адрес конечной точки WCF.", "Networking Error",
                                MessageBoxButton.OK, MessageBoxImage.Stop);
                Application.Current.Shutdown();
            }

            // Регистрация и запуск службы WCF
            localService = new P2PService(this, username);
            host         = new ServiceHost(localService, new Uri(serviceUrl));
            NetTcpBinding binding = new NetTcpBinding();

            binding.Security.Mode = SecurityMode.None;
            host.AddServiceEndpoint(typeof(IP2PService), binding, serviceUrl);
            try
            {
                host.Open();
            }
            catch (AddressAlreadyInUseException)
            {
                // Отображение ошибки и завершение работы приложения
                MessageBox.Show(this, "Не удается начать прослушивание, порт занят.", "WCF Error",
                                MessageBoxButton.OK, MessageBoxImage.Stop);
                Application.Current.Shutdown();
            }

            // Создание имени равноправного участника (пира)
            peerName = new PeerName("P2P Sample", PeerNameType.Unsecured);

            // Подготовка процесса регистрации имени равноправного участника в локальном облаке
            peerNameRegistration       = new PeerNameRegistration(peerName, int.Parse(port));
            peerNameRegistration.Cloud = Cloud.AllLinkLocal;

            // Запуск процесса регистрации
            peerNameRegistration.Start();
        }
Beispiel #14
0
        private static void Main(string[] args)
        {
            // Creates a secure (not spoofable) PeerName
            var peerName = new PeerName("MikesWebServer", PeerNameType.Secured);
            var pnReg    = new PeerNameRegistration {
                PeerName = peerName,
                Port     = 80,
                //OPTIONAL
                //The properties set below are optional.  You can register a PeerName without setting these properties
                Comment = "up to 39 unicode char comment",
                Data    = Encoding.UTF8.GetBytes("A data blob associated with the name")
            };

            /*
             * OPTIONAL
             * The properties below are also optional, but will not be set (ie. are commented out) for this example
             * pnReg.IPEndPointCollection = // a list of all {IPv4/v6 address, port} pairs to associate with the peername
             * pnReg.Cloud = //the scope in which the name should be registered (local subnet, internet, etc)
             */

            //Starting the registration means the name is published for others to resolve
            pnReg.Start();
            Console.WriteLine("Registration of Peer Name: {0} complete.", peerName);
            Console.WriteLine();
            Console.WriteLine("Press any key to stop the registration and close the program");
            Console.ReadKey();

            pnReg.Stop();
        }
Beispiel #15
0
        private static PeerNameRecordCollection Resolve(string serviceName)
        {
            var resolver = new PeerNameResolver();
            var peerName = new PeerName(serviceName, PeerNameType.Unsecured);

            return(resolver.Resolve(peerName));
        }
Beispiel #16
0
        private void btnResolve_Click(object sender, RoutedEventArgs e)
        {
            if (txtPeerName.Text.Length > 0)
            {
                // 建立PeerName物件
                PeerName peerName = new PeerName(txtPeerName.Text);

                // 建立PeerNameResolver物件
                PeerNameResolver resolver = new PeerNameResolver();

                // 將PNRP Peer Name解析為PNRP Peer Name記錄物件
                PeerNameRecordCollection pmrcs = resolver.Resolve(peerName);

                if (pmrcs.Count > 0)
                {
                    lstPeerNameRecord.Items.Clear();
                }
                else
                {
                    MessageBox.Show("No Peer Name Record Found", "Peer Name Resolver", MessageBoxButton.OK, MessageBoxImage.Error);
                }

                foreach (PeerNameRecord pmrc in pmrcs)
                {
                    foreach (IPEndPoint endpoint in pmrc.EndPointCollection)
                    {
                        lstPeerNameRecord.Items.Add(endpoint);
                    }
                }
            }
            else
            {
                MessageBox.Show("Please enter Peer Name.", "Peer Name Resolver", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Beispiel #17
0
        private void btnResolve_Click(object sender, RoutedEventArgs e)
        {
            if (txtPeerName.Text.Length > 0)
            {
                // 建立PeerName物件
                PeerName peerName = new PeerName(txtPeerName.Text);

                // 建立PeerNameResolver物件
                PeerNameResolver resolver = new PeerNameResolver();

                // 宣告非同步解析作業正在執行中所觸發之事件
                // 並定義所呼叫的方法為ResolveProgressChangedCallback
                resolver.ResolveProgressChanged += new EventHandler <ResolveProgressChangedEventArgs>(ResolveProgressChangedCallback);

                // 宣告非同步解析作業完成時所觸發之事件
                // 並定義所呼叫的方法為ResolveCompletedCallback
                resolver.ResolveCompleted += new EventHandler <ResolveCompletedEventArgs>(ResolveCompletedCallback);

                lstPeerNameRecord.Items.Clear();
                progressBar.Visibility = Visibility.Visible;

                // 非同步將PNRP Peer Name解析為PNRP Peer Name記錄物件
                resolver.ResolveAsync(peerName, 1);
            }
            else
            {
                MessageBox.Show("Please enter Peer Name.", "Peer Name Resolver", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Beispiel #18
0
        private void btnRegister_Click(object sender, RoutedEventArgs e)
        {
            if (txtPeerName.Text.Length > 0 && txtPort.Text.Length > 0)
            {
                // 建立PeerName物件
                // 設定PNRP Peer Name為未受保護的名稱
                PeerName peerName = new PeerName(txtPeerName.Text, PeerNameType.Unsecured);

                // 以PNRP Peer Name與通訊埠建立PeerNameRegistration物件
                peerNameRegistration = new PeerNameRegistration(peerName, Int32.Parse(txtPort.Text));

                // 設定PNRP Peer Name的其他資訊
                peerNameRegistration.Comment = "PNRP Peer Name的其他資訊";
                // 設定PeerNameRegistration物件之二進位資料
                peerNameRegistration.Data = System.Text.Encoding.UTF8.GetBytes("二進位資料");

                // 設定用戶端或Peer端點目前參與的所有連結本機之PNRP Cloud
                peerNameRegistration.Cloud = Cloud.AllLinkLocal;
                // 設定是否自動選取IP位址和通訊埠
                peerNameRegistration.UseAutoEndPointSelection = true;
                // 將PNRP Peer Name註冊至PNRP Cloud中
                peerNameRegistration.Start();
            }
            else
            {
                MessageBox.Show("Please enter Peer Name and Port.", "P2P", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
        {
            // Получение конфигурационной информации из App.config
            string port        = ConfigurationManager.AppSettings["port"];
            string username    = ConfigurationManager.AppSettings["username"];
            string machineName = Environment.MachineName;

            // Установка заголовка окна
            Title = string.Format("{0}: P2P example - {1}", machineName, username);

            // Получение URL-адреса службы с использованием адреса IPv4 и порта из конфигурационного файла
            string serviceUrl = Dns.GetHostAddresses(Dns.GetHostName())
                                .Where(address => address.AddressFamily == AddressFamily.InterNetwork)
                                .Select(address => string.Format("net.tcp://{0}:{1}/PeerToPeerService", address, port))
                                .FirstOrDefault();

            // Выполнение проверки, не является ли адрес нулевым
            if (serviceUrl == null)
            {
                // Отображение ошибки и завершение работы приложения
                MessageBox.Show(this, "Unable to determine WCF endpoint.", "Networking Error", MessageBoxButton.OK,
                                MessageBoxImage.Stop);
                Application.Current.Shutdown();
                return;
            }

            // Регистрация и запуск службы WCF
            _localService = new PeerToPeerService(this, username);
            _host         = new ServiceHost(_localService, new Uri(serviceUrl));
            var binding = new NetTcpBinding {
                Security = { Mode = SecurityMode.None }
            };

            _host.AddServiceEndpoint(typeof(IPeerToPeerService), binding, serviceUrl);

            try
            {
                _host.Open();
            }
            catch (AddressAlreadyInUseException)
            {
                // Отображение ошибки и завершение работы приложения
                MessageBox.Show(this, "Cannot start listening, port in use", "WCF Error", MessageBoxButton.OK,
                                MessageBoxImage.Stop);
                Application.Current.Shutdown();
            }

            // Создание имени равноправного участника
            _peerName = new PeerName("P2P Sample", PeerNameType.Unsecured);

            // Подготовка регистрации имени равноправного участника в облаке локального соединения
            _peerNameRegistration = new PeerNameRegistration(_peerName, int.Parse(port))
            {
                Cloud = Cloud.AllLinkLocal
            };

            // Начало регистрации
            _peerNameRegistration.Start();
        }
Beispiel #20
0
        public PeerNameResolver ResolvePeerName(PeerName peerName)
        {
            var peerNameResolver = new PeerNameResolver();

            peerNameResolver.ResolveCompleted += peerNameResolver_ResolveCompleted;
            peerNameResolver.ResolveAsync(peerName, Guid.NewGuid());
            return(peerNameResolver);
        }
Beispiel #21
0
        public static void RegisterNodeInPNRP(Cloud cloud = null)
        {
            PeerName name = new PeerName(DeNSo.Configuration.NodeIdentity.ToString(), PeerNameType.Secured);

            _peerNameRegistration       = new PeerNameRegistration(name, DeNSo.Configuration.Extensions.P2P().NetworkPort);
            _peerNameRegistration.Cloud = cloud ?? Cloud.Available;
            _peerNameRegistration.Start();
        }
        protected PeerNameRecord(SerializationInfo info, StreamingContext context)
        {
            m_Comment = info.GetString("_Comment");
            m_Data = info.GetValue("_Data", typeof(byte[])) as byte[];
            m_EndPointCollection = info.GetValue("_EndpointList", typeof(IPEndPointCollection)) as IPEndPointCollection;
            m_PeerName  = info.GetValue("_PeerName", typeof(PeerName)) as PeerName;

        }
Beispiel #23
0
        public PNRPManager(string classifierName, int port)
        {
            this.ClassifierName = classifierName;
            this.Port = port;

            PeerName peer = new PeerName(classifierName, PeerNameType.Unsecured);
            registration = new PeerNameRegistration(peer, port, Cloud.AllLinkLocal) { UseAutoEndPointSelection = true};
        }
Beispiel #24
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                var port     = ConfigurationManager.AppSettings["port"];
                var username = ConfigurationManager.AppSettings["username"];

                Title = $"P2P приложение - {username}";

                var dns = Dns.GetHostAddresses(Dns.GetHostName());

                var url = (from address in dns
                           where address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork
                           select $"net.tcp://{address}:{port}/P2PService").FirstOrDefault();

                MessageBox.Show(url);

                if (url == null)
                {
                    MessageBox.Show(this, "Не удается определить адрес конечной точки WCF.", "Networking Error",
                                    MessageBoxButton.OK, MessageBoxImage.Stop);
                    Application.Current.Shutdown();
                }

                _service = new P2PService(this, username);
                _host    = new ServiceHost(_service, new Uri(url));
                var binding = new NetTcpBinding {
                    Security = { Mode = SecurityMode.None }
                };
                _host.AddServiceEndpoint(typeof(IP2PService), binding, url);

                try
                {
                    _host.Open();
                }
                catch (AddressAlreadyInUseException)
                {
                    MessageBox.Show(this, "Не удается начать прослушивание, порт занят.", "WCF Error",
                                    MessageBoxButton.OK, MessageBoxImage.Stop);
                    Application.Current.Shutdown();
                }

                _pn  = new PeerName("0.P2P Sample");
                _pnr = new PeerNameRegistration(_pn, int.Parse(port))
                {
                    Cloud   = Cloud.Available,
                    Comment = "Simple p2p app untitled"
                };

                _pnr.Start();
                MessageBox.Show("Started!");
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
                MessageBox.Show(exception.StackTrace);
            }
        }
Beispiel #25
0
        public PeerNameRecordCollection LookupRegistration(PeerName peerName)
        {
            if (peerName == null)
            {
                throw new ArgumentException("Cannot have null or empty peerName");
            }

            return(_resolver.Resolve(peerName));
        }
Beispiel #26
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            // Get configuration from app.config
            string port        = ConfigurationManager.AppSettings["port"];
            string username    = ConfigurationManager.AppSettings["username"];
            string machineName = Environment.MachineName;
            string serviceUrl  = null;

            // Set window title
            this.Title = string.Format("P2P example - {0}", username);

            // Get service url using IPv4 address and port from config file
            foreach (IPAddress address in Dns.GetHostAddresses(Dns.GetHostName()))
            {
                if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    serviceUrl = string.Format("net.tcp://{0}:{1}/P2PService", address, port);
                    break;
                }
            }

            // Check for null address
            if (serviceUrl == null)
            {
                // Display error and shutdown
                MessageBox.Show(this, "Unable to determine WCF endpoint.", "Networking Error", MessageBoxButton.OK, MessageBoxImage.Stop);
                Application.Current.Shutdown();
            }

            // Register and start WCF service.
            localService = new P2PService(this, username);
            host         = new ServiceHost(localService, new Uri(serviceUrl));
            NetTcpBinding binding = new NetTcpBinding();

            binding.Security.Mode = SecurityMode.None;
            host.AddServiceEndpoint(typeof(IP2PService), binding, serviceUrl);
            try
            {
                host.Open();
            }
            catch (AddressAlreadyInUseException)
            {
                // Display error and shutdown
                MessageBox.Show(this, "Cannot start listening, port in use.", "WCF Error", MessageBoxButton.OK, MessageBoxImage.Stop);
                Application.Current.Shutdown();
            }

            // Create peer name
            peerName = new PeerName("P2P Sample", PeerNameType.Unsecured);

            // Prepare peer name registration in link local clouds
            peerNameRegistration       = new PeerNameRegistration(peerName, int.Parse(port));
            peerNameRegistration.Cloud = Cloud.AllLinkLocal;

            // Start registration
            peerNameRegistration.Start();
        }
Beispiel #27
0
        /// <summary>
        /// コンストラクタ
        /// </summary>
        /// <param name="cloud">対象となるネットワーク</param>
        /// <param name="peerName">登録ピア名</param>
        public Resolver(Cloud cloud, PeerName peerName)
        {
            this.cloud    = cloud;
            this.peerName = peerName;

            peerNameResolver = new PeerNameResolver();
            peerNameResolver.ResolveProgressChanged += Pnr_ResolveProgressChanged;
            peerNameResolver.ResolveCompleted       += Pnr_ResolveCompleted;
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //get config from app.config
            string port       = ConfigurationManager.AppSettings["port"];
            string username   = ConfigurationManager.AppSettings["username"];
            string serviceUrl = null;

            // set form title
            this.Title = string.Format($"P2P node - {username}");

            //get url-address of service using Ipv4 and port from app config
            foreach (IPAddress address in Dns.GetHostAddresses(Dns.GetHostName()))
            {
                if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    serviceUrl = string.Format($"net.tcp://{address}:{port}/P2PService");
                    break;
                }
            }

            // check if address is not null
            if (serviceUrl == null)
            {
                MessageBox.Show(this, "Can not define service address WCF.", "Networking Error",
                                MessageBoxButton.OK, MessageBoxImage.Stop);
                Application.Current.Shutdown();
            }

            // registration and run WCF
            _localService = new P2PService(this, username);
            _host         = new ServiceHost(_localService, new Uri(serviceUrl ?? throw new InvalidOperationException()));
            NetTcpBinding binding = new NetTcpBinding();

            binding.Security.Mode = SecurityMode.None;
            _host.AddServiceEndpoint(typeof(IP2PService), binding, serviceUrl);
            try
            {
                _host.Open();
            }
            catch (AddressAlreadyInUseException)
            {
                MessageBox.Show(this, "Can not listen, the port is busy", "WCF Error",
                                MessageBoxButton.OK, MessageBoxImage.Stop);
                Application.Current.Shutdown();
            }

            // Create peer name
            peerName = new PeerName("P2P Sample", PeerNameType.Unsecured);

            // get ready to register participant in the local cloud
            _peerNameRegistration = new PeerNameRegistration(peerName, int.Parse(port))
            {
                Cloud = Cloud.AllLinkLocal
            };
            // run registration
            _peerNameRegistration.Start();
        }
 public PNRPManager(string classifierName, int port)
 {
     this.ClassifierName = classifierName;
     this.Port= port;
     peerName = new PeerName(classifierName, PeerNameType.Unsecured);
     registrations = new List<PeerNameRegistration>();
     registrations.Add(new PeerNameRegistration(peerName, this.Port, Cloud.AllLinkLocal) { UseAutoEndPointSelection=true });
     //registrations.Add(new PeerNameRegistration(peerName, this.Port, Cloud.Global) { UseAutoEndPointSelection = true });
 }
Beispiel #30
0
        private void CreatePeer()
        {
            _peerName           = new PeerName(PEER_CLASSIFIER, PeerNameType.Unsecured);
            _registration       = new PeerNameRegistration(_peerName, _port);
            _registration.Cloud = Cloud.AllLinkLocal;

            // connect to peer cloud
            _registration.Start();
        }
        protected override void InitializeCommands()
        {
            this.CreateRegistrationCommand = new PresenterCommand()
            {
                CanExecuteDelegate = code => PeerClassifier.Length > 0,
                ExecuteDelegate = code =>
                {
                    PeerName name = new PeerName(this.PeerClassifier,_peerNameType);

                    try
                    {
                        _service.CreateRegistration(name, 8080);
                    }
                    catch (PeerToPeerException ex)
                    {
                        ServiceLocator.Resolve<IMessageBoxService>().ShowError(ex.Message);
                    }
                    finally
                    {

                        this.PeerClassifier = string.Empty;
                    }
                }
            };

            this.SetSecureCommand = new PresenterCommand()
            {
                CanExecuteDelegate = secure => true,
                ExecuteDelegate = secure =>
                    {
                        _peerNameType = ((bool)secure) ? PeerNameType.Secured : PeerNameType.Unsecured;
                    }
            };

            this.LookupRegistrationCommand = new PresenterCommand
            {
                CanExecuteDelegate = code => PeerClassifier.Length>0,
                ExecuteDelegate = code =>
                    {
                        try
                        {
                            PeerName peer = new PeerName(PeerClassifier, _peerNameType);
                            LookupPresenter presenter = new LookupPresenter(peer,_service);
                            ServiceLocator.Resolve<IDialogService>().ShowDialog("LookUpRegistration", presenter);
                        }
                        catch (PeerToPeerException ex)
                        {
                            ServiceLocator.Resolve<IMessageBoxService>().ShowError(ex.Message);
                        }
                        finally
                        {
                            this.PeerClassifier = string.Empty;
                        }
                    }
            };
        }
Beispiel #32
0
        //private readonly TcpClient _client;
        //private readonly TcpListener _listener;

        public LocalPeer(string name, int port, Cloud cloud)
        {
            var peerName = new PeerName(name, PeerNameType.Secured);

            // _client = new TcpClient();
            //_listener = new TcpListener();

            _peerRegist = new PeerNameRegistration(peerName, port, cloud);
            _peerRegist.Start();
        }
Beispiel #33
0
        public PeerNameRegistration RegisterPeerGlobal(PeerName peerName, int port)
        {
            var peerNameRegistration = new PeerNameRegistration(peerName, port)
            {
                Cloud = Cloud.Global
            };

            peerNameRegistration.Start();
            return(peerNameRegistration);
        }
        protected override void InitializeCommands()
        {
            this.CreateRegistrationCommand = new PresenterCommand()
            {
                CanExecuteDelegate = code => PeerClassifier.Length > 0,
                ExecuteDelegate    = code =>
                {
                    PeerName name = new PeerName(this.PeerClassifier, _peerNameType);

                    try
                    {
                        _service.CreateRegistration(name, 8080);
                    }
                    catch (PeerToPeerException ex)
                    {
                        ServiceLocator.Resolve <IMessageBoxService>().ShowError(ex.Message);
                    }
                    finally
                    {
                        this.PeerClassifier = string.Empty;
                    }
                }
            };

            this.SetSecureCommand = new PresenterCommand()
            {
                CanExecuteDelegate = secure => true,
                ExecuteDelegate    = secure =>
                {
                    _peerNameType = ((bool)secure) ? PeerNameType.Secured : PeerNameType.Unsecured;
                }
            };

            this.LookupRegistrationCommand = new PresenterCommand
            {
                CanExecuteDelegate = code => PeerClassifier.Length > 0,
                ExecuteDelegate    = code =>
                {
                    try
                    {
                        PeerName        peer      = new PeerName(PeerClassifier, _peerNameType);
                        LookupPresenter presenter = new LookupPresenter(peer, _service);
                        ServiceLocator.Resolve <IDialogService>().ShowDialog("LookUpRegistration", presenter);
                    }
                    catch (PeerToPeerException ex)
                    {
                        ServiceLocator.Resolve <IMessageBoxService>().ShowError(ex.Message);
                    }
                    finally
                    {
                        this.PeerClassifier = string.Empty;
                    }
                }
            };
        }
Beispiel #35
0
 private void btnRegister_Click(object sender, EventArgs e)
 {
     var resourceNameStr = this.txtResource.Text;
     var resourceName = new PeerName(resourceNameStr, PeerNameType.Unsecured);
     resourceNameReg[seedCount] = new PeerNameRegistration(resourceName, int.Parse(this.txtPort.Text));
     resourceNameReg[seedCount].Comment = resourceName.ToString();
     resourceNameReg[seedCount].Data = Encoding.UTF8.GetBytes(string.Format("{0}", DateTime.Now.ToString()));
     resourceNameReg[seedCount].Start();
     seedCount++;
     this.cbxResourceList.Items.Add(resourceName.ToString());
 }
Beispiel #36
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));
             }
         }
     }
 }
Beispiel #37
0
        // 注册资源
        private void btnRegister_Click(object sender, EventArgs e)
        {
            if (tbxResourceName.Text == "") {
                MessageBox.Show("请输入发布的资源名!", "提示");
                return;
            }

            // 将资源名注册到云中
            // 具体资源名的结构在博客有介绍
            PeerName resourceName = new PeerName(tbxResourceName.Text, PeerNameType.Unsecured);
            // 用指定的名称和端口号初始化PeerNameRegistration类的实例
            resourceNameReg[seedCount] = new PeerNameRegistration(resourceName, int.Parse(tbxlocalport.Text));
            // 设置在云中注册的对等名对象的其他信息的注释
            resourceNameReg[seedCount].Comment = resourceName.ToString();
            // 设置PeerNameRegistration对象的应用程序定义的二进制数据
            resourceNameReg[seedCount].Data = Encoding.UTF8.GetBytes(string.Format("{0}", DateTime.Now.ToString()));
            // 在云中注册PeerName(对等名)
            resourceNameReg[seedCount].Start();
            seedCount++;
            comboxSharelist.Items.Add(resourceName.ToString());
            tbxResourceName.Text = "";
        }
Beispiel #38
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();

        }
Beispiel #39
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);
                    }
                }
            }
        }
        public PeerContact GetContact(PeerName peerName)
        {
            if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName);
            
            PeerCollaborationPermission.UnrestrictedPeerCollaborationPermission.Demand();
            if (peerName == null)
                throw new ArgumentNullException("peerName");

            int errorCode = 0;
            SafeCollabData safeContact = null;
            PeerContact peerContact = null;

            Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, 
                "Entering GetContact() with peername {0}", peerName.ToString());

            try{
                errorCode = UnsafeCollabNativeMethods.PeerCollabGetContact(peerName.ToString(),
                                                                        out safeContact);
                if (errorCode == UnsafeCollabReturnCodes.PEER_E_CONTACT_NOT_FOUND){
                    Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "Contact not found in Contact Manager");
                    throw new PeerToPeerException(SR.GetString(SR.Collab_ContactNotFound));
                }
                else if (errorCode != 0){
                    Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerCollabGetContact returned with errorcode {0}", errorCode);
                    throw PeerToPeerException.CreateFromHr(SR.GetString(SR.Collab_GetContactFailed), errorCode);
                }

                if (!safeContact.DangerousGetHandle().Equals(IntPtr.Zero)){
                    Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Found contact.");
                    PEER_CONTACT pc = (PEER_CONTACT)Marshal.PtrToStructure(safeContact.DangerousGetHandle(), typeof(PEER_CONTACT));
                    peerContact = CollaborationHelperFunctions.ConvertPEER_CONTACTToPeerContact(pc);
                }
                else{
                    Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "No contact found.");
                }
            }
            finally{
                safeContact.Dispose();
            }
            Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Leaving GetContact()");

            return peerContact;
        }
        public void DeleteContact(PeerName peerName)
        {
            Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0,
                        "Entering DeleteContact().");

            if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName);
            
            PeerCollaborationPermission.UnrestrictedPeerCollaborationPermission.Demand();
            if (peerName == null)
                throw new ArgumentNullException("peerName");

            Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0,
                        "Peername is {0}", peerName.ToString());

            int errorCode = UnsafeCollabNativeMethods.PeerCollabDeleteContact(peerName.ToString());

            if (errorCode == UnsafeCollabReturnCodes.PEER_E_CONTACT_NOT_FOUND){
                Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "Contact not found in Contact Manager");
                throw new ArgumentException(SR.GetString(SR.Collab_ContactNotFound), "peerName");
            } 
            else if (errorCode != 0){
                Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerCollabDeleteContact returned with errorcode {0}", errorCode);
                throw (PeerToPeerException.CreateFromHr(SR.GetString(SR.Collab_DeleteContactFailed), errorCode));
            }
            Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0,
                        "Leaving DeleteContact() successfully.");
        }
Beispiel #42
0
 public ReceivedDataEventArgs(string data, PeerName from)
 {
     Data = data;
     FromPeer = from;
 }
Beispiel #43
0
 public void ResolveAsync(PeerName peerName, Cloud cloud, object userState)
 {
     ResolveAsync(peerName, cloud, Int32.MaxValue, userState);
 }
Beispiel #44
0
        public void ResolveAsync(PeerName peerName, Cloud cloud, int maxRecords, object userState)
        {
            //-------------------------------------------------
            //Check arguments
            //-------------------------------------------------
            if (peerName == null)
            {
                throw new ArgumentNullException(SR.GetString(SR.Pnrp_PeerNameCantBeNull), "peerName");
            }
            if (cloud == null)
            {
                cloud = Cloud.Available;
            }
            if (maxRecords <= 0)
            {
                throw new ArgumentOutOfRangeException("maxRecords", SR.GetString(SR.Pnrp_MaxRecordsParameterMustBeGreaterThanZero));
            }

            if (m_ResolveCompleted == null)
            {
                throw new PeerToPeerException(SR.GetString(SR.Pnrp_AtleastOneEvenHandlerNeeded));
            }
            //---------------------------------------------------
            //Demand CAS permissions
            //---------------------------------------------------
            PnrpPermission.UnrestrictedPnrpPermission.Demand();

            //---------------------------------------------------------------
            //No perf hit here, real native call happens only one time if it 
            //did not already happen
            //---------------------------------------------------------------
            UnsafeP2PNativeMethods.PnrpStartup();

            //----------------------------------------------------
            //userToken can't be null
            //----------------------------------------------------
            if (userState == null)
            {
                throw new ArgumentNullException(SR.GetString(SR.NullUserToken), "userState");
            }

            PeerNameResolverHelper peerNameResolverHelper = null;
            //---------------------------------------------------
            //The userToken can't be duplicate of what is in the 
            //current list. These are the requriments for the new Async model 
            //that supports multiple outstanding async calls
            //---------------------------------------------------
            int newTraceEventId  = NewTraceEventId;
            lock (m_PeerNameResolverHelperListLock)
            {
                if (m_PeerNameResolverHelperList.ContainsKey(userState))
                {
                    throw new ArgumentException(SR.GetString(SR.DuplicateUserToken));
                }
                Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, newTraceEventId, 
                                                "PeerNameResolverHelper is being created with TraceEventId {0}", newTraceEventId);
                peerNameResolverHelper = new PeerNameResolverHelper(peerName, cloud, maxRecords, userState, this, newTraceEventId);
                m_PeerNameResolverHelperList[userState] = peerNameResolverHelper;
            }

            try
            {
                //---------------------------------------------------
                //Start resolution on that resolver
                //---------------------------------------------------
                peerNameResolverHelper.StartAsyncResolve();
            }
            catch
            {
                //---------------------------------------------------
                //If an exception happens clear the userState from the 
                //list so that that token can be reused
                //---------------------------------------------------
                lock (m_PeerNameResolverHelperListLock)
                {
                    m_PeerNameResolverHelperList.Remove(userState);
                    Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, newTraceEventId,
                        "Removing userState token from pending list {0}", userState.GetHashCode());
                }
                throw;
            }
        }
        public void Stop()
        {
            if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName);

            //-------------------------------------------------
            //No registration happened previously - throw
            //-------------------------------------------------
			if(m_RegistrationHandle.IsInvalid || m_RegistrationHandle.IsClosed)
			{
				throw new InvalidOperationException(SR.GetString(SR.Pnrp_NoRegistrationFound));
			}

            //-------------------------------------------------
            //Demand for the Unrestricted Pnrp Permission
            //-------------------------------------------------
            PnrpPermission.UnrestrictedPnrpPermission.Demand();

            m_RegistrationHandle.Dispose();

			m_PeerNameRecord = new PeerNameRecord();

            m_RegisteredPeerName = null;
			
            m_IsRegistered = false;
        }
Beispiel #46
0
 public PeerNameRecordCollection Resolve(PeerName peerName)
 {
     return Resolve(peerName, Cloud.Available, int.MaxValue);
 }
Beispiel #47
0
 public PeerNameRecordCollection Resolve(PeerName peerName, Cloud cloud)
 {
     return Resolve(peerName, cloud, int.MaxValue);
 }
Beispiel #48
0
 public PeerNameRecordCollection Resolve(PeerName peerName, int maxRecords)
 {
     return Resolve(peerName, Cloud.Available, maxRecords);
 }
Beispiel #49
0
 public void SendMessage(string message, PeerName from)
 {
     ReceivedData(from, new ReceivedDataEventArgs(message, from));
 }
Beispiel #50
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            // Получение конфигурационной информации из app.config
            string port = ConfigurationManager.AppSettings["port"];
            string username = ConfigurationManager.AppSettings["username"];
            string machineName = Environment.MachineName;
            string serviceUrl = null;

            statusPort.Content = "Порт: " + port;
            statusUsername.Content = "Имя пользователя: " + username;

            // Установка заголовка окна
            this.Title = string.Format("P2P приложение - {0}", username);

            //  Получение URL-адреса службы с использованием адресаIPv4
            //  и порта из конфигурационного файла
            foreach (IPAddress address in Dns.GetHostAddresses(Dns.GetHostName()))
            {
                if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    serviceUrl = string.Format("net.tcp://{0}:{1}/P2PService", address, port);
                    break;
                }
            }

            // Выполнение проверки, не является ли адрес null
            if (serviceUrl == null)
            {
                // Отображение ошибки и завершение работы приложения
                MessageBox.Show(this, "Не удается определить адрес конечной точки WCF.", "Networking Error",
                    MessageBoxButton.OK, MessageBoxImage.Stop);
                Application.Current.Shutdown();
            }

            // Регистрация и запуск службы WCF
            localService = new P2PService(this, username);
            host = new ServiceHost(localService, new Uri(serviceUrl));
            NetTcpBinding binding = new NetTcpBinding();
            binding.Security.Mode = SecurityMode.None;
            host.AddServiceEndpoint(typeof(IP2PService), binding, serviceUrl);
            try
            {
                host.Open();
                hostopen = true;
            }
            catch (AddressAlreadyInUseException)
            {
                // Отображение ошибки и завершение работы приложения
                MessageBox.Show(this, "Не удается начать прослушивание, порт занят.", "WCF Error",
                   MessageBoxButton.OK, MessageBoxImage.Stop);
                hostopen = false;
                Application.Current.Shutdown();
            }

            if (hostopen)
            {
                // Создание имени равноправного участника (пира)
                peerName = new PeerName("P2P Sample" + new Guid().ToString(), PeerNameType.Unsecured);

                // Подготовка процесса регистрации имени равноправного участника в локальном облаке
                peerNameRegistration = new PeerNameRegistration(peerName, int.Parse(port));
                peerNameRegistration.Cloud = Cloud.AllLinkLocal;

                // Запуск процесса регистрации
                peerNameRegistration.Start();
            }
        }
Beispiel #51
0
        public PeerNameRecordCollection Resolve(PeerName peerName, Cloud cloud, int maxRecords)
        {
            
            //---------------------------------------------------
            //Check arguments
            //---------------------------------------------------
            if (peerName == null)
            {
                throw new ArgumentNullException(SR.GetString(SR.Pnrp_PeerNameCantBeNull), "peerName");
            }

            if (maxRecords <= 0)
            {
                throw new ArgumentOutOfRangeException("maxRecords", SR.GetString(SR.Pnrp_MaxRecordsParameterMustBeGreaterThanZero));
            }

            //---------------------------------------------------
            //Assume all clouds if the clould passed is null?
            //---------------------------------------------------
            if (cloud == null)
            {
                cloud = Cloud.Available;
            }
            
            //---------------------------------------------------
            //Demand CAS permissions
            //---------------------------------------------------
            PnrpPermission.UnrestrictedPnrpPermission.Demand();

            //---------------------------------------------------------------
            //No perf hit here, real native call happens only one time if it 
            //did not already happen
            //---------------------------------------------------------------
            UnsafeP2PNativeMethods.PnrpStartup();

            //---------------------------------------------------------------
            //Trace log
            //---------------------------------------------------------------
            Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Sync Resolve called with PeerName: {0}, Cloud: {1}, MaxRecords {2}", peerName, cloud, maxRecords);

            SafePeerData shEndPointInfoArray;
            string NativeCloudName = cloud.InternalName;
            UInt32 ActualCountOfEndPoints = (UInt32)maxRecords;
            int result = UnsafeP2PNativeMethods.PeerPnrpResolve(peerName.ToString(), 
                                                                NativeCloudName, 
                                                                ref ActualCountOfEndPoints, 
                                                                out shEndPointInfoArray);
            if (result != 0)
            {
                throw PeerToPeerException.CreateFromHr(SR.GetString(SR.Pnrp_CouldNotStartNameResolution), result);
            }

            //---------------------------------------------------
            //If there are no endpoints returned, return 
            //an empty PeerNameRecord Collection
            //---------------------------------------------------
            PeerNameRecordCollection PeerNameRecords = new PeerNameRecordCollection();
            if (ActualCountOfEndPoints != 0)
            {
                try
                {
                    unsafe
                    {
                        IntPtr pEndPointInfoArray = shEndPointInfoArray.DangerousGetHandle();
                        PEER_PNRP_ENDPOINT_INFO* pEndPoints = (PEER_PNRP_ENDPOINT_INFO*)pEndPointInfoArray;
                        for (int i = 0; i < ActualCountOfEndPoints; i++)
                        {
                            PeerNameRecord record = new PeerNameRecord();
                            PEER_PNRP_ENDPOINT_INFO* pEndPointInfo = &pEndPoints[i];
                            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)));
                            }
                            //----------------------------------
                            //Dump for trace
                            //----------------------------------
                            record.TracePeerNameRecord();
                            //----------------------------------                
                            //Add to collection
                            //----------------------------------
                            PeerNameRecords.Add(record);
                        }
                    }
                }
                finally
                {
                    shEndPointInfoArray.Dispose();
                }
            }
            Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Sync Resolve returnig with PeerNameRecord count :{0}", PeerNameRecords.Count);
            return PeerNameRecords;
        }
        /// <summary>
        /// This constuctor popuates the PeerNameRecord and registers automatically
        /// Registers with automatic address selection within the cloud
        /// </summary>
        /// <param name="name">PeerName to register</param>
        /// <param name="port">Port to register on</param>
        /// <param name="cloud">A specific cloud to regster in</param>/// 
        public PeerNameRegistration(PeerName name, int port, Cloud cloud)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            if (cloud == null)
            {
                cloud = Cloud.Available;
            }
            if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
            {
                throw new ArgumentOutOfRangeException("port", SR.GetString(SR.Pnrp_PortOutOfRange));
            }


            m_PeerNameRecord.PeerName = name;
            m_Port = port;
            m_Cloud = cloud;
            Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Created a PeerNameRegistration with PeerName {0}, Port {1}, Cloud {2} - Proceeding to register", name, port, cloud);
        }
        private void InternalRegister()
        {
            //------------------------------------------
            //If we already registered, get out this place
            //------------------------------------------
            if (m_IsRegistered)
            {
                throw new PeerToPeerException(SR.GetString(SR.Pnrp_UseUpdateInsteadOfRegister));
            }

            //------------------------------------------
            //Make sure you have the required info
            //------------------------------------------
            if (m_PeerNameRecord.PeerName == null)
            {
                throw new ArgumentNullException("PeerName");
            }

            //------------------------------------------
            //If auto address selection is turned off
            //then there must be atleast Data or Endpoints
            //specified 
            //------------------------------------------
            if (!m_UseAutoEndPointSelection)
            {
                if ((EndPointCollection.Count == 0) &&
                     (Data == null || Data.Length <= 0))
                {
                    throw new PeerToPeerException(SR.GetString(SR.Pnrp_BlobOrEndpointListNeeded));
                }
            }


            //-------------------------------------------------
            //Demand for the Unrestricted Pnrp Permission
            //-------------------------------------------------
            PnrpPermission.UnrestrictedPnrpPermission.Demand();

            //---------------------------------------------------------------
            //No perf hit here, real native call happens only one time if it 
            //did not already happen
            //---------------------------------------------------------------
            UnsafeP2PNativeMethods.PnrpStartup();

            //---------------------------------------------------------------
            //Log trace info
            //---------------------------------------------------------------
            if (Logging.P2PTraceSource.Switch.ShouldTrace(TraceEventType.Information))
            {
                Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "InternalRegister() is called with the following Info");
                m_PeerNameRecord.TracePeerNameRecord();
            }

            PEER_PNRP_REGISTRATION_INFO regInfo = new PEER_PNRP_REGISTRATION_INFO();
            GCHandle handle;
            //-------------------------------------------------
            //Set data
            //-------------------------------------------------
            if (m_PeerNameRecord.Data != null)
            {
                regInfo.payLoad.cbPayload = (UInt32)m_PeerNameRecord.Data.Length;
                handle = GCHandle.Alloc(m_PeerNameRecord.Data, GCHandleType.Pinned);
                regInfo.payLoad.pbPayload = handle.AddrOfPinnedObject(); //m_PeerNameRecord.Data;
            }
            else
            {
                handle = new GCHandle();
            }
            //-------------------------------------------------
            //Set comment
            //-------------------------------------------------
            if (m_PeerNameRecord.Comment != null && m_PeerNameRecord.Comment.Length > 0)
            {
                regInfo.pwszComment = m_PeerNameRecord.Comment;
            }
            //-------------------------------------------------
            //Set cloud name
            //-------------------------------------------------
            if (m_Cloud != null)
            {
                regInfo.pwszCloudName = m_Cloud.InternalName;
            }
            try
            {
                if (m_PeerNameRecord.EndPointCollection.Count == 0)
                {
                    //-------------------------------------------------
                    //Set port only if the addresses are null
                    //and then set the selection to auto addresses
                    //-------------------------------------------------
                    regInfo.wport = (ushort)m_Port;

                    if(m_UseAutoEndPointSelection)
                        regInfo.cAddresses = PEER_PNRP_AUTO_ADDRESSES;

                    //-------------------------------------------------
                    //Call the native API to register
                    //-------------------------------------------------
                    int result = UnsafeP2PNativeMethods.PeerPnrpRegister(m_PeerNameRecord.PeerName.ToString(),
                                        ref regInfo,
                                        out m_RegistrationHandle);
                    if (result != 0)
                    {
                        throw PeerToPeerException.CreateFromHr(SR.GetString(SR.Pnrp_CouldNotRegisterPeerName), result);
                    }
                }
                else
                {
                    //-------------------------------------------------
                    //Set the Endpoint List
                    //-------------------------------------------------
                    int numAddresses = m_PeerNameRecord.EndPointCollection.Count;
                    int cbRequriedBytes = numAddresses * Marshal.SizeOf(typeof(IntPtr));
                    IntPtr pSocketAddrList = Marshal.AllocHGlobal(cbRequriedBytes);
                    GCHandle[] GCHandles = new GCHandle[numAddresses];
                    try
                    {
                        unsafe
                        {
                            IntPtr* pAddress = (IntPtr*)pSocketAddrList;
                            for (int i = 0; i < m_PeerNameRecord.EndPointCollection.Count; i++)
                            {
                                byte[] sockaddr = SystemNetHelpers.SOCKADDRFromIPEndPoint(m_PeerNameRecord.EndPointCollection[i]);
                                GCHandles[i] = GCHandle.Alloc(sockaddr, GCHandleType.Pinned);
                                IntPtr psockAddr = GCHandles[i].AddrOfPinnedObject();
                                pAddress[i] = psockAddr;
                            }
                        }
                        regInfo.ArrayOfSOCKADDRIN6Pointers = pSocketAddrList;
                        regInfo.cAddresses = (UInt32)numAddresses;
                        int result = UnsafeP2PNativeMethods.PeerPnrpRegister(m_PeerNameRecord.PeerName.ToString(),
                                            ref regInfo,
                                            out m_RegistrationHandle);
                        if (result != 0)
                        {
                            throw PeerToPeerException.CreateFromHr(SR.GetString(SR.Pnrp_CouldNotRegisterPeerName), result);
                        }
                    }
                    finally
                    {
                        if (pSocketAddrList != IntPtr.Zero)
                            Marshal.FreeHGlobal(pSocketAddrList);

                        for (int i = 0; i < GCHandles.Length; i++)
                        {
                            if (GCHandles[i].IsAllocated)
                                GCHandles[i].Free();
                        }
                    }
                }
            }
            finally
            {
                if (handle.IsAllocated)
                {
                    handle.Free();
                }

            }
            m_RegisteredPeerName = m_PeerNameRecord.PeerName;
            m_IsRegistered = true;
            Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Registration is successful. The handle is {0}", m_RegistrationHandle.DangerousGetHandle());
        }
 public void Start(string peerClassifier, int port)
 {
     PeerName peerName = new PeerName(peerClassifier, PeerNameType.Unsecured);
     _peerNameRegistration = new PeerNameRegistration(peerName, port, Cloud.Global);
     _peerNameRegistration.Start();
 }
 /// <summary>
 /// This constuctor popuates the PeerNameRecord and registers automatically
 /// Registers in all clouds with automatic address selection
 /// </summary>
 /// <param name="name">PeerName to register</param>
 /// <param name="port">Port to register on</param>
 public PeerNameRegistration(PeerName name, int port) : this(name, port, null)
 {
 }
Beispiel #56
0
 public void ResolveAsync(PeerName peerName, int maxRecords, object userState)
 {
     ResolveAsync(peerName, Cloud.Available, maxRecords, userState);
 }
Beispiel #57
0
 public LookupPresenter(PeerName peerName, Core.PnrpManager manager) : base()
 {
     _currentPeerName = peerName;
     _manager = manager;
     _manager.LookupRegistrationAsync(_currentPeerName, resolver_ResolveProgressChanged, resolver_ResolveCompleted);
 }
Beispiel #58
0
        private void OpenPeer()
        {
            if (TargetGrobal)
            {
                #region インデックスサーバー名の確認

                if (string.IsNullOrWhiteSpace(textBoxIndexServerAddress.Text))
                {
                    MessageBox.Show(labelIndexServerAddress.Text + "を入力してください。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    tabControl1.SelectedTab = tabPageSetting;
                    textBoxIndexServerAddress.SelectAll();
                    textBoxIndexServerAddress.Focus();
                    return;
                }

                #endregion

                try
                {
                    peerName = PeerName.CreateFromPeerHostName(textBoxIndexServerAddress.Text);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    tabControl1.SelectedTab = tabPageSetting;
                    textBoxIndexServerAddress.SelectAll();
                    textBoxIndexServerAddress.Focus();
                    return;
                }
            }
            else
            {
                #region 入力ピア名の検証

                if (string.IsNullOrWhiteSpace(Classifier))
                {
                    MessageBox.Show(labelClassifier.Text + "を入力してください。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    tabControl1.SelectedTab = tabPageSetting;
                    textBoxClassifier.SelectAll();
                    textBoxClassifier.Focus();
                    return;
                }

                #endregion

                peerName = new PeerName(Classifier, PeerNameType);
            }

            MakeResolver();

            register = new Register<UserData>(Cloud, peerName, PortNo);
            register.SetData(MyData);

            UpdateUI();

            AddLog("StartPeer", LogType.System);

            buttonLoad.PerformClick();
        }
Beispiel #59
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()
         );
 }
Beispiel #60
0
 public void ResolveAsync(PeerName peerName, object userState)
 {
     ResolveAsync(peerName, Cloud.Available, Int32.MaxValue, userState);
 }