public bool RegisterWatcher(ServiceProfile profile, string host, IServiceContext serviceContext)
 {
     lock (locker)
     {
         IRPCWatcher watcher = watchers.Find(w => w.HostInfo.Node.Equals(host, StringComparison.OrdinalIgnoreCase));
         if (watcher == null)
         {
             this.logger.LogDebug($@"setting up an Remote fs watcher for {host}...");
             var currentHostInfo = new RPCHostInfo(host, profile.GetNodeServiceNetLocation(host));
             this.logger.LogDebug($@"targeting {currentHostInfo.WatchDir} on server {host}...");
             using (var subContainer = this.factoryContainer.GetNestedContainer())
             {
                 subContainer.Inject <IRPCHostInfo>(currentHostInfo);
                 watcher = subContainer.GetInstance <IRPCWatcher>();
                 watcher.OrchWatcherErrorEventHandler += HandleWatcherFailure;
                 this.logger.LogDebug($@"{host} watchdog setup ok ");
                 var result = watcher.StartWatching();
                 if (result)
                 {
                     this.logger.LogDebug($@"{host} watchdog working...");
                     watchers.Add(watcher);
                 }
                 else
                 {
                     this.logger.LogError($@"{host} watchdog setup ok but failed to start");
                     return(false);
                 }
             }
         }
         watcher.OrchFileChangeEventHandler += serviceContext.OnProcessFinishRequest;
         return(true);
     }
 }
        private void InitializeMapper()
        {
            var profile       = new ServiceProfile();
            var configuration = new MapperConfiguration(cfg => cfg.AddProfile(profile));

            _mapper = new Mapper(configuration);
        }
        void environment_ServiceScheduleRequested(object sender, ServiceScheduleRequestedEventArgs e)
        {
            if (e.ServiceInstance != null)
            {
                if (e.ServiceInstance.ParentInstance == null)
                {
                    this.AddChildServiceToSchedule(e.ServiceInstance);
                }
                else
                {
                    this.AddRequestToSchedule(e.ServiceInstance);
                }
            }
            else
            {
                ServiceProfile profile = _profiles[e.AccountID];
                IEnumerable <ServiceConfiguration> configuration = from sc in profile.Services
                                                                   where sc.ServiceName == e.ServiceName
                                                                   select sc;
                ServiceConfiguration mergedConfiguration = configuration.ToList <ServiceConfiguration>()[0].Merge(e.OverridingConfiguration);

                ServiceInstance instance = Environment.NewServiceInstance(mergedConfiguration);

                this.AddRequestToSchedule(instance);
            }
        }
Beispiel #4
0
 private string PutRequestOnBox(string node, string filename, string request, ServiceProfile serviceProfile, string fileInBox, int timeoutSeconds)
 {
     lock (CallLocker)
     {
         this.logger.LogDebug($@"Start checking {filename} request into {node}");
         if (!serviceProfile.VerifyServiceProfileOnNode(node))
         {
             this.logger.LogDebug($@"Put Request on {node} fail, either {node} is not up or server-client profile incorrect");
             return($"[ORCH-ERR]Put Request on {node} fail, either {node} is not up or profile incorrect.");
         }
         var outBoxFile = Path.Combine(Path.Combine(serviceProfile.GetNodeServiceNetLocation(node), "boxes", "outbox"), filename);
         WriteFileRequest(node, filename, request, serviceProfile, fileInBox);
         this.logger.LogDebug($@"Request {filename} is written to {node}, and will timeout in {timeoutSeconds} seconds");
         if (sync.WaitOne(timeoutSeconds * 1000))
         {
             this.logger.LogDebug($@"Request {filename} comes back, returning result");
             return(File.ReadAllText(outBoxFile, Encoding.UTF8));
         }
         else
         {
             this.logger.LogDebug($@"Request {filename} timeout  ({timeoutSeconds})");
             return($@"[ORCH-ERR]the operation time out ({timeoutSeconds})");
         }
     }
 }
