-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathIndex.razor
87 lines (67 loc) · 2.13 KB
/
Index.razor
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
@page "/"
@implements IDisposable
<h1>Streaming request / response</h1>
Type to send:
<input @bind="Input" @bind:event="oninput" />
You typed: @Message
@code {
string Input
{
get => null;
set
{
pipe.Writer.WriteAsync(System.Text.Encoding.UTF8.GetBytes(value));
}
}
string Message { get; set; }
readonly System.Threading.CancellationTokenSource cts = new System.Threading.CancellationTokenSource();
readonly BrowserHttpHandler handler = new BrowserHttpHandler();
readonly System.IO.Pipelines.Pipe pipe = new System.IO.Pipelines.Pipe();
protected override void OnInitialized()
{
Task.Run(Send);
Task.Run(Receive);
}
async Task Send()
{
try
{
using var request = new HttpRequestMessage(HttpMethod.Post, "/send?channel=123");
request.Options.Set(BrowserHttpHandler.EnableStreamingRequest, true);
request.SetBrowserRequestOption("allowHTTP1ForStreamingUpload", true);
request.Content = new StreamContent(pipe.Reader.AsStream());
using var response = await handler.SendAsync(request, cts.Token);
}
catch (Exception ex)
{
Message = ex.Message;
}
}
async Task Receive()
{
var buffer = new byte[1024];
try
{
using var request = new HttpRequestMessage(HttpMethod.Get, "/receive?channel=123");
request.Options.Set(BrowserHttpHandler.EnableStreamingResponse, true);
using var response = await handler.SendAsync(request, cts.Token);
using var stream = await response.Content.ReadAsStreamAsync();
int readCount;
while ((readCount = await stream.ReadAsync(buffer)) > 0)
{
var str = System.Text.Encoding.UTF8.GetString(buffer, 0, readCount);
Message += str;
StateHasChanged();
}
}
catch (Exception ex)
{
Message = ex.Message;
}
}
public void Dispose()
{
cts.Cancel();
cts.Dispose();
}
}