forked from Linq2GraphQL/Linq2GraphQL.Client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSSEClient.cs
More file actions
58 lines (47 loc) · 1.74 KB
/
SSEClient.cs
File metadata and controls
58 lines (47 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using System.Net.Http.Headers;
using System.Net.Mime;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Text;
using System.Text.Json;
namespace Linq2GraphQL.Client.Subscriptions;
public class SSEClient : IDisposable
{
private readonly GraphClient graphClient;
private readonly GraphQLRequest payload;
private readonly Subject<string> subscriptionSubject = new();
private HttpResponseMessage response;
private StreamReader streamReader;
public SSEClient(GraphClient graphClient, GraphQLRequest payload)
{
this.graphClient = graphClient;
this.payload = payload;
}
public IObservable<string> Subscription => subscriptionSubject.AsObservable();
public void Dispose()
{
streamReader?.Dispose();
response?.Dispose();
}
public async Task Start()
{
var json = JsonSerializer.Serialize(payload, graphClient.SerializerOptions);
var request = new HttpRequestMessage(HttpMethod.Post, "")
{
Content = new StringContent(json, Encoding.UTF8, MediaTypeNames.Application.Json)
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream"));
response = await graphClient.HttpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
response.EnsureSuccessStatusCode();
streamReader = new StreamReader(await response.Content.ReadAsStreamAsync());
while (!streamReader.EndOfStream)
{
var message = await streamReader.ReadLineAsync();
if (message.StartsWith("data: "))
{
var jsonData = message.Substring(6);
subscriptionSubject.OnNext(jsonData);
}
}
}
}