Beispiel #5
0
        static void Main(string[] args)
        {
            Console.WriteLine("Multicast DNS spike");

            // set logger factory
            var properties = new Common.Logging.Configuration.NameValueCollection
            {
                ["level"]        = "TRACE",
                ["showLogName"]  = "true",
                ["showDateTime"] = "true"
            };

            LogManager.Adapter = new ConsoleOutLoggerFactoryAdapter(properties);

            var mdns = new MulticastService
            {
                NetworkInterfaceDiscoveryInterval = TimeSpan.FromSeconds(1),
            };

            foreach (var a in MulticastService.GetIPAddresses())
            {
                Console.WriteLine($"IP address {a}");
            }

            mdns.QueryReceived += (s, e) =>
            {
                var names = e.Message.Questions
                            .Select(q => q.Name + " " + q.Type);
                Console.WriteLine($"got a query for {String.Join(", ", names)}");
            };
            mdns.AnswerReceived += (s, e) =>
            {
                var names = e.Message.Answers
                            .Select(q => q.Name + " " + q.Type)
                            .Distinct();
                Console.WriteLine($"got answer for {String.Join(", ", names)}");
            };
            mdns.NetworkInterfaceDiscovered += (s, e) =>
            {
                foreach (var nic in e.NetworkInterfaces)
                {
                    Console.WriteLine($"discovered NIC '{nic.Name}'");
                }
            };

            var sd = new ServiceDiscovery(mdns);

            sd.Advertise(new ServiceProfile("x1", "_xservice._tcp", 5011));
            sd.Advertise(new ServiceProfile("x2", "_xservice._tcp", 666));
            var z1 = new ServiceProfile("z1", "_zservice.udp", 5012);

            z1.AddProperty("foo", "bar");
            sd.Advertise(z1);

            mdns.Start();
            Console.ReadKey();
        }
Beispiel #6
0
 public string ProcessRequest(string node, string filename, string request, ServiceProfile serviceProfile)
 {
     return(PutRequestOnBox(
                node,
                filename,
                request,
                serviceProfile,
                Path.Combine(Path.Combine(serviceProfile.GetNodeServiceNetLocation(node), "boxes", "inbox"), filename)));
 }
