示例#1
0
        private void Connected()
        {
            var key = Identity.GetUserId();

            var newUser = connectionManager.Add(key, Context.ConnectionId, Identity.Name);

            if (newUser)
            {
                Clients.Others.UserConnected(key, Identity.Name);
            }
        }
        public override async Task OnConnectedAsync()
        {
            var httpContext = Context.GetHttpContext();
            var userId      = httpContext.User.Claims.ToTokenPayload().UserClaims.Id;

            var connectionId = Context.ConnectionId;

            _connectionManager.Add(userId, connectionId);

            var notifications = await _notificationCache.Get(userId);

            await Clients.Caller.SeedNotifications(notifications.Select(x => x.ToDto()));

            await base.OnConnectedAsync();
        }
示例#3
0
        public async Task ListenAsync(int port, CancellationTokenSource cancellationSource)
        {
            try
            {
                var ep = new IPEndPoint(IPAddress.Any, port);
                _listener.Bind(ep);
                _listener.Listen(100);

                _logger.LogInformation("Started Socket Listener on '{0}'", ep.ToString());

                while (!cancellationSource.Token.IsCancellationRequested)
                {
                    var client = await _listener.AcceptAsync();

                    _logger.LogInformation("Accepted a socket connection from '{0}'.", client.RemoteEndPoint.ToString());

                    var connection = new TcpConnection(client, _logger);
                    _connections.Add(connection);
                    _connectionManager.Add(connection);
                    connection.BeginReceive();
                }
            }
            catch (Exception ex)
            {
                cancellationSource.Cancel(false);
                throw ex;
            }

            foreach (var conn in _connections)
            {
                _connectionManager.Remove(conn);
                await conn.CloseAsync();
            }

            if (_listener != null)
            {
                _connectionManager.Disconnected -= OnConnectionDisconnected;
                _listener.Shutdown(SocketShutdown.Both);
                _listener.Dispose();
                _listener = null;
            }
        }