Skip to content

About

No description or website provided.

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

WebSocket4D

WebSocket4D logo

WebSocket4D is a WebSocket client (RFC 6455) for Delphi on Windows, tested with RAD Studio 13. The repository is laid out for a server as well, but so far it contains only the client: the protocol code in Source/Core has no client or network dependencies, so a server can reuse it later.

License Release Delphi

Each connection has its own reader thread. It parses frames straight from the socket buffer into the reusable slots of a lock-free single-producer/single-consumer queue, so in steady state receiving allocates nothing, and messages arrive in the order the server sent them. Your code takes messages from that queue on its own thread, or the client starts a dispatch thread that passes each message to OnMessage. Before a message is queued, the reader thread runs OnReaderMessage, for work that must not wait behind a slow consumer, such as heartbeats. Sending is safe from any thread.

The client supports per-message compression (RFC 7692) and the whole-connection zlib and zstd streams that Discord's gateway uses. TLS is handled by a TLS factory that you pass to the constructor. The default factory uses Indy's OpenSSL handler, which ships with Delphi; a second factory, in Source\Tls\TaurusTLS, uses TaurusTLS with OpenSSL 3. With either one, the certificate and host name are verified against the Windows root store by default, and after the handshake the client reads and writes OpenSSL directly instead of through Indy's buffers.

Requirements

WebSocket4D runs on Windows, as Win64 or Win32. It is built and tested with RAD Studio 13 (37.0) only. Earlier versions are untested; because the code uses inline variables and constants, 10.3 Rio is the oldest version it can work with at all, and pull requests that make it build and pass the tests on 10.3 to 12 are welcome.

Plain ws:// connections need nothing else. For wss:// you need the DLLs of the TLS backend you use (see TLS), and for compress=zstd-stream you need libzstd.dll (see Compression).

Installation

You can use the library from source, as runtime packages, or through DPM, the Delphi package manager.

From source, add these folders to your project's search path:

Source\Core;Source\Client;Source\Tls;Source\Tls\Indy

Source\Core needs only the RTL. For the optional TaurusTLS backend, also add Source\Tls\TaurusTLS (see TLS).

The packages folder has two runtime packages for Win32 and Win64. There are no design-time packages, because the library has no components.

Package Contains Requires
packages\WebSocket4D.dproj Core, client, TLS abstraction and the Indy backend rtl and Indy, which ship with Delphi
packages\WebSocket4D.TaurusTLS.dproj The TaurusTLS backend WebSocket4D and TaurusTLS_RT (TaurusTLS 1.0.11.53 from GetIt)

Build WebSocket4D first; if you do not use TaurusTLS, it is the only package you need. The packages use {$LIBSUFFIX AUTO}, so the BPL name carries the compiler version, for example WebSocket4D370.bpl for RAD Studio 13.

With DPM, install the package GDK.WebSocket4D:

dpm install GDK.WebSocket4D c:\myprojects\project1.dproj

DPM builds the WebSocket4D package for RAD Studio 11 to 13, Win32 and Win64 (only 13 is tested, see Requirements). Indy is declared as a bundled dependency, so DPM uses the Indy that ships with Delphi. The TaurusTLS backend is not part of the DPM package, because TaurusTLS comes from GetIt; to use it, add Source\Tls\TaurusTLS and TaurusTLS's Source folder to your search path, or build packages\WebSocket4D.TaurusTLS.dproj.

Getting started

Connect, then take messages from the queue on your own thread:

uses
  WebSocket4D.Types,
  WebSocket4D.SpscQueue,   // lets the compiler inline TryPeek and Release
  WebSocket4D.Client;

const Client = TWebSocketClient.Create;
try
  Client.Connect('wss://example.com/socket');

  var Msg: TWsMessage;
  while Client.State <> TWsState.Closed do
  begin
    if Client.WaitPeek(Msg, 250) then
    begin
      Writeln(Msg.AsString);   // Msg.Payload / Msg.Len stay valid until Release
      Client.Release;
    end;
  end;

  // Messages received before the close are still queued
  while Client.TryPeek(Msg) do
  begin
    Writeln(Msg.AsString);
    Client.Release;
  end;
finally
  Client.Free;
end;

WaitPeek waits up to the given number of milliseconds for a message. The message stays valid until you call Release, which hands its slot back to the reader. TryPeek does the same without waiting, and Drain handles every waiting message in one call and releases each one for you.

The connection can close while messages are still in the queue, and they stay readable after the close. That is why the example reads the queue once more after the loop. IsOpen turns False as soon as the close handshake starts; State becomes Closed only after the reader has queued its last message, so the loop above waits for State rather than IsOpen.