Beispiel #7
0
        public static async Task Receive(ReceiveParameters param)
        {
            if (param.deviceName == null)
            {
                param.deviceName = Environment.MachineName;
            }
            try
            {
                using (var socket = new Socket(AddressFamily.InterNetwork,
                                               SocketType.Stream,
                                               ProtocolType.Tcp))
                {
                    using (var sd = new ServiceDiscovery())
                    {
                        var endPoint = new IPEndPoint(IPAddress.Any, 0);
                        socket.Bind(endPoint);
                        var port           = ((IPEndPoint)socket.LocalEndPoint).Port;
                        var serviceProfile = new ServiceProfile(param.deviceName, ADropDomainName, (ushort)port);
                        sd.Advertise(serviceProfile);
                        socket.Listen(1);
                        var incoming = socket.Accept();
                        Console.WriteLine($"{incoming.RemoteEndPoint} connect, receiving metadata.");
                        using (var receiver = new Receiver(incoming))
                        {
                            var meta = receiver.ReadMetadata();
                            Console.WriteLine($"MetaInfo: {meta.FileInfos.Count()} files with type:\n{meta.FileInfos}");

                            receiver.SendAction(Proto.Action.Types.ActionType.Accepted);

                            for (int i = 0; i < meta.FileInfos.Count(); i++)
                            {
                                var mimeType = meta.FileInfos[i].FileType;
                                var result   = await receiver.ReadFile();

                                if (mimeType == "text/plain")
                                {
                                    Console.WriteLine($"received text: \n{Encoding.UTF8.GetString(result)}");
                                }
                                else
                                {
                                    var extension = MimeTypes.MimeTypeMap.GetExtension(mimeType) ?? ".dat";
                                    File.WriteAllBytes($"{i}{extension}", result);
                                }
                            }
                        }
                    }
                    return;
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine(e);
            }

            return;
        }
Beispiel #8
0
 private void WriteFileRequest(string node, string filename, string request, ServiceProfile serviceProfile, string fileInBox)
 {
     this.repository.RegisterWatcher(serviceProfile, node, this);
     currentFile = filename;
     using (FileStream sw = File.OpenWrite(fileInBox))
     {
         byte[] bytes = Encoding.UTF8.GetBytes(request);
         sw.Write(bytes, 0, bytes.Length);
     }
 }
Beispiel #9
0
        public Task <Guid> Register(ServiceProfile service)
        {
            var guid = Guid.NewGuid();
            RegisteredServiceProfile registeredService = (RegisteredServiceProfile)service;

            registeredService.RegisteredID = guid;
            RegisteredServices.Add(registeredService);
            OnServiceRegister?.Invoke(this, service);
            return(Task.FromResult(guid));
        }
Beispiel #10
0
        public RSMService()
        {
            InitializeComponent();

            Profile                  = new ServiceProfile();
            Profile.Service          = this;
            this.ServiceName         = Profile.Name;
            this.CanStop             = true;
            this.CanPauseAndContinue = true;
            this.AutoLog             = true;
        }
Beispiel #11
0
        private void StartAdvertiser()
        {
            _logger.LogDebug($"Starting advertiser on local network");
            var neonService = new ServiceProfile("neon", "_neonhome._tcp", 5000);

            neonService.AddProperty("http", "5000");
            neonService.AddProperty("https", "5001");
            neonService.AddProperty("appVersion", AssemblyUtils.GetVersion());
            neonService.AddProperty("uuid", _uuid);

            _serviceAdvertiser.Advertise(neonService);
        }
Beispiel #12
0
        private static void RunServer()
        {
            var service = "_appletv.local.appletv._local.appletv.local.appletv.local";
            var mdns    = new MulticastService();

            mdns.QueryReceived += (s, e) =>
            {
                var msg = e.Message;
                if (msg.Questions.Any(q => q.Name == service))
                {
                    var res       = msg.CreateResponse();
                    var addresses = MulticastService.GetIPAddresses()
                                    .Where(ip => ip.AddressFamily == AddressFamily.InterNetwork);
                    foreach (var address in addresses)
                    {
                        var ar = new ARecord
                        {
                            Name    = service,
                            Address = address
                        };
                        var writer = new PresentationWriter(new StringWriter());
                        writer.WriteString("123qweq");
                        ar.WriteData(writer);
                        ar.Name = "qweqeqweq";
                        res.Answers.Add(ar);
                    }
                    mdns.SendAnswer(res);
                }
            };
            advertiseThread = new Thread(new ThreadStart(() =>
            {
                sd     = new ServiceDiscovery(mdns);
                var sp = new ServiceProfile("_itxpt_multicast._tcp.", "_itxpt._tcp", 5353, new List <IPAddress> {
                    IPAddress.Parse("192.168.88.239")
                });
                //sp.AddProperty("host", "192.168.88.239");
                //sp.AddProperty("port", "14005");
                sp.Resources.Add(new ARecord {
                    Name = "_itxpt_multicast._tcp.", Address = IPAddress.Parse("192.168.88.239"), Class = DnsClass.ANY
                });
                sp.Resources.Add(new SRVRecord {
                    Name = "_itxpt_multicast._tcp.", Port = 5353, Priority = 0, Weight = 0, Class = DnsClass.ANY
                });
                sp.Resources.Add(new PTRRecord {
                    Name = "_itxpt_multicast._tcp.", DomainName = "192.168.88.239"
                });
                sd.Advertise(sp);
            }));
            advertiseThread.Start();

            mdns.Start();
        }
        private void AddServiceClick(object sender, EventArgs e)
        {
            curService.soid      = Convert.ToInt32(newSoid.Text);
            curService.srvcToken = newToken.Text;
            curService.Trigger   = textToTrigger[newTrigger.Text];

            ServiceProfile prof = new ServiceProfile();

            prof.userName  = userName.Text;
            prof.soid      = curService.soid;
            prof.srvcToken = curService.srvcToken;
            prof.triggers.Add(curService.Trigger);

            curService.profile.Add(prof);
        }
Beispiel #14
0
        private void AdvertiseService(IPAddress ip)
        {
            var service = new ServiceProfile($"Vent-Test", "_venttest._tcp", 54321, new List <IPAddress>()
            {
                ip
            });

            service.AddProperty("vn", "1.0");
            service.AddProperty("fn", new EasClientDeviceInformation().FriendlyName);
            Debug.WriteLine("Made service profile");
            SD = new ServiceDiscovery();
            Debug.WriteLine("Made ServiceDiscovery");
            SD.Advertise(service);
            Debug.WriteLine("Advertising");
        }
Beispiel #15
0
 public FsRPCBase(
     ServiceProfile profile,
     IServiceDeployment serviceDeployment,
     IFileNameProvider provider,
     IContextPool <FsBaseExecSvc.Interface.IServiceContext> contextPool,
     ILogger <FsRPCBase> logger,
     IOSHelper oSHelper)
 {
     this.contextPool       = contextPool;
     this.profile           = profile;
     this.logger            = logger;
     this.serviceDeployment = serviceDeployment;
     this.provider          = provider;
     this.oshelper          = oSHelper;
 }
Beispiel #16
0
        public sealed override void RefreshSystem()
        {
            var sd = DataUtil.GetSystemData();

            _devMode  = sd.DeviceMode;
            _hostName = _sd.DeviceName;
            _discovery?.Dispose();
            var address = new List <IPAddress> {
                IPAddress.Parse(IpUtil.GetLocalIpAddress())
            };
            var service = new ServiceProfile(_hostName, "_glimmr._tcp", 21324, address);

            service.AddProperty("mac", sd.DeviceId);
            _discovery = new ServiceDiscovery();
            _discovery.Advertise(service);
        }
Beispiel #17
0
        public RSMInstaller()
        {
            InitializeComponent();
            processInstaller = new ServiceProcessInstaller();
            serviceInstaller = new ServiceInstaller();

            var profile = new ServiceProfile();

            processInstaller.Account     = ServiceAccount.LocalSystem;
            serviceInstaller.StartType   = ServiceStartMode.Automatic;
            serviceInstaller.ServiceName = profile.Name;
            serviceInstaller.Description = profile.Description;

            Installers.Add(serviceInstaller);
            Installers.Add(processInstaller);
        }
Beispiel #18
0
        /// <inheritdoc />
        public Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogTrace("Going to check if is necessary register.");
            if (_option.RegistermDNS)
            {
                _logger.LogTrace("Going to register Service in mDNS.");
                Task.Run(() =>
                {
                    _logger.LogTrace("Going to wait {delay} before register.", _option.MDnsDelay.ToString("G"));
                    Task.Delay(_option.MDnsDelay, cancellationToken).GetAwaiter().GetResult();

                    var tls    = _server.Features.Get <ITlsHandshakeFeature>();
                    var hasTls = tls != null && tls.Protocol != SslProtocols.None;

                    var addresses = _server.Features.Get <IServerAddressesFeature>()?.Addresses ?? new List <string>();

                    foreach (var address in addresses)
                    {
                        var index = address.LastIndexOf(':');
                        if (index < 0 || index + 1 == address.Length)
                        {
                            _logger.LogWarning("Going to ignore {address} address, because it has a invalid format", address);
                            continue;
                        }

                        var port = ushort.Parse(address.AsSpan().Slice(index + 1));

                        var profile = new ServiceProfile("_webthing._tcp.local", _name, port);
                        profile.AddProperty("path", "/");

                        if (hasTls)
                        {
                            profile.AddProperty("tls", "1");
                        }

                        _profiles.Add(profile);

                        _logger.LogInformation("Advertising and Announcing the {serviceName} in {port} port", _name, port);
                        _discovery.Advertise(profile);
                        _discovery.Announce(profile);
                    }
                }, cancellationToken);
            }

            return(Task.CompletedTask);
        }
