Junior — Middle
Can you explain what the WebSocket protocol is and how it is used for real-time data exchange?
sobes.tech AI
Answer from AI
WebSocket is a communication protocol that provides a full-duplex channel between the client and server over a single TCP connection.
Unlike traditional HTTP, where the client sends a request and waits for a response, WebSocket allows the server and client to exchange messages at any time without needing to re-establish the connection.
This is especially useful for real-time data exchange applications, such as:
- Chat applications
- Online games
- Financial trading platforms
Example of usage in C# with the System.Net.WebSockets library:
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
ClientWebSocket ws = new ClientWebSocket();
await ws.ConnectAsync(new Uri("wss://example.com/socket"), CancellationToken.None);
string message = "Hello, WebSocket!";
var bytes = Encoding.UTF8.GetBytes(message);
await ws.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Text, true, CancellationToken.None);
var buffer = new byte[1024];
var result = await ws.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
Console.WriteLine("Received: " + Encoding.UTF8.GetString(buffer, 0, result.Count));
await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
}
}
Thus, WebSocket enables the creation of interactive applications with minimal data exchange latency.