Example #1
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};
        }
Example #2
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());
 }
Example #3
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 = "";
        }
Example #4
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();
            }
        }
 public void Stop()
 {
     if (_peerNameRegistration != null)
         _peerNameRegistration.Stop();
     _peerNameRegistration = null;
 }
 public void Start(string peerClassifier, int port)
 {
     PeerName peerName = new PeerName(peerClassifier, PeerNameType.Unsecured);
     _peerNameRegistration = new PeerNameRegistration(peerName, port, Cloud.Global);
     _peerNameRegistration.Start();
 }
Example #7
0
        // Регистрация локального равноправного участника
        public void RegisterHost(string username)
        {
            // Получение конфигурационной информации из app.config
            string port = ConfigurationManager.AppSettings["port"];
            string serviceUrl = string.Format("net.tcp://0.0.0.0:{0}/P2PService", port);

            // Создание регистрационных данных о локальном пире
            LocalPeer.ServiceProxy = new P2PService(username);
            LocalPeer.ServiceProxy.ReceivedData += ServiceProxyOnReceivedData;
            LocalPeer.DisplayString = LocalPeer.ServiceProxy.GetName();
            host = new ServiceHost(LocalPeer.ServiceProxy, new Uri(serviceUrl));
            var binding = new NetTcpBinding();
            binding.Security.Mode = SecurityMode.None;
            host.AddServiceEndpoint(typeof (IP2PService), binding, serviceUrl);
            try
            {
                host.Open();
                // Создание имени равноправного участника с определенным классификатором.
                LocalPeer.PeerName = new PeerName("P2P_Checksum", PeerNameType.Unsecured);

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

                // Запуск процесса регистрации
                peerNameRegistration.Start();

                logger.Info(
                    "КТО: пользователь {0}. ЧТО: запуск регистрации хоста на порте {1}. РЕЗУЛЬТАТ: успешно. Имя хоста - {2}",
                    username, port, serviceUrl);
            }
            catch (AddressAlreadyInUseException)
            {
                logger.Error(
                    "ОШИБКА. КТО: пользователь{0}. ЧТО: запуск регистрации хоста на порте {1}. РЕЗУЛЬТАТ: неудача. Ошибка WCF: невозможно начать прослушивание на порте {1}, он используется другой программой",
                    username, port);
            }
        }
Example #8
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;
        }
Example #9
0
        public bool DeleteRegistration(PeerNameRegistration registration)
        {
            _registrations.Remove(registration);
            ProcessRegistrations(this.CurrentScope);

            return false;
        }