If you would rather not poll, let the client start a dispatch thread that calls OnMessage:

Client.DispatchMode := TWsDispatchMode.Thread;
Client.OnMessage :=
  procedure(const Msg: TWsMessage)
  begin
    HandlePayload(Msg.Payload, Msg.Len);
  end;

Assign OnMessage before Connect: in this mode, Connect raises EWebSocketError without it, because messages would otherwise be discarded. The message is released when the handler returns, and an exception in the handler is reported through OnError. SendText, SendBinary and Ping may be called from any thread; a lock keeps their frames apart.

Heartbeats and the reader thread

Protocol logic on top of WebSocket, such as heartbeats, stays in your application. The reader thread runs OnReaderMessage for every message before it is queued, so you can read the few fields you need (a message type, a sequence number, an interval) the moment a message arrives. Send the heartbeats themselves from your own timer thread; that way they never wait behind a slow consumer. Keep OnReaderMessage short, because every message waits for it.

Assign OnMessage and OnReaderMessage before Connect. While the client is connected, assigning either raises EWebSocketError, because the reader and dispatch threads may be running the old handler. This also applies after the server closed the connection, until you call Disconnect.

The DiscordHello sample does exactly this against a live gateway: DiscordHello.Scanner.pas reads the fields without allocating, and DiscordHello.Heartbeat.pas sends the heartbeats. The other sample, EchoBench, is a local test server with functional checks and the benchmark below. CONTRIBUTING.md explains how to build and run both.

TLS

For a wss:// URL, the client asks its TLS factory for a new session on every connect. Two backends come with the library:

Backend Unit DLLs next to the executable
Indy (default) WebSocket4D.Tls.Indy.Factory libeay32.dll, ssleay32.dll (OpenSSL 1.0.2u, for example from IndySockets/OpenSSL-Binaries)
TaurusTLS WebSocket4D.Tls.TaurusTLS.Factory libssl-3-x64.dll, libcrypto-3-x64.dll (Win32: libssl-3.dll, libcrypto-3.dll); OpenSSL 1.1.1 or later

TWebSocketClient.Create uses Indy, so a plain build depends only on what ships with Delphi. To use OpenSSL 3 instead, install TaurusTLS 1.0.11.53 from GetIt, add Source\Tls\TaurusTLS and TaurusTLS's own Source folder to the search path, and pass its factory to the constructor. TaurusTLS is compiled in only when you use that unit:

uses
  WebSocket4D.Tls.Factory,
  WebSocket4D.Tls.TaurusTLS.Factory;

const TlsFactory: IWsTlsFactory = TWsTaurusTlsFactory.Create;
const Client = TWebSocketClient.Create(TlsFactory);

Both backends load OpenSSL from a process-wide folder. If the DLLs are not next to the executable, set that folder once at startup, with IdOpenSSLSetLibPath('...') (unit IdSSLOpenSSLHeaders) for Indy or GetOpenSSLLoader.OpenSSLPath := '...' (unit TaurusTLSLoader) for TaurusTLS. Each backend checks its library on every wss:// connect, before any network I/O. If the DLLs are missing, have an unsupported version or lack a function the backend needs, Connect raises EWebSocketTlsLibraryError, which names the DLLs, the reason and how to set the folder.

Certificate checking works the same on both backends: with TlsOptions.VerifyPeer on, which is the default, the certificate chain is checked against the Windows root store and the certificate must match the host name. Indy itself does neither; the Indy backend adds both.

The two backends differ in the OpenSSL they load. The Indy backend needs OpenSSL 1.0.2, a branch the OpenSSL project no longer supports: it has had no public security fixes since the end of 2019. The TaurusTLS backend uses OpenSSL 3. Neither makes a connection safe by itself; what matters is that you ship a current OpenSSL build from a source you trust and update it when OpenSSL publishes fixes. SECURITY.md has more on this.

To use another TLS library, implement IWsTlsFactory (WebSocket4D.Tls.Factory) and IWsTlsSession (WebSocket4D.Tls.Session). In Attach, a session installs an IOHandler that descends from Indy's TIdSSLIOHandlerSocketBase. The transport turns on its PassThrough, opens the TCP connection, and then starts the TLS handshake by turning PassThrough off, so the handshake deadline can cut it off. After the handshake, the session serves non-blocking Read/Write calls on the raw SSL handle.

Compression

WebSocket4D supports two kinds of compression: per-message compression, which is part of the WebSocket standard, and stream compression, which some servers use instead.

Per-message compression (permessage-deflate, RFC 7692) is negotiated in the handshake. Set UsePerMessageDeflate to offer it. If the server accepts, the client inflates the compressed messages it receives and compresses the messages it sends, except those smaller than DeflateMinSize (128 bytes by default).

