WebSocket Implementation in C#

WebSocket is a protocol that allows for real-time, full-duplex communication over a single, long-lived connection. It is widely used in web development to enable real-time communication between clients and servers. In this article, we will explore how to implement WebSocket communication in C#.

To get started with WebSocket in C, we need to use the System.Net.WebSockets namespace, which provides classes and methods for working with the WebSocket protocol. The ClientWebSocket class is used to create a WebSocket client, while the HttpListenerWebSocketContext class is used to represent a WebSocket connection on the server side.

Here’s an example of how to create a WebSocket client in C:

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

public class WebSocketClient
{
    public static async Task Connect(string url)
    {
        using (ClientWebSocket client = new ClientWebSocket())
        {
            await client.ConnectAsync(new Uri(url), CancellationToken.None);

            // Perform WebSocket communication here

            await client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
        }
    }
}

In the above code, we create a ClientWebSocket instance and connect to the specified URL using the ConnectAsync method. We can then perform WebSocket communication operations within the using block. Finally, we close the WebSocket connection using the CloseAsync method.

Now let’s take a look at how to implement a WebSocket server in C. Here’s an example:

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

public class WebSocketServer
{
    private HttpListener listener;

    public async Task Start(string url)
    {
        listener = new HttpListener();
        listener.Prefixes.Add(url);
        listener.Start();

        while (true)
        {
            HttpListenerContext context = await listener.GetContextAsync();
            if (context.Request.IsWebSocketRequest)
            {
                HttpListenerWebSocketContext webSocketContext = await context.AcceptWebSocketAsync(null);
                // Handle WebSocket communication here
                await HandleWebSocketCommunication(webSocketContext.WebSocket);
            }
            else
            {
                context.Response.StatusCode = 400; // Bad Request
                context.Response.Close();
            }
        }
    }

    private async Task HandleWebSocketCommunication(WebSocket webSocket)
    {
        byte[] buffer = new byte[1024];
        WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);

        while (!result.CloseStatus.HasValue)
        {
            // Handle received WebSocket data
            await HandleReceivedData(buffer, result.Count);

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

        await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
    }
}

In the code above, we create an HTTP listener and start listening for WebSocket requests on the specified URL. When a request is received, we check if it is a WebSocket request using the IsWebSocketRequest property of the HttpListenerRequest object. If it is, we accept the WebSocket connection using the AcceptWebSocketAsync method and handle the WebSocket communication within the HandleWebSocketCommunication method.

With these examples, you should now have a basic understanding of how to implement WebSocket communication in C. Remember to handle exceptions and error handling to ensure reliable WebSocket communication.