Beispiel #19
0
 private string PutRequestOnBox(string node, string filename, string request, ServiceProfile serviceProfile, string fileInBox)
 {
     lock (CallLocker)
     {
         this.logger.LogDebug($@"Start checking {filename} request into {node}");
         if (!serviceProfile.VerifyServiceProfileOnNode(node))
         {
             this.logger.LogDebug($@"Put Request on {node} fail, either {node} is not up or server-client profile incorrect");
             return($"[ORCH-ERR]Put Request on {node} fail, either {node} is not up or profile incorrect.");
         }
         var outBoxFile = Path.Combine(Path.Combine(serviceProfile.GetNodeServiceNetLocation(node), "boxes", "outbox"), filename);
         WriteFileRequest(node, filename, request, serviceProfile, fileInBox);
         this.logger.LogDebug($@"Request {filename} is written to {node}, and will wait till the server process the request");
         sync.WaitOne();
         return(File.ReadAllText(outBoxFile, Encoding.UTF8));
     }
 }
Beispiel #20
0
        protected ServiceConfiguration CreatePipelineWorkflow(ServiceConfiguration workflowConfig)
        {
            var profile = new ServiceProfile {
                Name = "Profile"
            };

            profile.Parameters["AccountID"]        = ACCOUNT_ID;
            profile.Parameters["ChannelID"]        = CHANNEL_ID;
            profile.Parameters["FileDirectory"]    = GetTestName();
            profile.Parameters["DeliveryFileName"] = "temp.txt";
            profile.Parameters["SourceUrl"]        = "http://google.com";
            profile.Parameters["UsePassive"]       = true;
            profile.Parameters["UseBinary"]        = false;
            profile.Parameters["UserID"]           = "edgedev";
            profile.Parameters["Password"]         = "******";

            return(profile.DeriveConfiguration(workflowConfig));
        }
