Ejemplo n.º 1
0
        private async Task HandleIncomingDataAsync(StreamReader reader, CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    var command = await _playerCommandFactory.CreateAsync(reader, cancellationToken).ConfigureAwait(false);
                    if (command == null)
                    {
                        if (reader.EndOfStream)
                        {
                            return;
                        }

                        continue;
                    }

                    command.Validate(_player, _game);

                    var commandResponseDto = command.Execute(_player, _game);
                    Send(commandResponseDto);
                }
                catch (CommandException exception)
                {
                    var commandResponseDto = new CommandResponseDto
                    {
                        ErrorCode = (int)exception.ErrorCode,
                        Message = exception.Message
                    };
                    Send(commandResponseDto);
                }
                catch
                {
                    return;
                }
            }
        }
Ejemplo n.º 2
0
        private async Task HandleConnection(
            CancellationTokenSource cancellationTokenSource,
            StreamReader reader,
            StreamWriter writer)
        {
            var json = await reader.ReadJsonAsync(cancellationTokenSource.Token);

            var loginDto = json.FromJson<LoginDto>();

            var commandResponseDto = new CommandResponseDto { ErrorCode = (int)CommandErrorCode.Success };
            if (!TryAuthorize(loginDto))
            {
                commandResponseDto.ErrorCode = (int)CommandErrorCode.WrongLogin;
                await writer.WriteLineAsync(commandResponseDto.ToJson()).ConfigureAwait(false);
                return;
            }

            await writer.WriteLineAsync(commandResponseDto.ToJson()).ConfigureAwait(false);

            var connection = _connectionFactory.Create(loginDto);
            lock (ConnectionsLock)
            {
                _connections.Add(connection);
            }
            try
            {
                await connection.RunAsync(reader, writer, cancellationTokenSource).ConfigureAwait(false);
            }
            finally
            {
                lock (ConnectionsLock)
                {
                    _connections.Remove(connection);
                }

                Log.Info($"{loginDto.Login} disconnected");
            }
        }