2.14WebSocket Duplex Communication

Created on Aug 17, 2026~6 min read

WebSocket is a protocol that provides full-duplex communication over a single TCP connection. WebSocket simplifies data exchange between the client and the server, allowing the server to actively push data to the client. In the WebSocket API, the browser and the server only need to complete a single handshake, after which a persistent connection is created directly between them for bidirectional data transfer.

Use cases for WebSocket:

  • Real-time chat applications: WebSocket enables real-time message delivery, making communication between users nearly latency-free.
  • Online games: For games that require fast responses, WebSocket provides low-latency data transfer.
  • Stock market updates: Update stock prices and other financial information in real time.
  • Collaborative editing tools: Allow multiple users to edit the same document simultaneously and see each other's changes in real time.
  • Real-time map applications: For example, real-time traffic condition updates in navigation applications.

The following example shows how to use WebSocketClient to connect to a server:

cs
using var webSocketClient = new WebSocketClient("wss://ws.postman-echo.com/raw");    // Supports ws:// and wss://// Connection established eventwebSocketClient.Connected += (sender, s) =>{    Console.WriteLine("Connected");    return Task.CompletedTask;};// Connection closed eventwebSocketClient.Closed += (sender, args) =>{    Console.WriteLine("Connection closed");    return Task.CompletedTask;};// Text message receivedwebSocketClient.TextReceived += (sender, s) =>{    Console.WriteLine(s.Message);    return Task.CompletedTask;};// Binary message receivedwebSocketClient.BinaryReceived += (sender, s) =>{    Console.WriteLine(s.Message);    return Task.CompletedTask;};// Connect to the serverawait webSocketClient.ConnectAsync();// Start a task that sends messages in a loop_ = Task.Run(async () =>{    var i = 0;    while (i < 5)    {        // Send a text message        await webSocketClient.SendAsync("Hello, WebSocket!");        await Task.Delay(1000);        i++;    }    // Close the connection    await webSocketClient.CloseAsync();});// Wait for message reception and close events (blocking)await webSocketClient.WaitAsync();

Differences between WebSocket and Server-Sent Events (SSE):

  • Communication direction: WebSocket supports full-duplex bidirectional communication, while SSE only supports unidirectional data push from the server to the client.
  • Protocol: WebSocket uses the independent WebSocket protocol (ws:// or wss://), while SSE is based on the HTTP protocol.
  • Handshake process: WebSocket requires a special HTTP upgrade header to switch protocols, while SSE requires no special handshake and establishes the connection directly through an HTTP request.
  • Connection persistence: A WebSocket connection remains open until explicitly closed, while an SSE connection may drop due to network issues, but the browser automatically reconnects.
  • Data format: WebSocket supports multiple data formats, including binary data, while SSE has a relatively fixed data format, typically simple text messages.
  • Cross-origin support: WebSocket checks the cross-origin policy when establishing a connection but is unrestricted afterward, while SSE relies on the CORS policy.

Choosing between WebSocket and SSE mainly depends on the specific application requirements:

  • If bidirectional communication or handling large volumes of data streams is required, WebSocket is the better choice;
  • If only server-to-client push updates are needed and the data format requirements are not high, SSE may be lighter-weight and easier to implement.