user3079834
user3079834

Reputation: 2214

Receive Server Sent Events (SSE) in UWP

I have an ASP.net core 3.1 server project that has a very simple API sending one-way Server Sent Events (SSE) like this:

[HttpGet]
public async Task Get()
{
    var response = Response;
    response.Headers.Add("Content-Type", "text/event-stream");
    response.Headers.Add("Cache-Control", "no-cache");
    response.Headers.Add("Connection", "keep-alive");

    for (var i = 0; true; ++i)
    {
        await response.WriteAsync($"id: unique{i}\n");
        await response.WriteAsync("event: add\n");
        //await response.WriteAsync("retry: 10000\n");
        await response.WriteAsync($"data: Controller {i} at {DateTime.Now}\n\n");

        response.Body.Flush();
        await Task.Delay(5 * 1000);
    }
}

Now I want to receive these events via C# UWP Client. Unfortunately I only receive the first event:

using (var client = new HttpClient())
{
    using (var stream = await client.GetStreamAsync("http://localhost:5000/api/subscription"))
    {
        using (var reader = new StreamReader(stream))
        {
            while (true)
            {
                Console.WriteLine(reader.ReadLine());
            }
        }
    }
}

How can I create a behavior in UWP in order to always listen to that connection and receiving events that I can process further?

Upvotes: 3

Views: 7242

Answers (2)

user3079834
user3079834

Reputation: 2214

I found a solution here https://techblog.dorogin.com/server-sent-event-aspnet-core-a42dc9b9ffa9. The trick was to not set up a WebAPI-call that continuously returns data like in the question but to create a data-strem with the MIME-type text/event-stream.

On the UWP client side you then read the stream like this:

var stream = httpClient.GetStreamAsync(requestUri).Result;

using (var reader = new StreamReader(stream))
{
    while (!reader.EndOfStream)
    {
        Debug.WriteLine(reader.ReadLine());
    }
}

Upvotes: 3

Anran Zhang
Anran Zhang

Reputation: 7727

HttpClient begins by initiating a request and ends when it receives the data returned by the server.

This is equivalent to making only one request. If you want to build a continuous data transmission channel between the application and the server, try using WebSocket

Here is a code example using WebSocket for reference: WebSocket sample


In addition, when debugging with Visual Studio, you can access localhost, but when publishing the application, UWP will not be able to access localhost due to the local network loopback

Thanks.

Upvotes: 1

Related Questions