6.36WebSocket Duplex Communication

Created on Aug 17, 2026~6 min read

WebSocket is a protocol that performs full-duplex communication over a single TCP connection. WebSocket makes data exchange between the client and the server simpler, 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 they can directly create a persistent connection and carry out bidirectional data transmission.

The application scenarios of 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 can provide low-latency data transmission.
  • 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://// Connected eventwebSocketClient.Connected += (sender, s) =>{    Console.WriteLine("Connected");    return Task.CompletedTask;};// Connection closed eventwebSocketClient.Closed += (sender, args) =>{    Console.WriteLine("Connection closed");    return Task.CompletedTask;};// Receive text messageswebSocketClient.TextReceived += (sender, s) =>{    Console.WriteLine(s.Message);    return Task.CompletedTask;};// Receive binary messageswebSocketClient.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 receive-message and close events (blocking)await webSocketClient.WaitAsync();

The difference between WebSocket and Server-Sent Events (SSE):

  • Communication direction: WebSocket supports full-duplex bidirectional communication, while SSE only supports the server pushing data to the client unidirectionally.
  • Protocol: WebSocket uses the standalone 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 persists until it is explicitly closed, while SSE may be disconnected due to network issues, but the browser will automatically reconnect.
  • Data format: WebSocket supports multiple data formats, including binary data, while the SSE data format is relatively fixed and is usually simple text messages.
  • Cross-origin support: WebSocket checks the cross-origin policy when establishing the connection and is unrestricted afterward, while SSE depends on the CORS policy.

Whether to use WebSocket or SSE mainly depends on the specific application requirements:

  • If bidirectional communication or handling large data streams is required, WebSocket is the better choice;
  • If you only need the server to push updates to the client and have low requirements for the data format, SSE may be lighter-weight and easier to implement.