tesses-cms/Tesses.CMS.Client/SSEClient.cs

69 lines
1.5 KiB
C#

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<SSEClient> 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<T>()
{
return JsonConvert.DeserializeObject<T>(Data);
}
}
public class SSEClient
{
Stream strm;
public SSEClient(Stream strm)
{
this.strm=strm;
}
public async IAsyncEnumerable<SSEEvent> 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));
}
}
}
}
}