logo.png
mORMot2 API Reference

mormot.net.ws.server.pas unit

Purpose: WebSockets Server-Side Process
- this unit is a part of the Open Source Synopse mORMot framework 2, licensed under a MPL/GPL/LGPL three license - see LICENSE.md

1.1. Units used in the mormot.net.ws.server unit

Unit NameDescription
mormot.core.baseFramework Core Shared Types and RTL-like Functions
mormot.core.buffersFramework Core Low-Level Memory Buffer Process
mormot.core.dataFramework Core Low-Level Data Processing Functions
mormot.core.jsonFramework Core Low-Level JSON Processing
mormot.core.logFramework Core Logging
mormot.core.osFramework Core Low-Level Wrappers to the Operating-System API
mormot.core.rttiFramework Core Low-Level Cross-Compiler RTTI Definitions
mormot.core.textFramework Core Low-Level Text Processing
mormot.core.threadsFramework Core Multi-Threading Support
mormot.core.unicodeFramework Core Low-Level Unicode UTF-8 UTF-16 Ansi Conversion
mormot.crypt.coreFramework Core Cryptographic Process (Hashing and Cypher)
mormot.crypt.eccFramework Core High-Level Public-Key Elliptic-Curve Cryptography
mormot.crypt.secureFramework Core Authentication and Security Features
mormot.net.clientHTTP/HTTPS Client Classes
mormot.net.httpHTTP/HTTPS Abstract Process Classes and Definitions
mormot.net.serverHTTP/HTTPS Server Classes
mormot.net.sockLow-level access to the OperatingSystem Sockets API (e.g. WinSock2)
mormot.net.ws.coreWebSockets Shared Process Classes and Definitions

1.2. mormot.net.ws.server class hierarchy

TWebCrtSocketProcessTWebSocketProcessServerTHttpServerSocketTWebSocketServerSocketTWebSocketServerTWebSocketServerRestTHttpServer
mormot.net.ws.server class hierarchy

1.3. Objects implemented in the mormot.net.ws.server unit

ObjectsDescription
TWebSocketProcessServerImplements WebSockets process as used on server side
TWebSocketServerMain HTTP/WebSockets server Thread using the standard Sockets API (e.g. WinSock)
TWebSocketServerRestMain HTTP/WebSockets server Thread using the standard Sockets API (e.g. WinSock)
TWebSocketServerSocketSocket maintained for each connection to the HTTP/WebSockets server

1.3.1. TWebSocketProcessServer

TWebSocketProcessServer = class(TWebCrtSocketProcess)

Implements WebSockets process as used on server side


1.3.2. TWebSocketServerSocket

TWebSocketServerSocket = class(THttpServerSocket)

Socket maintained for each connection to the HTTP/WebSockets server
- this class contains additional parameters used to maintain the WebSockets execution context in overriden TWebSocketServer.Process method


destructor Destroy; override;

Finalize this socket and its associated TWebSocketProcessServer


function NotifyCallback(Ctxt: THttpServerRequest; aMode: TWebSocketProcessNotifyCallback): cardinal; virtual;

Push a notification to the client


function WebSocketProtocol: TWebSocketProtocol;

The Sec-WebSocket-Protocol application protocol currently involved
- TWebSocketProtocolJson or TWebSocketProtocolBinary in the mORMot context
- could be nil if the connection is in standard HTTP/1.1 mode


procedure Close; override;

Set once upgraded ensure focConnectionClose is done before closing the connection


property WebSocketProcess: TWebSocketProcessServer read fProcess;

Low-level WebSocket protocol processing instance


1.3.3. TWebSocketServer

TWebSocketServer = class(THttpServer)

Main HTTP/WebSockets server Thread using the standard Sockets API (e.g. WinSock)
- once upgraded to WebSockets from the client, this class is able to serve any Sec-WebSocket-Protocol application content


constructor Create(const aPort: RawUtf8; const OnStart, OnStop: TOnNotifyThread; const ProcessName: RawUtf8; ServerThreadPoolCount: integer = 2; KeepAliveTimeOut: integer = 30000; ProcessOptions: THttpServerOptions = []); override;

Create a Server Thread, binded and listening on a port
- this constructor will raise a EHttpServer exception if binding failed
- expects the port to be specified as string, e.g. '1234'; you can optionally specify a server address to bind to, e.g. '1.2.3.4:1234'
- due to the way how WebSockets works, one thread will be created for any incoming connection
- note that this constructor will not register any protocol, so is useless until you execute Protocols.Add()
- in the current implementation, the ServerThreadPoolCount parameter will use two threads by default to handle shortliving HTTP/1.0 "connection: close" requests, and one thread will be maintained per keep-alive/websockets client
- by design, the KeepAliveTimeOut value is ignored with this server once it has been upgraded to WebSockets


destructor Destroy; override;

Close the server


function IsActiveWebSocket( ConnectionID: THttpServerConnectionID): TWebSocketProcessServer;

Give access to the underlying WebSockets connection from its ID


function Settings: PWebSocketProcessSettings;

Allow to customize the WebSockets processing
- apply to all protocols on this server instance
- those parameters are accessed by reference from existing connections, so you should better not modify them once the server started


function WebSocketConnections: integer;