Stream compression treats the whole connection as one zlib or zstd stream; this is the scheme Discord's gateway uses. The client turns it on when the URL contains compress=zlib-stream or compress=zstd-stream, or when you set TransportCompression to ZlibStream or ZstdStream. If you set the property and the URL asks for the other one, Connect raises.

zlib comes with Delphi, but zstd does not, so compress=zstd-stream loads libzstd.dll (zstd 1.4.0 or later) at runtime; connections without zstd never need it. Use the official build from the facebook/zstd releases (zstd-v<version>-win64.zip or -win32.zip, file dll\libzstd.dll) and match the bitness of your executable. The zips are not signed and the release publishes no checksum for them, so pin the SHA-256 you verified (for v1.5.7, the package manifests of Scoop list the same hashes as the download).

Put the DLL next to the executable, or set its folder once at startup:

uses
  WebSocket4D.Zstd.Loader;

TWsZstdLoader.LibraryFolder := 'C:\MyApp\lib';

Like the TLS backends, the zstd decoder is checked before any network I/O: Connect loads the DLL once per process, binds every function the decoder calls and checks the version. If anything is missing, it raises EWebSocketCompressionLibraryError, which names the DLL, the reason and how to set the folder.

A zstd frame header declares the window the decoder must keep, and libzstd allocates it before it decodes a byte. Left at zstd's own limit, a server could make the client reserve 128 MB per connection. MaxZstdWindowLog caps the window at 2^MaxZstdWindowLog bytes: 23 (8 MB) by default, the size RFC 8878 recommends decoders support. A frame that asks for more closes the connection with 1009, like a message above MaxMessageSize. Discord's gateway declares a 64 KB window, well within the default.

Configuration

Set these properties before you call Connect:

Property Default Meaning
DispatchMode Poll Thread starts a dispatch thread that calls OnMessage
Headers empty Extra request headers, one per line as Name: value or Name=value (what Headers.Values['Name'] := 'value' writes). The name must be a valid HTTP field name and the value may not contain control characters other than a tab. Headers the client sends itself (Host, Upgrade, Connection and the Sec-WebSocket-* headers) cannot be added; use Protocols for the subprotocol
Protocols empty Subprotocols to offer, comma-separated in order of preference, for example v2.chat, chat. Each name must be a non-empty HTTP token and appear once; spaces or tabs around the commas are allowed. Protocol holds the one the server selected
QueueCapacity 4096 Slots in the queue, rounded up to a power of two
ReceiveBufferSize 256 KB Bytes per socket read
MaxMessageSize 64 MB Larger messages close the connection with 1009
ValidateUtf8 True Strict UTF-8 check of text messages, with an ASCII fast path
UsePerMessageDeflate False Offer permessage-deflate
DeflateMinSize 128 bytes Smaller messages are sent uncompressed
TransportCompression None Stream compression: ZlibStream, ZstdStream, or None to take it from the URL
MaxZstdWindowLog 23 (8 MB) zstd-stream only: largest window a frame may declare, as a power of two from 10 to 31 (30 on Win32). A larger window closes the connection with 1009
TlsOptions.VerifyPeer True Verify the certificate and host name
ConnectTimeout 10 s Limit for the TCP connect and for each read during the TLS handshake
HandshakeTimeout 15 s Limit for the whole opening handshake: TCP connect, TLS handshake and the server's upgrade response together. A server that sends its answer slowly cannot stretch it. The host name lookup is not cut off: a slow DNS server can make Connect take longer, up to the operating system's resolver timeout
CloseTimeout 3 s How long Close waits for the server's Close frame

QueueCapacity decides how much memory the client holds on to. When the queue is full, the reader waits for a free slot, which slows the server down through TCP flow control; no message is dropped. Each slot keeps its buffer, up to 4 MB, for the next message, so memory use is roughly QueueCapacity times your typical message size. For messages of a megabyte or more, use 256 slots or fewer.

The client reports through these events: OnOpen, OnMessage, OnReaderMessage, OnPong, OnClose(Code, Reason, WasClean) and OnError. OnReaderMessage and OnPong run on the reader thread and OnMessage on the dispatch thread. OnClose runs on the reader thread in poll mode, and on the dispatch thread after the last message in dispatch mode. Do not free the client from inside an event.

Errors

The library's own exceptions descend from EWebSocketError (unit WebSocket4D.Exceptions). Only some of the ones Connect can raise are worth a retry, so a reconnect loop should look at the class:

Class When Retry?
EWebSocketTransportError DNS failure, refused or timed-out connection, failed TLS handshake (including a rejected certificate), socket errors. Indy's original exception is in InnerException Yes
EWebSocketHandshakeError The handshake did not complete within HandshakeTimeout, the connection closed during it, or the server did not accept the upgrade (a status other than 101, or an invalid upgrade response) Depends on the status
EWebSocketTlsLibraryError The TLS backend's DLLs are missing, too old or incomplete No
EWebSocketCompressionLibraryError libzstd.dll is missing, too old or incomplete No
EWebSocketError No URL or an invalid URL, a size option or HandshakeTimeout that is not greater than zero, a MaxZstdWindowLog outside the range zstd supports, TransportCompression disagreeing with the URL, a header line without a valid name, with a control character in the value, or with a header the client sends itself, a Protocols list with an empty, invalid or repeated name, a TLS session whose Attach installs no TIdSSLIOHandlerSocketBase, DispatchMode Thread without OnMessage, Connect called while already connected, or OnMessage or OnReaderMessage assigned while connected No

The two library errors descend from EWebSocketLibraryError rather than from EWebSocketTransportError on purpose: retrying cannot bring back a missing DLL. Once the connection is open, errors reach you through OnError and OnClose instead of exceptions.

How it works

docs/ARCHITECTURE.md shows the main types in a diagram and follows a connection through connecting, receiving and sending.

Conformance

The client is tested against Autobahn|Testsuite, the standard WebSocket conformance suite. As of version 1.0.0 (Win64 Release), the client runs all 517 cases, including performance (9.x) and permessage-deflate (12.x, 13.x), and none fail: 507 are OK, 3 informational and 7 non-strict. Invalid UTF-8 fails the connection on the fragment that contains it (6.4.x).

Non-strict means the client failed the connection correctly, but not as early as it could have. In 3.2, 3.3, 4.1.3, 4.1.4, 4.2.3, 4.2.4 and 5.15, the server sends a valid message and an invalid frame in one chunk. The reader fails the connection on the invalid frame before your code has echoed the valid message, so that echo never goes out.

CONTRIBUTING.md explains how to run the suite.

Benchmarks

Take these numbers with a grain of salt: they are nice to look at, but no rights can be derived from them.

They come from one machine (AMD Ryzen 7 7800X3D, 8 cores, 16 threads, 32 GB DDR5-4800, Windows 11 Pro), one Win64 Release build, best of three runs, over loopback. The local test server sends pre-built frames, so what is measured is the client's receive path: parsing, unmasking, validation, inflating and handing messages through the queue. There is no real network, no TLS and no work in the message handler.

Your own numbers will differ, and not only because of hardware. A different compiler version, other units or libraries linked into the executable, or a change elsewhere in the code moves where hot loops end up in memory, and code alignment alone can shift a tight loop by a noticeable margin. The OS scheduler matters too: runs with 100-byte messages occasionally drop to 2-6M msg/s when the consumer thread is descheduled and the queue fills. If throughput matters to you, measure inside your own application.

Messages Poll Dispatch thread
5,000,000 x 16 B binary 15.7M msg/s 17.5M msg/s
5,000,000 x 100 B binary 15.0M msg/s (1.43 GB/s) 15.0M msg/s (1.43 GB/s)
5,000,000 x 100 B text, UTF-8 validated 11.5M msg/s 12.3M msg/s
50,000 x 64 KB binary 5.5 GB/s 5.5 GB/s
10,000 x 1 MB binary (queue of 256) 4.7 GB/s 4.3 GB/s
200,000 x 1000 B permessage-deflate 407k msg/s (388 MB/s inflated)

Every run also checks that all messages arrive, in order. To run the benchmark yourself, start the EchoBench sample.

Not done yet

  • No server yet. When one is added, the reader needs a role setting: it rejects masked frames as a client must (RFC 6455 5.1), and a server must do the opposite. The TLS session interface also needs a server-side counterpart to Attach.
  • Windows only: socket I/O uses Winsock directly. POSIX needs a small transport port.
  • No HTTP or HTTPS proxy support: the client always connects to the server directly, so it cannot tunnel through a proxy with CONNECT.
  • Redirects are not followed: a 3xx response to the handshake fails Connect.
  • TLS has one option, VerifyPeer. Client certificates, a custom CA bundle and certificate pinning are not supported.
  • No automatic reconnect; reconnect and session-resume logic belongs in the application.

Contributing

Pull requests are welcome; CONTRIBUTING.md explains how to build, test and submit them. Report security issues privately as described in SECURITY.md, not in a public issue.

Licence

WebSocket4D is released under the MIT License. The Autobahn|Testsuite submodule in Tests/Autobahn/autobahn-testsuite is a separate project under its own licence (Apache 2.0); it is used only to test the client and is not part of the library.

About

No description or website provided.

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages