WebSocketPipe 0.9.0

dotnet add package WebSocketPipe --version 0.9.0                
NuGet\Install-Package WebSocketPipe -Version 0.9.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="WebSocketPipe" Version="0.9.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add WebSocketPipe --version 0.9.0                
#r "nuget: WebSocketPipe, 0.9.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install WebSocketPipe as a Cake Addin
#addin nuget:?package=WebSocketPipe&version=0.9.0

// Install WebSocketPipe as a Cake Tool
#tool nuget:?package=WebSocketPipe&version=0.9.0                

Version Downloads License

Usage

using Devlooped.Net;

var client = new ClientWebSocket();
await client.ConnectAsync(serverUri, CancellationToken.None);

using IWebSocketPipe pipe = WebSocketPipe.Create(client, closeWhenCompleted: true);

// Start the pipe before hooking up the processing
var run = pipe.RunAsync();

The IWebSocketPipe interface extends IDuplexPipe, exposing Input and Output properties that can be used to read incoming messages and write outgoing ones.

For example, to read incoming data and write it to the console, we could write the following code:

await ReadIncoming(pipe.Input);

async Task ReadIncoming(PipeReader reader)
{
    while (await reader.ReadAsync() is var result && !result.IsCompleted)
    {
        Console.WriteLine($"Received: {Encoding.UTF8.GetString(result.Buffer)}");
        reader.AdvanceTo(result.Buffer.End);
    }
    Console.WriteLine($"Done reading.");
}

Similarly, to write to the underlying websocket the input entered in the console, we use code like the following:

await SendOutgoing(pipe.Output);

async Task SendOutgoing(PipeWriter writer)
{
    while (Console.ReadLine() is var line && line?.Length > 0)
    {
        Encoding.UTF8.GetBytes(line, writer);
    }
    await writer.CompleteAsync();
    Console.WriteLine($"Done writing.");
}

If we wanted to simultaneously read and write and wait for completion of both operations, we could just wait for both tasks:

// Wait for completion of processing code
await Task.WhenAny(
    ReadIncoming(pipe.Input),
    SendOutgoing(pipe.Output));

Note that completing the PipeWriter automatically causes the reader to reveive a completed result and exit the loop. In addition, the overall IWebSocketPipe.RunAsync task will also run to completion.

The IWebSocketPipe takes care of gracefully closing the connection when the input or output are completed, if closeWhenCompleted is set to true when creating it.

Alternatively, it's also possible to complete the entire pipe explicitly, while setting an optional socket close status and status description for the server to act on:

await pipe.CompleteAsync(WebSocketCloseStatus.NormalClosure, "Done processing");

Specifying a close status will always close the underlying socket.

You can also use it on the server. This example is basically taken from the documentation on WebSockets in ASP.NET Core and adapted to use a WebSocketPipe to read/write to the client:

app.Use(async (context, next) =>
{
    if (context.Request.Path == "/ws")
    {
        if (context.WebSockets.IsWebSocketRequest)
        {
            using var websocket = await context.WebSockets.AcceptWebSocketAsync();
            using var pipe = WebSocketPipe.Create(websocket, true);
            await Task.WhenAll(Echo(pipe), pipe.RunAsync(context.RequestAborted));
        }
        else
        {
            context.Response.StatusCode = (int) HttpStatusCode.BadRequest;
        }
    }
    else
    {
        await next();
    }
});

The sample Echo method is simply:

async Task Echo(IDuplexPipe pipe)
{
    while (await pipe.Input.ReadAsync() is var result && !result.IsCompleted)
    {
        // Just assume we get a single-segment entry, for simplicity
        await pipe.Output.WriteAsync(result.Buffer.First);
        pipe.Input.AdvanceTo(result.Buffer.End);
    }
}

Sponsors

sponsored clariusclarius

get mentioned here too!

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.1 is compatible. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
0.9.0 2,090 10/4/2021
0.8.1 310 9/23/2021
0.8.0 336 9/22/2021