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:
WebSocketenables real-time message delivery, making communication between users nearly latency-free. - Online games: For games that require fast responses,
WebSocketcan 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:
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:
WebSocketsupports full-duplex bidirectional communication, whileSSEonly supports the server pushing data to the client unidirectionally. - Protocol:
WebSocketuses the standaloneWebSocketprotocol (ws://orwss://), whileSSEis based on theHTTPprotocol. - Handshake process:
WebSocketrequires a specialHTTPupgrade header to switch protocols, whileSSErequires no special handshake and establishes the connection directly through anHTTPrequest. - Connection persistence: A
WebSocketconnection persists until it is explicitly closed, whileSSEmay be disconnected due to network issues, but the browser will automatically reconnect. - Data format:
WebSocketsupports multiple data formats, including binary data, while theSSEdata format is relatively fixed and is usually simple text messages. - Cross-origin support:
WebSocketchecks the cross-origin policy when establishing the connection and is unrestricted afterward, whileSSEdepends on theCORSpolicy.
Whether to use WebSocket or SSE mainly depends on the specific application requirements:
- If bidirectional communication or handling large data streams is required,
WebSocketis the better choice; - If you only need the server to push updates to the client and have low requirements for the data format,
SSEmay be lighter-weight and easier to implement.