Exemplo n.º 1
0
        public override async Task OnConnectedAsync()
        {
            var ci = Context.GetClient(_options);

            var skip = false;

            if (!Context.GetHttpRequest().IsAccess(_options))
            {
                _logger.LogWarning(
                    $"{ci} access denied");
                skip = true;
            }

            await base.OnConnectedAsync();

            if (!skip && (string.IsNullOrWhiteSpace(ci.Name) || string.IsNullOrWhiteSpace(ci.Ip)))
            {
                _logger.LogWarning(
                    $"{ci} is not valid");
                skip = true;
            }

            if (!skip)
            {
                try
                {
                    var client = await _clientStore.GetClient(ci.Name, ci.Group);

                    if (client == null)
                    {
                        await _clientStore.AddClient(ci);

                        _logger.LogInformation(
                            $"{ci} register success");
                        return;
                    }

                    // SSN 崩溃导致没有设置 IsConnected 为 false, 所以需要检测心跳
                    if (!client.IsConnected ||
                        (DateTime.Now - (client.LastModificationTime ?? client.CreationTime)).Seconds < 7)
                    {
                        await _clientStore.ConnectClient(ci.Name, ci.Group, ci.ConnectionId);

                        _logger.LogInformation(
                            $"{ci} register success");
                        return;
                    }
                    else
                    {
                        _logger.LogInformation(
                            $"[{ci.Name}, {ci.Group}] is connected already");
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex,
                                     $"{ci} register failed: {ex.Message}");
                }
            }

            Context.Abort();
        }