Beispiel #21
0
        public bool DeployService(string node, ServiceProfile profile, bool reInstall)
        {
            var result = DeployOperation(
                node,
                profile.ServiceBinFullName,
                profile.ServiceName,
                profile.Domain,
                profile.Username,
                profile.Pwd,
                profile.SvcInstallMediaLoc,
                reInstall);

            if (result == false)
            {
                this.logger.LogWarning($@"DeployService on {node} failed");
            }
            return(result);
        }
Beispiel #22
0
        private void AdvertiseService(IApplicationBuilder app)
        {
            var mdns = new MulticastService();

            mdns.Start();

            var serverAddressesFeature = app.ServerFeatures.Get <IServerAddressesFeature>();

            foreach (var address in serverAddressesFeature.Addresses)
            {
                var    uri = new Uri(address);
                var    serviceDiscovery = new ServiceDiscovery(mdns);
                string serviceType      = "_" + uri.Scheme + "._tcp";
                var    service          = new ServiceProfile("TelekinesisServer", serviceType, (ushort)uri.Port);
                service.AddProperty("OSVersion", Environment.OSVersion.ToString());
                service.AddProperty("Platform", Environment.OSVersion.Platform.ToString());
                service.AddProperty("MachineName", Environment.MachineName);
                serviceDiscovery.Advertise(service);
            }
        }
Beispiel #23
0
        public DiscoveryClient(string serviceName, ushort port, string serviceType, IEnumerable <IPAddress> ipAddresses)
        {
            ServiceName = serviceName;
            ServiceType = serviceType;
            Port        = port;

            mdns        = new MulticastService();
            IPAddresses = ipAddresses ?? MulticastService.GetIPAddresses();

            logger.Info("Creating service profile with" +
                        "\tServiceName=" + serviceName +
                        "\tServiceType=" + serviceType +
                        "\tPort=" + port +
                        "\tIPAddresses=" + string.Join(";", IPAddresses));

            serviceProfile = new ServiceProfile(ServiceName, ServiceType, Port, IPAddresses);

            advertiseThread = new Thread(Advertise);
            IsRunning       = false;
        }
