示例#1
0
    public async Task ExecuteAsync(TcpClient tcpClient, CancellationToken stoppingToken)
    {
        _logger.LogTrace("Client started at: {time}", DateTime.Now);

        try
        {
            await using var bufferedStream = new BufferedStream(tcpClient.GetStream());
            using var streamReader         = new StreamReader(bufferedStream, Encoding);
            await using var streamWriter   = new StreamWriter(bufferedStream, Encoding);

            if (tcpClient.Connected)
            {
                var coreAudioController = _cachingCoreAudioController.GetCoreAudioController(stoppingToken);
                await SendCurrentAudioStateAsync(streamWriter, coreAudioController, stoppingToken);
            }

            while (tcpClient.Connected)
            {
                _logger.LogTrace("Reading message from client.");
                var message = await streamReader.ReadLineAsync();

                if (message == null)
                {
                    break;
                }

                _logger.LogTrace("Reading complete, deserialising message from client.");
                var audioUpdate = JsonConvert.DeserializeObject <PcAudio>(message, JsonSettings);
                if (audioUpdate !.ProtocolVersion != ProtocolVersion)
                {
                    throw new InvalidOperationException(
                              $"Protocol version mismatch Client('{audioUpdate.ProtocolVersion}') != " +
                              $"Server('{ProtocolVersion}')");
                }

                var coreAudioController = _cachingCoreAudioController.GetCoreAudioController(stoppingToken);
                await UpdateStateAsync(audioUpdate, coreAudioController, stoppingToken);
                await SendCurrentAudioStateAsync(streamWriter, coreAudioController, stoppingToken);
            }
        }
        catch (Exception e)
        {
            if (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogError(e, $"Exception occurred for client and {nameof(stoppingToken)} was not cancelled.");
            }
        }

        _logger.LogTrace("Client ended at: {time}", DateTime.Now);
    }
示例#2
0
 protected override async Task ExecuteAsync(CancellationToken stoppingToken)
 {
     // Perform an initial loading of Core Audio Controller to warm up the application.
     // The Core Audio Controller library can take some time to return and is blocking.
     await Task.Run(() => _cachingCoreAudioController.GetCoreAudioController(stoppingToken), stoppingToken);
 }