using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json; namespace Tesses.CMS.Client { public static class SSEExtensions { public static async Task GetSSEClientAsync(this HttpClient clt,string url) { var strm=await clt.GetStreamAsync(url); return new SSEClient(strm); } } public class SSEEvent { public SSEEvent(string data) { Data=data; } public string Data {get;set;} public T ParseJson() { return JsonConvert.DeserializeObject(Data); } } public class SSEClient { Stream strm; public SSEClient(Stream strm) { this.strm=strm; } public async IAsyncEnumerable ReadEventsAsync([EnumeratorCancellation]CancellationToken token=default(CancellationToken)) { using(var sr = new StreamReader(strm)){ token.Register(()=>{ sr.Dispose(); }); while(!token.IsCancellationRequested) { string text=""; try{ text=await sr.ReadLineAsync(); }catch(Exception ex) { _=ex; } if(!string.IsNullOrWhiteSpace(text)) yield return new SSEEvent(text.Substring(6)); } } } } }