|
1 | | -[](https://www.nuget.org/packages/WebSocketPipe) |
2 | | -[](https://www.nuget.org/packages/WebSocketPipe) |
3 | | -[](https://github.com/devlooped/WebSocketPipe/blob/main/license.txt) |
4 | | - |
5 | | -# Usage |
6 | | - |
7 | | -```csharp |
8 | | -using Devlooped.Net; |
9 | | - |
10 | | -var client = new ClientWebSocket(); |
11 | | -await client.ConnectAsync(serverUri, CancellationToken.None); |
12 | | - |
13 | | -using IWebSocketPipe pipe = WebSocketPipe.Create(client, closeWhenCompleted: true); |
14 | | - |
15 | | -// Start the pipe before hooking up the processing |
16 | | -var run = pipe.RunAsync(); |
17 | | -``` |
18 | | - |
19 | | -The `IWebSocketPipe` interface extends [IDuplexPipe](https://docs.microsoft.com/en-us/dotnet/api/system.io.pipelines.iduplexpipe?view=dotnet-plat-ext-5.0), |
20 | | -exposing `Input` and `Output` properties that can be used to |
21 | | -read incoming messages and write outgoing ones. |
22 | | - |
23 | | -For example, to read incoming data and write it to the console, |
24 | | -we could write the following code: |
25 | | - |
26 | | -```csharp |
27 | | -await ReadIncoming(pipe.Input); |
28 | | - |
29 | | -async Task ReadIncoming(PipeReader reader) |
30 | | -{ |
31 | | - while (await reader.ReadAsync() is var result && !result.IsCompleted) |
32 | | - { |
33 | | - Console.WriteLine($"Received: {Encoding.UTF8.GetString(result.Buffer)}"); |
34 | | - reader.AdvanceTo(result.Buffer.End); |
35 | | - } |
36 | | - Console.WriteLine($"Done reading."); |
37 | | -} |
38 | | -``` |
39 | | - |
40 | | -Similarly, to write to the underlying websocket the input |
41 | | -entered in the console, we use code like the following: |
42 | | - |
43 | | -```csharp |
44 | | -await SendOutgoing(pipe.Output); |
45 | | - |
46 | | -async Task SendOutgoing(PipeWriter writer) |
47 | | -{ |
48 | | - while (Console.ReadLine() is var line && line?.Length > 0) |
49 | | - { |
50 | | - Encoding.UTF8.GetBytes(line, writer); |
51 | | - } |
52 | | - await writer.CompleteAsync(); |
53 | | - Console.WriteLine($"Done writing."); |
54 | | -} |
55 | | -``` |
56 | | - |
57 | | -If we wanted to simultaneously read and write and wait for |
58 | | -completion of both operations, we could just wait for both |
59 | | -tasks: |
60 | | - |
61 | | -```csharp |
62 | | -// Wait for completion of processing code |
63 | | -await Task.WhenAny( |
64 | | - ReadIncoming(pipe.Input), |
65 | | - SendOutgoing(pipe.Output)); |
66 | | -``` |
67 | | - |
68 | | -Note that completing the `PipeWriter` automatically causes the |
69 | | -reader to reveive a completed result and exit the loop. In addition, |
70 | | -the overall `IWebSocketPipe.RunAsync` task will also run to completion. |
71 | | - |
72 | | - |
73 | | -The `IWebSocketPipe` takes care of gracefully closing the connection |
74 | | -when the input or output are completed, if `closeWhenCompleted` is set |
75 | | -to true when creating it. |
76 | | - |
77 | | -Alternatively, it's also possible to complete the entire pipe explicitly, |
78 | | -while setting an optional socket close status and status description for |
79 | | -the server to act on: |
80 | | - |
81 | | -```csharp |
82 | | -await pipe.CompleteAsync(WebSocketCloseStatus.NormalClosure, "Done processing"); |
83 | | -``` |
84 | | - |
85 | | -Specifying a close status will always close the underlying socket. |
86 | | - |
87 | | -You can also use it on the server. This example is basically taken from |
88 | | -the documentation on [WebSockets in ASP.NET Core](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/websockets?view=aspnetcore-5.0#configure-the-middleware) |
89 | | -and adapted to use a `WebSocketPipe` to read/write to the client: |
90 | | - |
91 | | -```csharp |
92 | | -app.Use(async (context, next) => |
93 | | -{ |
94 | | - if (context.Request.Path == "/ws") |
95 | | - { |
96 | | - if (context.WebSockets.IsWebSocketRequest) |
97 | | - { |
98 | | - using var websocket = await context.WebSockets.AcceptWebSocketAsync(); |
99 | | - using var pipe = WebSocketPipe.Create(websocket, true); |
100 | | - await Task.WhenAll(Echo(pipe), pipe.RunAsync(context.RequestAborted)); |
101 | | - } |
102 | | - else |
103 | | - { |
104 | | - context.Response.StatusCode = (int) HttpStatusCode.BadRequest; |
105 | | - } |
106 | | - } |
107 | | - else |
108 | | - { |
109 | | - await next(); |
110 | | - } |
111 | | -}); |
112 | | -``` |
113 | | - |
114 | | -The sample `Echo` method is simply: |
115 | | - |
116 | | -```csharp |
117 | | -async Task Echo(IDuplexPipe pipe) |
118 | | -{ |
119 | | - while (await pipe.Input.ReadAsync() is var result && !result.IsCompleted) |
120 | | - { |
121 | | - // Just assume we get a single-segment entry, for simplicity |
122 | | - await pipe.Output.WriteAsync(result.Buffer.First); |
123 | | - pipe.Input.AdvanceTo(result.Buffer.End); |
124 | | - } |
125 | | -} |
126 | | -``` |
127 | | - |
128 | | - |
129 | | -## Sponsors |
130 | | - |
131 | | -[](https://github.com/sponsors/devlooped) [](https://github.com/clarius)[](https://github.com/clarius) |
132 | | - |
133 | | -*[get mentioned here too](https://github.com/sponsors/devlooped)!* |
134 | | - |
| 1 | +<!-- include ../../readme.md#content --> |
| 2 | +<!-- include https://github.com/devlooped/sponsors/raw/main/footer.md --> |
135 | 3 |
|
| 4 | +<!-- Exclude from auto-expansion in CI --> |
| 5 | +<!-- exclude --> |
0 commit comments