Beispiel #24
0
        /// <inheritdoc />
        public override ServiceProfile BuildProfile()
        {
            var profile = new ServiceProfile(
                instanceName: SafeLabel(LocalPeer.Id.ToBase32()),
                serviceName: ServiceName,
                port: 0
                );

            // The TXT records contain the multi addresses.
            profile.Resources.RemoveAll(r => r is TXTRecord);
            foreach (var address in LocalPeer.Addresses)
            {
                profile.Resources.Add(new TXTRecord
                {
                    Name    = profile.FullyQualifiedName,
                    Strings = { $"dnsaddr={address.ToString()}" }
                });
            }

            return(profile);
        }
Beispiel #25
0
        static void Main(string[] args)
        {
            // Advertise via mDNS
            Console.WriteLine("Getting IP addresses");
            string sHostName = Dns.GetHostName();

            IPAddress[] IPs = Dns.GetHostAddresses(sHostName);
            Console.WriteLine($"Got: {String.Join(", ", (IEnumerable<IPAddress>)IPs)}");
            var service = new ServiceProfile($"Cards-Uno-{Guid.NewGuid()}", "_customservice._tcp", 54321, IPs);

            service.AddProperty("service_version", "1.0");
            Console.WriteLine("Made service profile");

            var SD = new ServiceDiscovery();

            Console.WriteLine("Made ServiceDiscovery");
            SD.Advertise(service);
            Console.WriteLine("Advertising");

            Console.ReadLine();
        }
Beispiel #26
0
        public UnplannedView(ServiceProfile accounServiceInformation, UnplanedType type, ServiceConfiguration serviceConfiguration, UnplannedView parent)
        {
            _options = new Dictionary <string, string>();


            _accounServiceInformation = accounServiceInformation;
            _unplanedType             = type;
            if (type == Objects.UnplanedType.Service)
            {
                _serviceConfiguration = serviceConfiguration;
                _serviceName          = _serviceConfiguration.ServiceName;
                ParentAccount         = parent;
            }
            foreach (var available in _accounServiceInformation.Services)
            {
                _availableServices.Add(available.ServiceName);
            }



            RaisePropertyChanged("AccountName");
        }
Beispiel #27
0
        /// <inheritdoc />
        public override ServiceProfile BuildProfile()
        {
            // Only internet addresses.
            var addresses = LocalPeer.Addresses
                            .Where(a => a.Protocols.First().Name == "ip4" || a.Protocols.First().Name == "ip6")
                            .ToArray();

            if (addresses.Length == 0)
            {
                return(null);
            }
            var ipAddresses = addresses
                              .Select(a => IPAddress.Parse(a.Protocols.First().Value));

            // Only one port is supported.
            var tcpPort = addresses.First()
                          .Protocols.First(p => p.Name == "tcp")
                          .Value;

            // Create the DNS records for this peer.  The TXT record
            // is singular and must contain the peer ID.
            var profile = new ServiceProfile(
                instanceName: LocalPeer.Id.ToBase58(),
                serviceName: ServiceName,
                port: ushort.Parse(tcpPort),
                addresses: ipAddresses
                );

            profile.Resources.RemoveAll(r => r.Type == DnsType.TXT);
            var txt = new TXTRecord {
                Name = profile.FullyQualifiedName
            };

            txt.Strings.Add(profile.InstanceName.ToString());
            profile.Resources.Add(txt);

            return(profile);
        }
