Exemple #1
0
        private async Task ReceiveLoop(CancellationToken cancellationToken)
        {
            using var textReader     = new StreamReader(this.stream, messageEncoding);
            using var pushbackReader = new PushbackTextReader(textReader);
            while (true)
            {
                cancellationToken.ThrowIfCancellationRequested();
                MessageBase message;
                try {
                    message = await TaskExtensions.WhenAny(
                        MessageBase.ReadMessage(pushbackReader, cancellationToken),
                        Task.Delay(TimeSpan.FromSeconds(ReceiveTimeoutSeconds), cancellationToken)
                        .Then(() => (MessageBase)null)
                        );
                } catch (JsonReaderException ex) {
                    Console.WriteLine(
                        $"Error reading message, aborting receive loop: {ex.Message}"
                        );

                    this.Shutdown();
                    return;
                }

                if (message == null)
                {
                    Console.WriteLine("Receive Timeout!");
                    // a timeout occurred!
                    this.Shutdown();
                    return;
                }

                var hubClient = this.hubContext.Clients.Client(this.hubConnectionId);

                if (hubClient == null)
                {
                    Console.WriteLine("Browser Disconnected!");
                    // Our client disconnected!
                    this.Shutdown();
                    return;
                }

                Console.WriteLine($"Message received: {message}");
                await hubClient.ReceiveMessage(message, cancellationToken);
            }
        }