WebSocket in .NET

Introduction

Web applications have evolved and they now require real-time communication between clients and servers. However, traditional HTTP requests have limitations when it comes to establishing persistent connections for ongoing data exchange. This is where WebSocket, a powerful communication protocol, comes into play. It enables full-duplex communication between a client and a server.

What is WebSocket?

WebSocket is a protocol that provides a full-duplex communication channel over a single, long-lived TCP connection. It facilitates real-time, bi-directional communication between a client and a server. Unlike HTTP, which follows a request-response model, WebSocket allows both the client and server to send messages to each other independently.

WebSocket in .NET

In the .NET ecosystem, developers can leverage the System.Net.WebSockets namespace to implement WebSocket functionality in their applications. .NET provides robust support for working with WebSockets, making it relatively straightforward to create WebSocket-based services.

Implementing a WebSocket Server in .NET

To create a WebSocket server in .NET, you can start by setting up  WebSocketListener and handling incoming connections. Here's an example.

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

class WebSocketServer
{
    public async Task StartServer(string ipAddress, int port)
    {
        HttpListener listener = new HttpListener();
        listener.Prefixes.Add($"http://{ipAddress}:{port}/");
        listener.Start();

        Console.WriteLine("Server started. Waiting for connections...");

        while (true)
        {
            HttpListenerContext context = await listener.GetContextAsync();
            if (context.Request.IsWebSocketRequest)
            {
                ProcessWebSocketRequest(context);
            }
            else
            {
                context.Response.StatusCode = 400;
                context.Response.Close();
            }
        }
    }

    private async Task ProcessWebSocketRequest(HttpListenerContext context)
    {
        HttpListenerWebSocketContext webSocketContext = await context.AcceptWebSocketAsync(null);
        WebSocket socket = webSocketContext.WebSocket;

        // Handle incoming messages
        byte[] buffer = new byte[1024];
        while (socket.State == WebSocketState.Open)
        {
            WebSocketReceiveResult result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            if (result.MessageType == WebSocketMessageType.Text)
            {
                string receivedMessage = System.Text.Encoding.UTF8.GetString(buffer, 0, result.Count);
                Console.WriteLine($"Received message: {receivedMessage}");

                // Echo back the received message
                await socket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), WebSocketMessageType.Text, true, CancellationToken.None);
            }
            else if (result.MessageType == WebSocketMessageType.Close)
            {
                await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
            }
        }
    }
}

Implementing a WebSocket Client in .NET

Creating a WebSocket client in .NET involves establishing a connection to a WebSocket server and handling messages. Here's an example.

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

class WebSocketClient
{
    public async Task ConnectToServer(string serverUri)
    {
        ClientWebSocket clientWebSocket = new ClientWebSocket();
        await clientWebSocket.ConnectAsync(new Uri(serverUri), CancellationToken.None);

        Console.WriteLine("Connected to the server. Start sending messages...");

        // Send messages to the server
        string message = "Hello, WebSocket!";
        byte[] buffer = Encoding.UTF8.GetBytes(message);
        await clientWebSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);

        // Receive messages from the server
        byte[] receiveBuffer = new byte[1024];
        while (clientWebSocket.State == WebSocketState.Open)
        {
            WebSocketReceiveResult result = await clientWebSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
            if (result.MessageType == WebSocketMessageType.Text)
            {
                string receivedMessage = Encoding.UTF8.GetString(receiveBuffer, 0, result.Count);
                Console.WriteLine($"Received message from server: {receivedMessage}");
            }
        }
    }
}

Conclusion

WebSocket in .NET provides a powerful means to establish real-time communication between clients and servers, enabling efficient data exchange in modern web applications. Whether you're building chat applications, real-time dashboards, or collaborative tools, WebSocket's bidirectional communication capabilities offer a robust solution for delivering responsive and interactive experiences to users. With .NET's support for WebSocket functionality, developers have the tools necessary to implement this technology effectively within their applications.


Similar Articles