How many WebSockets connections are currently maintained


procedure WebSocketBroadcast(const aFrame: TWebSocketFrame); overload;

Will send a given frame to all connected clients
- expect aFrame.opcode to be either focText or focBinary
- will call TWebSocketProcess.Outgoing.Push for asynchronous sending


procedure WebSocketBroadcast(const aFrame: TWebSocketFrame; const aClientsConnectionID: THttpServerConnectionIDDynArray); overload;

Will send a given frame to clients matching the supplied connection IDs
- expect aFrame.opcode to be either focText or focBinary
- WebSocketBroadcast(nil) will broadcast to all running websockets
- will call TWebSocketProcess.Outgoing.Push for asynchronous sending


property OnWebSocketClose: TOnWebSocketProtocolClosed read fOnWSClose write fOnWSClose;

Same as OnWebSocketDisconnect, but using TWebSocketProtocol as parameter


property OnWebSocketConnect: TOnWebSocketServerEvent read fOnWSConnect write fOnWSConnect;

Event triggerred when a new connection upgrade has been done
- just before the main processing WebSockets frames processing loop


property OnWebSocketDisconnect: TOnWebSocketServerEvent read fOnWSDisconnect write fOnWSDisconnect;

Event triggerred when a connection is about to be closed
- when the main processing WebSockets frames processing loop finishes


property OnWebSocketUpgraded: TOnWebSocketProtocolUpgraded read fOnWSUpgraded write fOnWSUpgraded;

Event triggerred when a new connection upgrade has been upgraded
- allow e.g. to verify a JWT bearer before returning the WS 101 response


property ProcessClass: TWebSocketProcessServerClass read fProcessClass write fProcessClass;

Allow to customize the WebSockets processing classes


property WebSocketProtocols: TWebSocketProtocolList read fProtocols;

Access to the protocol list handled by this server


1.3.4. TWebSocketServerRest

TWebSocketServerRest = class(TWebSocketServer)

Main HTTP/WebSockets server Thread using the standard Sockets API (e.g. WinSock)
- once upgraded to WebSockets from the client, this class is able to serve our proprietary Sec-WebSocket-Protocol: 'synopsejson' or 'synopsebin' application content, managing regular REST client-side requests and also server-side push notifications
- once in 'synopse*' mode, the Request() method will be trigerred from any incoming WebSocket frame from the client, and the OnCallback event will be available to push a WebSocket frame from the server to the client


constructor Create(const aPort: RawUtf8; const OnStart, OnStop: TOnNotifyThread; const aProcessName, aWebSocketsURI, aWebSocketsEncryptionKey: RawUtf8; aWebSocketsAjax: boolean = false); reintroduce; overload;

Create a Server Thread, binded and listening on a port, with our 'synopsebin' and optionally 'synopsejson' modes
- if aWebSocketsURI is '', any URI would potentially upgrade; you can specify an URI to limit the protocol upgrade to a single resource
- TWebSocketProtocolBinary will always be registered by this constructor
- aWebSocketsEncryptionKey format follows TWebSocketProtocol.SetEncryptKey, so could be e.g. 'password#xxxxxx.private' or 'a=mutual;e=aesctc128;p=34a2..' to use TEcdheProtocol, or a plain password for TProtocolAes
- if aWebSocketsAjax is TRUE, it will also register TWebSocketProtocolJson so that AJAX applications would be able to connect to this server
- warning: WaitStarted should be called after Create() to check for for actual port binding in the background thread


function Callback(Ctxt: THttpServerRequest; aNonBlocking: boolean): cardinal; override;

Server can send a request back to the client, when the connection has been upgraded to WebSocket
- InURL/InMethod/InContent properties are input parameters (InContentType is ignored)
- OutContent/OutContentType/OutCustomHeader are output parameters
- CallingThread should be set to the client's Ctxt.CallingThread value, so that the method could know which connnection is to be used - it will return HTTP_NOTFOUND (404) if the connection is unknown
- result of the function is the HTTP error code (200 if OK, e.g.)


function WebSocketsEnable(const aWebSocketsURI, aWebSocketsEncryptionKey: RawUtf8; aWebSocketsAjax: boolean = false; aWebSocketsBinaryOptions: TWebSocketProtocolBinaryOptions = [pboSynLzCompress]): pointer; override;

Defines the WebSockets protocols to be used for this Server
- i.e. 'synopsebin' and optionally 'synopsejson' modes
- if aWebSocketsURI is '', any URI would potentially upgrade; you can specify an URI to limit the protocol upgrade to a single resource
- TWebSocketProtocolBinary will always be registered by this constructor
- aWebSocketsEncryptionKey format follows TWebSocketProtocol.SetEncryptKey
- if aWebSocketsAjax is TRUE, it will also register TWebSocketProtocolJson so that AJAX applications would be able to connect to this server


1.4. Types implemented in the mormot.net.ws.server unit

1.4.1. TOnWebSocketServerEvent

TOnWebSocketServerEvent = procedure(Sender: TWebSocketServerSocket) of object;

Callback signature to notify TWebSocketServer connections


1.4.2. TWebSocketProcessServerClass

TWebSocketProcessServerClass = class of TWebSocketProcessServer;

Meta-class of WebSockets process as used on server side