Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
71 lines (49 loc) · 1.54 KB
/
Copy pathProgram.cs
File metadata and controls
71 lines (49 loc) · 1.54 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
59
60
61
62
63
64
65
66
67
68
69
using System.Text;
using System.Threading.Channels;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddCors();
builder.Services.AddSingleton(
Channel.CreateUnbounded<string>()
);
var app = builder.Build();
app.UseCors(e => e.AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod());
app.MapPost("/send", async (Channel<string> channel, HttpContext context) =>
{
using var reader = new StreamReader(context.Request.Body);
var message = await reader.ReadToEndAsync();
if (string.IsNullOrWhiteSpace(message))
return Results.BadRequest();
await channel.Writer.WriteAsync(message);
return Results.Accepted();
});
app.MapGet("/sse", async (
HttpContext context,
Channel<string> channel) =>
{
try
{
var id = context.Request.Query["id"].ToString();
var token = context.Request.Query["token"].ToString();
context.Response.Headers.Append("Content-Type", "text/event-stream");
context.Response.Headers.Append("Cache-Control", "no-cache");
context.Response.Headers.Append("Connection", "keep-alive");
await foreach (var msg in channel.Reader.ReadAllAsync(
context.RequestAborted))
{
await context.Response.WriteAsync($"data: {msg}\n\n");
await context.Response.Body.FlushAsync();
}
}
catch (TaskCanceledException ex)
{
}
catch (OperationCanceledException ex)
{
}
catch (Exception ex)
{
throw;
}
});
await app.RunAsync();