예제 #1
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);
        }