Example #1
0
 public PeerEntry(PeerName peerName, IPeerToPeerService serviceProxy, string displayString, bool buttonsEnabled)
 {
     PeerName       = peerName;
     ServiceProxy   = serviceProxy;
     DisplayString  = displayString;
     ButtonsEnabled = buttonsEnabled;
 }
        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();
        }
        private void Resolver_ResolveProgressChanged(object sender, ResolveProgressChangedEventArgs e)
        {
            PeerNameRecord peer = e.PeerNameRecord;

            peer.EndPointCollection.Where(point => point.Address.AddressFamily == AddressFamily.InterNetwork)
            .AsParallel()
            .ForAll(
                point =>
            {
                try
                {
                    string endpointUrl = string.Format("net.tcp://{0}:{1}/PeerToPeerService", point.Address, point.Port);
                    var binding        = new NetTcpBinding {
                        Security = { Mode = SecurityMode.None }
                    };
                    IPeerToPeerService serviceProxy = ChannelFactory <IPeerToPeerService> .CreateChannel(binding,
                                                                                                         new EndpointAddress(endpointUrl));

                    lock (_peersLock)
                    {
                        _peerList.Add(new PeerEntry
                        {
                            PeerName       = peer.PeerName,
                            ServiceProxy   = serviceProxy,
                            DisplayString  = serviceProxy.GetName(),
                            ButtonsEnabled = true
                        });
                    }
                }
                catch (EndpointNotFoundException)
                {
                    lock (_peersLock)
                    {
                        _peerList.Add(new PeerEntry
                        {
                            PeerName       = peer.PeerName,
                            DisplayString  = "Unknown peer",
                            ButtonsEnabled = false
                        });
                    }
                }
            });
        }