@@ -18,18 +18,37 @@ await client.ConnectAsync(serverUri, CancellationToken.None);
1818
1919using IWebSocketPipe pipe = WebSocketPipe .Create (client , closeWhenCompleted : true );
2020
21- var read = Task .Run (async () =>
22- {
23- var read = await pipe .Input .ReadAsync ();
24- Output .WriteLine (" Client: " + Encoding .UTF8 .GetString (read .Buffer ));
25- await pipe .CompleteAsync (WebSocketCloseStatus .NormalClosure , " Client Done" );
26- });
27-
21+ // Start the pipe before hooking up the processing
2822var run = pipe .RunAsync ();
2923
30- await pipe .Output .WriteAsync (Encoding .UTF8 .GetBytes (" hello" ).AsMemory ());
31-
24+ // Wait for completion of processing code
25+ await Task .WhenAny (
26+ ReadIncoming (pipe .Input ),
27+ SendOutgoing (pipe .Output ));
3228
29+ // When the processing completes, the overall pipe run will also complete
30+ await run ;
3331
32+ // Reads incoming data and writes to the console
33+ async Task ReadIncoming (PipeReader reader )
34+ {
35+ while (await reader .ReadAsync () is var result && ! result .IsCompleted )
36+ {
37+ Console .WriteLine ($" Received: {Encoding .UTF8 .GetString (result .Buffer )}" );
38+ reader .AdvanceTo (result .Buffer .Start , result .Buffer .End );
39+ }
40+ Console .WriteLine ($" Done reading." );
41+ }
42+
43+ // Reads console input and writes to pipe until an empty line is entered
44+ async Task SendOutgoing (PipeWriter writer )
45+ {
46+ while (Console .ReadLine () is var line && line ? .Length > 0 )
47+ {
48+ Encoding .UTF8 .GetBytes (line , writer );
49+ }
50+ await writer .CompleteAsync ();
51+ Console .WriteLine ($" Done writing." );
52+ }
3453```
3554
0 commit comments