Beispiel #28
0
        // Needs netsh http add urlacl url="http://+:63737/" user=everyone
        public static void Listen()
        {
            var listener = new HttpListener();

            listener.Prefixes.Add("http://+:63737/");
            listener.Start();

            var sd = new ServiceDiscovery();

            foreach (var ni in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (ni.OperationalStatus != OperationalStatus.Up)
                {
                    continue;
                }
                if (ni.GetIPProperties().GatewayAddresses.Count == 0)
                {
                    continue;
                }

                foreach (var ua in ni.GetIPProperties().UnicastAddresses)
                {
                    var service = new ServiceProfile(Environment.MachineName, "_punt37._tcp", 63737, new List <IPAddress> {
                        ua.Address
                    });
                    sd.Advertise(service);
                }
            }

            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    var context = listener.GetContext();
                    Task.Factory.StartNew(() => ProcessRequest(context));
                }
            });
        }
Beispiel #29
0
        public Client(string clientIp)
        {
            _clientIp = clientIp;
            mdns      = new MulticastService();
            var domainName = "_itxpt_multicast._tcp";

            servicename = "gnsslocation";
            mdns.NetworkInterfaceDiscovered += (s, e) => mdns.SendQuery(domainName);

            mdns.AnswerReceived += (s, e) =>
            {
                Console.WriteLine($"GET response from server {e.RemoteEndPoint.Address}:{e.RemoteEndPoint.Port}. Message: {e.Message.Answers.FirstOrDefault()}");
                List <ResourceRecord> answers = e.Message.Answers;
                this.ParseRecords(answers);

                Func <IPEndPoint, bool> predicate = null;
                foreach (ResourceRecord record in answers)
                {
                    if ((record is TXTRecord) && this.ForMe)
                    {
                        foreach (string str in ((TXTRecord)record).Strings)
                        {
                            char[]   separator = new char[] { '=' };
                            string[] strArray  = str.Split(separator);
                            if (strArray.Length == 2)
                            {
                                if (strArray[0] == "address")
                                {
                                    string text1 = strArray[1];
                                }
                                if (strArray[0] == "multicast")
                                {
                                    this.multicastIp = strArray[1];
                                }
                            }
                        }
                    }
                }
                answers = e.Message.AdditionalRecords;
                foreach (ResourceRecord record in answers)
                {
                    if ((record is TXTRecord) && this.ForMe)
                    {
                        foreach (string str in ((TXTRecord)record).Strings)
                        {
                            char[]   separator = new char[] { '=' };
                            string[] strArray  = str.Split(separator);
                            if (strArray.Length == 2)
                            {
                                if (strArray[0] == "address")
                                {
                                    string text1 = strArray[1];
                                }
                                if (strArray[0] == "multicast")
                                {
                                    this.multicastIp = strArray[1];
                                }
                            }
                        }
                    }
                }

                if ((this.srvRec != null) && (this.ForMe && ((this.srvRec.Port != 0) && (!string.IsNullOrEmpty(this.multicastIp) && (this.udpClient == null)))))
                {
                    if (predicate == null)
                    {
                        predicate = p => p.Port == this.srvRec.Port;
                    }
                    if (Enumerable.Any <IPEndPoint>(IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners(), predicate))
                    {
                        Console.WriteLine(string.Format("{0}:{1} already in use. Try again later", this.multicastIp, this.srvRec.Port));
                    }
                    else
                    {
                        Console.WriteLine("FeedbackType.Client: " + string.Format("JoinMulticastGroup {0}:{1}", this.multicastIp, this.srvRec.Port));
                        udpClient = new UdpClient(this.srvRec.Port);
                        udpClient.JoinMulticastGroup(IPAddress.Parse(this.multicastIp), 50);
                        receiveThread = new Thread(new ThreadStart(this.Receive));
                        receiveThread.Start();
                    }
                }
            };

            advertiseThread = new Thread(new ThreadStart(() =>
            {
                sd     = new ServiceDiscovery(mdns);
                var sp = new ServiceProfile(servicename, domainName, 14005);
                sp.AddProperty("host", "192.168.88.239");
                sp.AddProperty("port", "14005");
                sp.Resources.Add(new ARecord {
                    Name = "_itxpt_multicast._tcp", Address = IPAddress.Parse("192.168.88.239"), Class = DnsClass.IN
                });
                sp.Resources.Add(new SRVRecord {
                    Name = "_itxpt_multicast._tcp", Port = 14005, Priority = 0, Weight = 0, Class = DnsClass.IN
                });
                sd.Advertise(sp);
            }));

            advertiseThread.Start();

            mdns.Start();
        }
        public MDNSServicePublisher()
        {
            Task.Run(() => {
                var mdns     = new MulticastService();
                mdns.UseIpv6 = false;
                foreach (var a in MulticastService.GetIPAddresses())
                {
                    Debug.WriteLine($"IP address {a}");
                }

                mdns.QueryReceived += (s, e) =>
                {
                    var names = e.Message.Questions
                                .Select(q => q.Name + " " + q.Type);
                    Debug.WriteLine($"got a query for {String.Join(", ", names)}");
                };
                mdns.AnswerReceived += (s, e) =>
                {
                    var names = e.Message.Answers
                                .Select(q => q.Name + " " + q.Type)
                                .Distinct();
                    Debug.WriteLine($"got answer for {String.Join(", ", names)}");
                };
                mdns.NetworkInterfaceDiscovered += (s, e) =>
                {
                    foreach (var nic in e.NetworkInterfaces)
                    {
                        Debug.WriteLine($"discovered NIC '{nic.Name}'");
                    }
                };

                var sd = new ServiceDiscovery(mdns);

                var address = new List <IPAddress>();
                address.Add(IPAddress.Parse("10.113.81.192"));

                var s1 = new ServiceProfile("JOSHMobile", "_airplay._tcp.", 7000, address);
                s1.AddProperty("deviceid", "00:05:A6:16:45:8F");
                s1.AddProperty("features", "0xA7FFFF7,0xE");
                s1.AddProperty("flags", "0x4");
                s1.AddProperty("model", "AppleTV5,3");
                s1.AddProperty("pi", "6b448552-85ce-4143-a896-e28d12e8a0ab");
                s1.AddProperty("pk", "F381DC574DEAF9C70B75297755BC7C7C35BB1D0DB500258F3AB46B5FE7C7355B");
                s1.AddProperty("srcvers", "220.68");
                s1.AddProperty("vv", "2");



                var s2 = new ServiceProfile("0005A616458F@JOSHMobile", "_raop._tcp.", 7000, address);
                s2.AddProperty("am", "AppleTV5,3");
                s2.AddProperty("ch", "2");
                s2.AddProperty("cn", "0,1,2,3");
                s2.AddProperty("da", "true");
                s2.AddProperty("ek", "1");
                s2.AddProperty("et", "0,3,5");
                s2.AddProperty("md", "0,1,2");
                s2.AddProperty("pw", "false");
                s2.AddProperty("sm", "false");
                s2.AddProperty("sr", "44100");
                s2.AddProperty("ss", "16");
                s2.AddProperty("sv", "false");
                s2.AddProperty("tp", "UDP");
                s2.AddProperty("txvers", "1");
                s2.AddProperty("vn", "65537");
                s2.AddProperty("vs", "220.68");
                s2.AddProperty("sf", "0x4");
                s2.AddProperty("ft", "0xA7FFFF7,0xE");
                s2.AddProperty("pk", "F381DC574DEAF9C70B75297755BC7C7C35BB1D0DB500258F3AB46B5FE7C7355B");
                s2.AddProperty("vv", "2");

                sd.Advertise(s2);
                sd.Advertise(s1);
                mdns.Start();
            }
                     );
        }
Beispiel #31
0
 ///<exclude/>
 public bool Equals(ServiceProfile other)
 {
     if (ReferenceEquals(null, other)) return false;
     if (ReferenceEquals(this, other)) return true;
     return other._Id == (_Id) && other._InterfaceType == (_InterfaceType) && other._Properties.SequenceEqual(_Properties) && other._Service == (_Service);
 }