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.
WebSocket is a web technology providing bi-directional, full-duplex communication channels over a single TCP socket, standardized by the IETF as RFC 6455.
WebSocket enables persistent, two-way communication between browsers and servers without constant polling.
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.
A WebSocket connection starts as an HTTP upgrade request and then transitions to a persistent binary frame protocol.
The client sends an HTTP GET request with Upgrade: websocket and Connection: Upgrade headers, along with a random Sec-WebSocket-Key.
The server responds with HTTP 101 Switching Protocols, confirming the upgrade. The TCP connection is now a WebSocket channel.
Both sides freely send text or binary frames with minimal 2-byte overhead. The connection stays open until either side closes it.
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;