I'd like to create:
So far this is my Code:
Client
public async Task SubscribeToUpdates()
{
this.subscribe = false;
try
{
var client = new HttpClient();
var stream = await client.GetStreamAsync(Constants.SubscribeEndpoint);
using (var rdr = new StreamReader(stream))
{
while (!rdr.EndOfStream && !subscribe)
{
var result = rdr.ReadLine();
var json = JObject.Parse(result);
this.HandleUpdateResult(json); // todo
}
}
}
catch (Exception e)
{
// TO do: log exception
}
}
Server, not working
[HttpGet]
public Task PushStreamContent()
{
HttpContext.Response.ContentType = "text/event-stream";
var sourceStream = randomStream();
return sourceStream.CopyToAsync(HttpContext.Response.Body);
}
public static Stream randomStream()
{
Random rnd = new Random();
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(JsonConvert.SerializeObject(rnd.News(0,255));
writer.Flush();
stream.Position = 0;
return stream;
}
Question:
Working Full .Net Version
I've managed to write the Code for .net Standard, but not for .net core. Reason for this is that PushStreamContent does not exist in .net core :/.
[HttpGet]
public HttpResponseMessage PushStreamContent()
{
var response = Request.CreateResponse(HttpStatusCode.Accepted);
response.Content =
new PushStreamContent((stream, content, context) =>
{
var plotter = new Plotter();
while (true)
{
using (var writer = new StreamWriter(stream))
{
Random rnd = new Random()
writer.WriteLine(rnd.Next(0,255));
stream.Flush();
Thread.Sleep(20);
}
}
});
return response;
}
Thanks to the previous Answer from "Mike McCaughan" and "Joel Harkes", i've rethinked the communcation process and switched from REST to Websockets.
You can find a good Example how to use WebSockets in .net Core (and Xamarin.Forms) here. You will have to use the Nuget Package "Websockets.PCL".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With