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:
WebSocketenables real-time message delivery, making communication between users nearly latency-free. - Online games: For games that require fast responses,
WebSocketprovides 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:
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:
WebSocketsupports full-duplex bidirectional communication, whileSSEonly supports unidirectional data push from the server to the client. - Protocol:
WebSocketuses the independentWebSocketprotocol (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 remains open until explicitly closed, while anSSEconnection may drop due to network issues, but the browser automatically reconnects. - Data format:
WebSocketsupports multiple data formats, including binary data, whileSSEhas a relatively fixed data format, typically simple text messages. - Cross-origin support:
WebSocketchecks the cross-origin policy when establishing a connection but is unrestricted afterward, whileSSErelies on theCORSpolicy.
Choosing between WebSocket and SSE mainly depends on the specific application requirements:
- If bidirectional communication or handling large volumes of data streams is required,
WebSocketis the better choice; - If only server-to-client push updates are needed and the data format requirements are not high,
SSEmay be lighter-weight and easier to implement.