WebSockets over HTTP/2

WebSockets over HTTP/2 using ASP.NET

NET 7 introduces Websockets over HTTP/2 support for Kestrel, the SignalR JavaScript client, and SignalR with Blazor WebAssembly.

HTTP2

  • Multiplexing Request multiplexing
  • Server push cacheable information
  • Header compression HPACK

ref site:

os and browsers support

Note: recommended to use Chrome/FireFox

WebSockets

Enable WebSocket

  • default
app.UseWebSockets()
  • options
var webSocketOptions = new WebSocketOptions
{
    KeepAliveInterval = TimeSpan.FromMinutes(2)
};

app.UseWebSockets(webSocketOptions);

Accept WebSocket requests

if (HttpContext.WebSockets.IsWebSocketRequest)
{
    using var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
}

receive messages

var buffer = new byte[1024 * 4];

var receiveResult = await webSocket.ReceiveAsync(
    new ArraySegment<byte>(buffer), CancellationToken.None);

ArraySegment

Array version of substring()

String[] names = { "Adam", "Bruce", "Charles", "Daniel",
                         "Ebenezer", "Francis", "Gilbert",
                         "Henry", "Irving", "John", "Karl",
                         "Lucian", "Michael" };
      var partNames = new ArraySegment<string>(names, 2, 5);

The example displays the following output:

//    Charles
//    Daniel
//    Ebenezer
//    Francis
//    Gilbert

Send messages

var memory = new ReadOnlyMemory<byte>(Encoding.UTF8.GetBytes(str));

await webSocket.SendAsync(
                memory,
                0, // text message
                0, // none
                CancellationToken.None);

ReadOnlyMemory

var memory = new ReadOnlyMemory<byte>(Encoding.UTF8.GetBytes(str));

MessageType

  • Binary
1

The message is in binary format.

  • Close
2

A receive has completed because a close message was received.

  • Text
0

The message is clear text.

WebSocketMessageFlags

  • DisableCompression
2

Disables compression for the message if compression has been enabled for the WebSocket instance.

  • EndOfMessage
1

Indicates that the data in “buffer” is the last part of a message.

  • None
0

None

close

await webSocket.CloseAsync(
            1000,  // NormalClosure
            "normal closure",
            CancellationToken.None);

WebSocketCloseStatus

Fields:

1000, 1001, 1002, 1003, 1005, 1007, 1008, 1009, 1010, 1100

Samples

  • WebSocketController
    Operation WebSocket
  • Program.cs
    Enable WebSocket

Ref