Server Streaming in SignalR
Learn to add the streaming functionality in SignalR servers.
Introduction
As the name suggests, server streaming works the other way. However, you still need a client involved. The client needs to trigger a server streaming endpoint on the server. Once it’s triggered, it will subscribe to the stream and read messages from it either until no more messages are left or the server disconnects the stream.
Press + to interact
We will now add some server streaming functionality to our clients and the server-side hub. This time, we'll start with the server because it controls the stream.
Adding server streaming capabilities to SignalR Hub
In the LearningHub.cs
file inside the SignalRServer
project, we'll add the following namespace reference:
using System.Runtime.CompilerServices;
Then, we'll add the following method:
Press + to interact
public async IAsyncEnumerable<string> TriggerStream(int jobsCount,[EnumeratorCancellation]CancellationToken cancellationToken){for (var i = 0; i < jobsCount; i++){cancellationToken.ThrowIfCancellationRequested();yield return $"Job {i} executed successfully";await Task.Delay(1000, cancellationToken);}}
...