GithubHelp home page GithubHelp logo

dorucioclea / websocketchannel Goto Github PK

View Code? Open in Web Editor NEW

This project forked from devlooped/websocketchannel

0.0 1.0 0.0 83 KB

High-performance System.Threading.Channels API adapter for System.Net.WebSockets

Home Page: https://clarius.org/WebSocketChannel

License: MIT License

C# 99.22% SCSS 0.78%

websocketchannel's Introduction

Icon WebSocketChannel

High-performance System.Threading.Channels API adapter for System.Net.WebSockets

Version Downloads License Build

Usage

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

Channel<ReadOnlyMemory<byte>> channel = client.CreateChannel();

await channel.Writer.WriteAsync(Encoding.UTF8.GetBytes("hello").AsMemory());

// Read single message when it arrives
ReadOnlyMemory<byte> response = await channel.Reader.ReadAsync();

// Read all messages while underlying websocket is open
await foreach (var item in channel.Reader.ReadAllAsync())
{
    Console.WriteLine(Encoding.UTF8.GetString(item.Span));
}

// Completing the writer closes the underlying websocket cleanly
channel.Writer.Complete();

// Can also complete reporting an error for the remote party
channel.Writer.Complete(new InvalidOperationException("Bad format"));

The WebSocketChannel can also be used on the server. The following example is basically taken from the documentation on WebSockets in ASP.NET Core and adapted to use a WebSocketChannel to echo messages to the client:

app.Use(async (context, next) =>
{
    if (context.Request.Path == "/ws")
    {
        if (context.WebSockets.IsWebSocketRequest)
        {
            using var webSocket = await context.WebSockets.AcceptWebSocketAsync();
            var channel = WebSocketChannel.Create(webSocket);
            try
            {
                await foreach (var item in channel.Reader.ReadAllAsync(context.RequestAborted))
                {
                    await channel.Writer.WriteAsync(item, context.RequestAborted);
                }
            }
            catch (OperationCanceledException)
            {
                try
                {
                    await webSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, null, default);
                }
                catch { } // Best effort to try closing cleanly. Client may be entirely gone.
            }
        }
        else
        {
            context.Response.StatusCode = (int) HttpStatusCode.BadRequest;
        }
    }
    else
    {
        await next();
    }
});

Installation

This project can be used either as a regular nuget package:

<PackageReference Include="WebSocketChannel" Version="*" />

Or alternatively, referenced directly as a source-only dependency using dotnet-file:

> dotnet file add https://github.com/devlooped/WebSocketChannel/blob/main/src/WebSocketChannel/WebSocketChannel.cs
> dotnet file add https://github.com/devlooped/WebSocketChannel/blob/main/src/WebSocketChannel/WebSocketExtensions.cs

It's also possible to specify a desired target location for the referenced source files, such as:

> dotnet file add https://github.com/devlooped/WebSocketChannel/blob/main/src/WebSocketChannel/WebSocketChannel.cs src/MyProject/External/.
> dotnet file add https://github.com/devlooped/WebSocketChannel/blob/main/src/WebSocketChannel/WebSocketExtensions.cs src/MyProject/External/.

When referenced as loose source files, it's easy to also get automated PRs when the upstream files change, as in the dotnet-file.yml workflow that keeps the repository up to date with a template. See also dotnet-config, which is used to for the dotnet-file configuration settings that tracks all this.

Dogfooding

CI Version Build

We also produce CI packages from branches and pull requests so you can dogfood builds as quickly as they are produced.

The CI feed is https://pkg.kzu.io/index.json.

The versioning scheme for packages is:

  • PR builds: 42.42.42-pr[NUMBER]
  • Branch builds: 42.42.42-[BRANCH].[COMMITS]

Sponsors

Clarius Org C. Augusto Proiete Kirill Osenkov MFB Technologies, Inc. Stephen Shaw Torutek DRIVE.NET, Inc. David Kean Daniel Gnägi Ashley Medway Keith Pickford bitbonk Thomas Bolon Yurii Rashkovskii Kori Francis Zdenek Havlin Sean Killeen Toni Wenzel Giorgi Dalakishvili Kelly White Allan Ritchie Mike James Uno Platform Dan Siegel Reuben Swartz Jeremy Simmons Jacob Foshee Eric Johnson Norman Mackay Certify The Web Taylor Mansfield Mårten Rånge David Petric Rich Lee Danilo Dantas Gary Woodfine Steve Bilogan Ix Technologies B.V. New Relic Chris Johnston‮ David JENNI Jonathan Oleg Kyrylchuk

Sponsor this project  

Learn more about GitHub Sponsors

websocketchannel's People

Contributors

kzu avatar dependabot[bot] avatar devlooped-bot avatar corradocavalli avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.