WebSocket API (Windows.Networking.Sockets)

The Windows Runtime (WinRT) provides a robust set of APIs for implementing WebSocket client and server functionality within Universal Windows Platform (UWP) applications.

Introduction to WebSockets

WebSockets offer a full-duplex communication channel over a single TCP connection. This allows for real-time, bi-directional data transfer between a client and a server, making them ideal for applications requiring instant updates, such as chat applications, live dashboards, and online gaming.

Key Classes

The primary classes for WebSocket communication in UWP are:

Using MessageWebSocket

Here's a simplified example of how to establish a WebSocket connection and send a message using MessageWebSocket:

C# Example (Client)


using Windows.Networking.Sockets;
using Windows.Storage.Streams;
using System;
using System.Threading.Tasks;

public class WebSocketClient
{
    private MessageWebSocket webSocket;

    public async Task ConnectAsync(string uri)
    {
        webSocket = new MessageWebSocket();
        webSocket.Closed += WebSocket_Closed;
        webSocket.MessageReceived += WebSocket_MessageReceived;

        try
        {
            await webSocket.ConnectAsync(new Uri(uri));
            Console.WriteLine("WebSocket connected successfully.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"WebSocket connection failed: {ex.Message}");
        }
    }

    public async Task SendMessageAsync(string message)
    {
        if (webSocket != null && webSocket.ConnectionStatus == WebSocketConnectionStatus.Open)
        {
            using (var dataWriter = new DataWriter(webSocket.OutputStream))
            {
                dataWriter.WriteString(message);
                await dataWriter.StoreAsync();
                Console.WriteLine($"Message sent: {message}");
            }
        }
        else
        {
            Console.WriteLine("WebSocket is not connected.");
        }
    }

    private void WebSocket_Closed(MessageWebSocket sender, WebSocketClosedEventArgs args)
    {
        Console.WriteLine($"WebSocket closed: Code={args.Code}, Reason={args.Reason}");
    }

    private void WebSocket_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
    {
        using (var reader = args.DataReader)
        {
            string message = reader.ReadString(reader.UnconsumedBufferLength);
            Console.WriteLine($"Message received: {message}");
        }
    }

    public void Close()
    {
        if (webSocket != null)
        {
            webSocket.Close(1000, "Normal closure");
            webSocket = null;
        }
    }
}
                

Server-Side WebSockets

While UWP applications are primarily designed as clients, it's possible to create WebSocket servers using network listener APIs and handling the WebSocket handshake manually. However, for robust server implementations, it's recommended to use dedicated server technologies like ASP.NET Core or Node.js.

Error Handling and Connection Management

Properly handling WebSocket connection events is crucial for a reliable application. Implement event handlers for Closed, MessageReceived, and potential exceptions during connection or data transfer.

Security Considerations

Always use secure WebSocket connections (WSS) by default when communicating over the internet. This is achieved by using wss:// in the URI instead of ws://.