Overview

Configure The WebSockets

app.UseWebSockets();
app.UseWebSockets(new WebSocketOptions()
{
    KeepAliveInterval = TimeSpan.FromSeconds(120),
    ReceiveBufferSize = 4 * 1024
});

app.Use(async (context, next) =>
{
	if (context.Request.Path == "/ws")
	{
		if (context.WebSockets.IsWebSocketRequest)
		{
			WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
			await Echo(context, webSocket);
		}
		else context.Response.StatusCode = 400;
	}
	else await next();
});

Send & Receive Messages

private async Task Echo(HttpContext context, WebSocket webSocket)
{
    var buffer = new byte[1024 * 4];
    var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
    while (!result.CloseStatus.HasValue)
    {
        await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count),
            result.MessageType, result.EndOfMessage, CancellationToken.None);
        result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
    }
    await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
}

SignalR