Sobes.tech
Junior — Middle

Can you explain what web sockets are and how they work to establish a two-way connection between client and server?

sobes.tech AI

Answer from AI

WebSockets are a protocol that provides full-duplex communication between a client and a server over a single TCP connection.

How it works:

  1. The client initiates an HTTP request with the header Upgrade: websocket to switch to the WebSocket protocol.
  2. The server confirms the switch by responding with the appropriate header.
  3. After a successful handshake, a persistent connection is established, allowing both parties to send data at any time.

This differs from traditional HTTP, where the client sends a request and the server responds, and the connection is closed. WebSockets allow the server to send data to the client without a request, which is useful for chats, games, real-time updates, etc.

Example in C# using System.Net.WebSockets:

using System.Net.WebSockets;
using System.Threading;
using System.Text;

// Example of sending and receiving messages via WebSocket
ClientWebSocket ws = new ClientWebSocket();
await ws.ConnectAsync(new Uri("wss://example.com/socket"), CancellationToken.None);

// Sending a message
string message = "Hello";
byte[] bytes = Encoding.UTF8.GetBytes(message);
await ws.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Text, true, CancellationToken.None);

// Receiving a message
var buffer = new byte[1024];
var result = await ws.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
string received = Encoding.UTF8.GetString(buffer, 0, result.Count);