public async Task Listen(CancellationToken token) { while (!token.IsCancellationRequested) { System.Collections.Generic.Queue <object> payload = await _pipeFormatter.ReceivePayloadAsync(token); if (!(payload.Dequeue() is RelayHeader serverHeader)) { throw new InvalidDataException("Header was not a RelayHeader."); } switch (serverHeader) { case RelayHeader.Disconnected: Disconnected?.Invoke(this, (MqttEndpointDisconnected)payload.Dequeue()); break; case RelayHeader.MessageEvent: _receiver.OnNext((MqttApplicationMessage)payload.Dequeue()); break; default: throw new InvalidDataException("Unknown Relay Header."); } } }
async Task Run(CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { Queue <object> payload = await _pf.ReceivePayloadAsync(cancellationToken); if (!(payload.Dequeue() is StubClientHeader clientHeader)) { throw new InvalidOperationException("Payload did not start with a ClientHeader."); } switch (clientHeader) { case StubClientHeader.Disconnect: await _client.DisconnectAsync(); _m.Warn($"Disconnect should have empty payload, but the payload contain ${payload.Count} objects."); break; case StubClientHeader.Connect: SessionState state; if (payload.Count == 1) { state = await _client.ConnectAsync((MqttLastWill)payload.Dequeue()); } else if (payload.Count == 3) { state = await _client.ConnectAsync((MqttClientCredentials)payload.Dequeue(), (MqttLastWill)payload.Dequeue(), (bool)payload.Dequeue()); } else { throw new InvalidOperationException("Payload count is incorrect."); } await _pf.SendPayloadAsync(state); break; case StubClientHeader.Publish: await _client.PublishAsync((MqttApplicationMessage)payload.Dequeue(), (MqttQualityOfService)payload.Dequeue(), (bool)payload.Dequeue()); break; case StubClientHeader.Subscribe: await _client.SubscribeAsync((string)payload.Dequeue(), (MqttQualityOfService)payload.Dequeue()); break; case StubClientHeader.Unsubscribe: await _client.UnsubscribeAsync((string[])payload.Dequeue()); break; case StubClientHeader.IsConnected: await _pf.SendPayloadAsync(_client.IsConnected); break; default: throw new InvalidOperationException("Unknown ClientHeader."); } } }