Server Sent Events

Live on this server

A live ticker that receives prices pushed by the server.

A stock ticker whose price changes every second, pushed by the server to the browser. Server sent events keep a response open and write an event to it whenever there is news - simpler than websockets when data only flows from the server to the client.

EventSource.Create() runs SendQuotesAsync for every client, as long as it stays connected. In the browser, new EventSource('quotes/') receives the events, and reconnects on its own if the connection drops. The prices are made up.

To run it, create a console app (dotnet new console), add GenHTTP (dotnet add package GenHTTP.Full), replace Program.cs with the code below and start it with dotnet run - it answers at http://localhost:8080/.

Program.cs74 lines
using GenHTTP.Engine.Internal;

using GenHTTP.Api.Protocol;

using GenHTTP.Modules.IO;
using GenHTTP.Modules.Layouting;
using GenHTTP.Modules.Practices;
using GenHTTP.Modules.ServerSentEvents;

var quotes = EventSource.Create()
                        .Generator(SendQuotesAsync);

var page = Content.From(Resource.FromString(TickerPage.Html).Type(ContentType.TextHtml));

var app = Layout.Create()
                .Index(page) // GET /
                .Add("quotes", quotes); // GET /quotes/

await Host.Create()
          .Handler(app)
          .Defaults()
          .RunAsync();

// runs for every client as long as it stays connected
static async ValueTask SendQuotesAsync(IEventConnection connection)
{
    var price = 100.0m;
    var id = 0;

    while (connection.Connected)
    {
        var change = Math.Round((decimal)(Random.Shared.NextDouble() - 0.5), 2);

        price += change;

        // serialized to JSON, the browser listens for the "quote" event type
        await connection.DataAsync(new Quote("GENH", price, change), eventType: "quote", eventId: $"{id++}");

        await Task.Delay(1000);
    }
}

public record Quote(string Symbol, decimal Price, decimal Change);

public static class TickerPage
{

    public const string Html =
        """
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="utf-8">
            <title>Ticker</title>
        </head>
        <body>
            <h1>GENH <span id="price">-</span></h1>
            <p id="change"></p>
            <script>
                // reconnects automatically if the connection drops
                const events = new EventSource('quotes/');

                events.addEventListener('quote', (event) => {
                    const quote = JSON.parse(event.data);

                    document.getElementById('price').textContent = quote.price.toFixed(2);
                    document.getElementById('change').textContent = `${quote.change >= 0 ? '+' : ''}${quote.change.toFixed(2)}`;
                });
            </script>
        </body>
        </html>
        """;

}

Try it

Send the requests to the sample running on this server - change the path, headers or body as you like, or copy them as curl commands.

  1. Open the ticker

    PAGE /demo/sse/ Open
  2. Watch the raw event stream

    curl -N https://genhttp.org/demo/sse/quotes/