What are WebSockets?

WebSocket is a web technology providing bi-directional, full-duplex communication channels over a single TCP socket, standardized by the IETF as RFC 6455.

Real-Time Communication

WebSocket enables persistent, two-way communication between browsers and servers without constant polling.

Beyond HTTP Request-Response

Traditional HTTP follows a request-response pattern where the client must initiate every exchange. WebSocket upgrades an HTTP connection into a persistent, full-duplex channel where both client and server can send data at any time. This eliminates the overhead of repeated HTTP handshakes and enables true real-time interactions such as live feeds, online gaming, collaborative editing, and financial tickers.

  • Bi-directional: both client and server can push data
  • Persistent connection reduces latency and overhead
  • Operates over standard TCP port 80/443, traversing firewalls
  • Standardized as RFC 6455 by the IETF
CLIENT SERVER Full-Duplex ws:// or wss:// RFC 6455

The WebSocket Handshake

A WebSocket connection starts as an HTTP upgrade request and then transitions to a persistent binary frame protocol.

1. HTTP Upgrade Request

The client sends an HTTP GET request with Upgrade: websocket and Connection: Upgrade headers, along with a random Sec-WebSocket-Key.

2. Server Accepts

The server responds with HTTP 101 Switching Protocols, confirming the upgrade. The TCP connection is now a WebSocket channel.

3. Full-Duplex Messaging

Both sides freely send text or binary frames with minimal 2-byte overhead. The connection stays open until either side closes it.

Delphi WebSocket Example

Connect to a WebSocket server and exchange messages in a few lines of code.

uses
  sgcWebSocket_Client, sgcWebSocket_Types;

var
  WSClient: TsgcWebSocketClient;

procedure TForm1.FormCreate(Sender: TObject);
begin
  WSClient := TsgcWebSocketClient.Create(nil);
  WSClient.Host := 'echo.websocket.org';
  WSClient.Port := 443;
  WSClient.TLS := True;
  WSClient.OnMessage := OnMessage;
  WSClient.Active := True;
end;

procedure TForm1.OnMessage(Connection: TsgcWSConnection;
  const aText: string);
begin
  // Handle incoming messages
  Memo1.Lines.Add('Received: ' + aText);
end;

procedure TForm1.ButtonSendClick(Sender: TObject);
begin
  // Send a text message to the server
  WSClient.WriteData('Hello, WebSocket!');
end;

Ready to Build Real-Time Applications?

Download sgcWebSockets and add WebSocket support to your Delphi, C++ Builder, or .NET projects today.