WebSockets

suggest change

The WebSocket protocol (RFC 6455) provides full-duplex, persistent two-way communication between client and server over a single TCP connection (ws:// and wss://). Unlike standard HTTP request-response cycles, WebSockets allow either party to push data independently with minimal protocol overhead.

In .NET, core WebSocket support is provided by the System.Net.WebSockets namespace through ClientWebSocket (for client connections) and WebSocket abstractions.


1. Connecting as a WebSocket Client with ClientWebSocket

ClientWebSocket is .NET's high-performance, asynchronous WebSocket client.

Complete Client Echo Example

using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

class WebSocketClientExample
{
    static async Task Main()
    {
        using var client = new ClientWebSocket();
        
        // Configure options before connecting
        client.Options.KeepAliveInterval = TimeSpan.FromSeconds(30);
        
        var serverUri = new Uri("wss://echo.websocket.org");
        using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15));

        Console.WriteLine($"Connecting to {serverUri}...");
        await client.ConnectAsync(serverUri, cts.Token);
        Console.WriteLine("Connected!");

        // Start receive loop in the background
        var receiveTask = ReceiveMessagesAsync(client, cts.Token);

        // Send a message
        string message = "Hello from C# ClientWebSocket!";
        byte[] messageBytes = Encoding.UTF8.GetBytes(message);
        await client.SendAsync(
            new ArraySegment<byte>(messageBytes),
            WebSocketMessageType.Text,
            endOfMessage: true,
            cts.Token
        );
        Console.WriteLine($"Sent: {message}");

        // Wait briefly for reply
        await Task.Delay(2000);

        // Graceful close
        if (client.State == WebSocketState.Open)
        {
            await client.CloseAsync(
                WebSocketCloseStatus.NormalClosure,
                "Closing client connection",
                CancellationToken.None
            );
            Console.WriteLine("WebSocket connection closed cleanly.");
        }

        await receiveTask;
    }

    private static async Task ReceiveMessagesAsync(ClientWebSocket client, CancellationToken token)
    {
        byte[] buffer = new byte[4096];

        try
        {
            while (client.State == WebSocketState.Open && !token.IsCancellationRequested)
            {
                var memoryStream = new System.IO.MemoryStream();
                WebSocketReceiveResult result;

                // Loop until the entire frame/message is collected
                do
                {
                    result = await client.ReceiveAsync(new ArraySegment<byte>(buffer), token);

                    if (result.MessageType == WebSocketMessageType.Close)
                    {
                        Console.WriteLine("Received close frame.");
                        return;
                    }

                    memoryStream.Write(buffer, 0, result.Count);
                }
                while (!result.EndOfMessage);

                string received = Encoding.UTF8.GetString(memoryStream.ToArray());
                Console.WriteLine($"Received [{result.MessageType}]: {received}");
            }
        }
        catch (OperationCanceledException)
        {
            // Expected on cancellation
        }
        catch (Exception ex)
        {
            Console.Error.WriteLine($"Receive error: {ex.Message}");
        }
    }
}

2. Standalone WebSocket Server with HttpListener

For lightweight microservices or mock servers without ASP.NET Core dependencies, System.Net.HttpListener can accept and upgrade WebSocket handshakes:

using System;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

class StandaloneWebSocketServer
{
    static async Task Main()
    {
        var listener = new HttpListener();
        string prefix = "http://localhost:5000/";
        listener.Prefixes.Add(prefix);
        listener.Start();

        Console.WriteLine($"WebSocket Server listening on {prefix}...");

        while (true)
        {
            HttpListenerContext context = await listener.GetContextAsync();

            if (context.Request.IsWebSocketRequest)
            {
                _ = ProcessWebSocketRequestAsync(context);
            }
            else
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                context.Response.Close();
            }
        }
    }

    private static async Task ProcessWebSocketRequestAsync(HttpListenerContext context)
    {
        HttpListenerWebSocketContext wsContext = await context.AcceptWebSocketAsync(subProtocol: null);
        WebSocket socket = wsContext.WebSocket;
        Console.WriteLine("Client WebSocket connection established.");

        byte[] buffer = new byte[4096];

        try
        {
            while (socket.State == WebSocketState.Open)
            {
                WebSocketReceiveResult result = await socket.ReceiveAsync(
                    new ArraySegment<byte>(buffer),
                    CancellationToken.None
                );

                if (result.MessageType == WebSocketMessageType.Close)
                {
                    await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
                    break;
                }

                // Echo message back to client
                await socket.SendAsync(
                    new ArraySegment<byte>(buffer, 0, result.Count),
                    result.MessageType,
                    result.EndOfMessage,
                    CancellationToken.None
                );
            }
        }
        catch (Exception ex)
        {
            Console.Error.WriteLine($"Socket exception: {ex.Message}");
        }
        finally
        {
            socket.Dispose();
        }
    }
}

3. WebSockets in ASP.NET Core

In production web applications, ASP.NET Core provides middleware for handling WebSockets:

using System.Net.WebSockets;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseWebSockets(new WebSocketOptions
{
    KeepAliveInterval = TimeSpan.FromSeconds(30)
});

app.Map("/ws", async context =>
{
    if (context.WebSockets.IsWebSocketRequest)
    {
        using var webSocket = await context.WebSockets.AcceptWebSocketAsync();
        var buffer = new byte[1024 * 4];

        while (webSocket.State == WebSocketState.Open)
        {
            var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            if (result.MessageType == WebSocketMessageType.Close)
            {
                await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
                break;
            }

            // Process or echo message...
            await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);
        }
    }
    else
    {
        context.Response.StatusCode = StatusCodes.Status400BadRequest;
    }
});

app.Run();

4. Key Rules and Best Practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents