Add automatic keep-alive to Server Sent Events
As the provider of an event stream, I would like the connection to be automatically be kept alive so that I do not have to manually send dummy messages or comments once in a while.
Example
If enabled, the handler would spawn an additional thread that frequently sends a comment or ping event to the connected client to prevent the connection from being terminated by a proxy and to check whether the client is still connected. If sending the comment fails, the handler should cancel the generator logic using a CancellationToken. Both threads would need to be carefully be synchronized to prevent them from writing to the connection at the same time.
var source = EventSource.Create()
.Generator(...)
.KeepAlive();
Acceptance criteria
- Keeping the connection alive is an optional feature
- If the keep alive functionality detects that the client is no longer active the generator logic can be cancelled
- Write access to the connection is synchronized
- The feature is documented on the website
The problem fits to the producer/consumer pattern (some process writing to the connection is consumer and Ping / user logic are producers of events). In C# you can largely utilize BlockingCollection<>. If you want a bit more syntactic sugar around BlockingCollection, you can use 3rd party AsyncCollection.