TsgcWebSocketServer implements Server WebSocket Component and can handle multiple threaded client connections. Follow the steps below to configure this component:
1. Drop a TsgcWebSocketServer component onto the form
2. Set Port (default is 80). If you are behind a firewall probably you will need to configure it.
3. Set Specifications allowed, by default, all specifications are allowed.
RFC6455: is standard and recommended WebSocket specification.
Hixie76: it's a draft and it's only recommended to establish Hixie76 connections if you want to provide support to old browsers like Safari 4.2
4. The following events are available:
OnConnect: every time a WebSocket connection is established, this event is triggered.
OnDisconnect: every time a WebSocket connection is dropped, this event is triggered.
OnError: whenever a WebSocket error occurs (like mal-formed handshake), this event is triggered.
OnMessage: every time a client sends a text message and it's received by server, this event is triggered.
OnBinary: every time a client sends a binary message and it's received by server, this event is triggered.
OnHandhake: this event is triggered after the handshake is evaluated on the server side.
OnException: whenever an exception occurs, this event is triggered.
OnAuthentication: if authentication is enabled, this event is triggered. You can check user and password passed by the client and enable/disable Authenticated Variable.
OnUnknownProtocol: if WebSocket protocol is not detected (because the client is using plain TCP protocol for example), in this event connection can be accepted or rejected.
OnStartup: raised after the server has started.
OnShutdown: raised after the server has stopped.
OnTCPConnect: public event, is called AFTER the TCP connection and BEFORE Websocket handshake. Is useful when your server accepts plain TCP connections (because OnConnect event is only fired after first message sent by client).
OnBeforeHeartBeat: if HeartBeat is enabled, allows implementing a custom HeartBeat setting Handled parameter to True (this means, standard websocket ping won't be sent).
OnSSLGetHandler: This event is raised before SSL handler is created, you can create here your own SSL Handler (needs to be inherited from TIdServerIOHandlerSSLBase or TIdIOHandlerSSLBase) and set the properties needed.
OnSSLAfterCreateHandler: This event is called after the SSL Handler is created. Can be used to customize some of the properties of the IOHandler.
OnSSLALPNSelect: When the connection is using ALPN this event is raised to set which protocol will be used.
OnSSLVerifyPeer: When the property VerifyCertificate is set to True and the client is using a certificate, this event will be raised with the certificate data and the option to accept or not the connection.
5. Create a procedure and set property Active = True.
Broadcast: sends a message to all connected clients.
Message / Stream: message or stream to send to all clients.
Channel: if you specify a channel, the message will be sent only to subscribers.
Protocol: if defined, the message will be sent only to a specific protocol.
Exclude: if defined, list of connection guid excluded (separated by comma).
Include: if defined, list of connection guid included (separated by comma).
WriteData: sends a message to a single or multiple clients. Every time a Client establishes a WebSocket connection, this connection is identified by a Guid, you can use this Guid to send a message to a client.
Ping: sends a ping to all connected clients. If a time-out is specified, it waits a response until a time-out is exceeded, if no response, then closes the connection.
DisconnectAll: disconnects all active connections.
Start: uses a secondary thread to connect to the server, this prevents your application from freezing while trying to connect.
Stop: uses a secondary thread to disconnect from the server, this prevents your application from freezing while trying to disconnect.
Authentication: if enabled, you can authenticate WebSocket connections against a username and password.
Authusers: is a list of authenticated users, following spec:
user=password
Implements 3 types of WebSocket Authentication
Session: client needs to do an HTTP GET passing username and password, and if authenticated, server response a Session ID. With this Session ID, client open WebSocket connection passing as a parameter.
URL: client open Websocket connection passing username and password as a parameter.
Basic: implements Basic Access Authentication, only applies to VCL Websockets (Server and Client) and HTTP Requests (client web browsers don't implement this type of authentication).
Bindings: used to manage IP and Ports.
Connections: contains a list of all clients connections.
Count: Connections number count.
LogFile: if enabled, saves socket messages to a specified log file, useful for debugging.
Enabled: if enabled every time a message is received and sent by socket it will be saved on a file.
FileName: full path to the filename.
UnMaskFrames: by default True, means that saves the websocket messages received unmasked.
Extensions: you can enable message compression (if client don't support compression, messages will be exchanged automatically without compression).
FallBack: if WebSockets protocol it's not supported natively by the browser, you can enable the following fallbacks:
Flash: if enabled, if the browser hasn't native WebSocket implementation and has flash enabled, it uses Flash as a Transport.
ServerSentEvents: if enabled, allows to send push notifications from the server to browser clients.
Retry: interval in seconds to try to reconnect to server (3 by default).
HeartBeat: if enabled, attempts to keep alive WebSocket client connections by sending a ping every x seconds.
Interval: number of seconds between each ping.
Timeout: max number of seconds between a ping and pong.
HeartBeatType: allows customizing how the HeartBeat works
TCPKeepAlive: if enabled, uses keep-alive at TCP socket level; in Windows, it will enable SIO_KEEPALIVE_VALS if supported, otherwise it will use keepalive. By default is disabled.
Interval: in milliseconds.
Timeout: in milliseconds.
HTTP2Options: by default HTTP/2 protocol is not enabled, it uses HTTP 1.1 to handle HTTP requests. Enable this property if you want to use the HTTP/2 protocol if the client supports it.
Enabled: if true, HTTP/2 protocol is supported. If client doesn't supports HTTP/2, HTTP 1.1 will be used as fallback.
Settings: Specifies the header values to send to the HTTP/2 server.
EnablePush: by default enabled, this setting can be used to avoid server push content to client.
HeaderTableSize: Allows the sender to inform the remote endpoint of the maximum size of the header compression table used to decode header blocks, in octets. The encoder can select any size equal to or less than this value by using signaling specific to the header compression format inside a header block. The initial value is 4,096 octets.
InitialWindowSize: Indicates the sender’s initial window size (in octets) for stream-level flow control. The initial value is 65,535 octets. This setting affects the window size of all streams.
MaxConcurrentStreams: Indicates the maximum number of concurrent streams that the sender will allow. This limit is directional: it applies to the number of streams that the sender permits the receiver to create. Initially, there is no limit to this value.
MaxFrameSize: Indicates the size of the largest frame payload that the sender is willing to receive, in octets. The initial value is 16,384 octets.
MaxHeaderListSize: This advisory setting informs a peer of the maximum size of header list that the sender is prepared to accept, in octets. The value is based on the uncompressed size of header fields, including the length of the name and value in octets plus an overhead of 32 octets for each header field.
IOHandlerOptions: by default uses normal Indy Handler (every connection runs in his own thread)
iohDefault: default indy IOHandler, every new connection creates a new thread.
iohIOCP: only for windows and requires sgcWebSockets Enterprise Edition, a thread pool handles all connections. Read more about IOCP.
iohEPOLL: only for linux and requires sgcWebSockets Enterprise Edition, a thread pool handles all connections. Read more about EPOLL.
LoadBalancer: it's a client which connects to Load Balancer Server to broadcast messages and send information about the server.
AutoRegisterBindings: if enabled, sends automatically server bindings to load balancer server.
AutoRestart: time to wait in seconds after a load balancer server connection has been dropped and tries to reconnect; zero means no restart (by default);
Bindings: here you can set manual bindings to be sent to Load Balancer Server, example:
WS://127.0.0.1:80
WSS://127.0.0.2:8888
Enabled: if enabled, it will connect to Load Balancer Server.
Guid: used to identify server on Load Balancer Server side.
Host: Load Balancer Server Host.
Port: Load Balancer Server Port.
MaxConnections: max connections allowed (if zero there is no limit).
NotifyEvents: defines which mode to notify WebSocket events.
neAsynchronous: this is the default mode, notify threaded events on asynchronous mode, adds events to a queue that are synchronized with the main thread asynchronously.
neSynchronous: if this mode is selected, notify threaded events on synchronous mode, needs to synchronize with the main thread to notify these events.
neNoSync: there is no synchronization with the main thread, if you need to access to controls that are not thread-safe, you need to implement your own synchronization methods.
Options:
FragmentedMessages: allows handling fragmented messages
frgOnlyBuffer: the message is buffered until all data is received, it raises OnBinary or OnMessage event (option by default)
frgOnlyFragmented: every time a new fragment is received, it raises OnFragmented Event.
frgAll: every time a new fragment is received, it raises OnFragmented Event with All data received from the first packet. When all data is received, it raises OnBinary or OnMessage event.
HTMLFiles: if enabled, allows to request Web Browser tests, enabled by default.
JavascriptFiles: if enabled, allows requesting built-in JavaScript libraries, enabled by default.
RaiseDisconnectExceptions: enabled by default; raises an exception every time there's a disconnection due to a protocol error.
ReadTimeOut: time in milliseconds to check if there is data in socket connection, 10 by default.
WriteTimeOut: max time in milliseconds sending data to other peer, 0 by default (only works under Windows OS).
ValidateUTF8: if enabled, validates whether the message contains valid UTF8 characters; by default, it's disabled.
Software: contains the value of the HTTP Server header; the default value is the library name and version.
QueueOptions: this property allows queuing the messages in an internal queue (instead of send directly) and send the messages in the context of the connection thread (QueueOptions only works on Indy based servers where every connection runs in his own thread), this prevents locks when several threads try to send a message using the same connection. For every message type: Text, Binary or Ping a queue can be configured, by default the value set is qmNone which means the messages are not queued. The other types, means different queue levels and the difference between them are just the order where are processed (first are processed qmLevel1, then qmLevel2 and finally qmLevel3).
Example: if Text and Binary messages have the property set to qmLevel2 and Ping to qmLevel1. The server will process first the Ping messages (so the ping message is sent first than Text or Binary if they are queued at the same time), and then process the Text and Binary messages in the same queue. QueueOptions is not supported when IOHandlerOptions = iohIOCP
ReadEmptySource: max number of times an HTTP Connection is read and there is no data received, 0 by default (means no limit). If the limit is reached, the connection is closed.
SecurityOptions:
OriginsAllowed: define here which origins are allowed (by default accepts connections from all origins), if the origin is not in the list closes the connection. Examples:
Allow all connections to IP 127.0.0.1 and port 5555. OriginsAllowed = "http://127.0.0.1:5555"
Allow all connections to IP 127.0.0.1 and all ports. OriginsAllowed = "http://127.0.0.1:*"
Allow all connections from any IP. OriginsAllowed = ""
SSL: enables secure connections.
SSLOptions: used to define SSL properties: certificates filenames, password...
RootCertFile: path to root certificate file.
CertFile: path to certificate file in PEM format.
KeyFile: path to certificate key file in PEM format.
Password: if certificate is secured with a password, set here.
VerifyCertificate: if certificate must be verified, enable this property.
VerifyCertificate_Options:
FailfIfNoCertificate: if the client did not return a certificate, the TLS/SSL handshake is immediately terminated with a "handshake failure" alert.
VerifyClientOnce: only request a client certificate on the initial TLS/SSL handshake. Do not ask for a client certificate again in case of a renegotiation.
VerifyDepth: is an Integer property that represents the maximum number of links permitted when verification is performed for the X.509 certificate.
Version: by default negotiates all possible TLS versions from newer to lower. A specific TLS version can be selected.
tlsUndefined: this is the default value, the client attempts to negotiate all available TLS versions (starting from newest to oldest), till connects successfully.
tls1_0: implements TLS 1.0
tls1_1:implements TLS 1.1
tls1_2: implements TLS 1.2
tls1_3: implements TLS 1.3
OpenSSL_Options:
APIVersion: allows defining which OpenSSL API will be used.
oslAPI_1_0: uses API 1.0 OpenSSL, it's latest supported by Indy
oslAPI_1_1: uses API 1.1 OpenSSL, requires our custom Indy library and allows using OpenSSL 1.1.1 libraries (with TLS 1.3 support).
oslAPI_3_0: uses API 3.0 OpenSSL, requires our custom Indy library and allows using OpenSSL 3.0.0 libraries (with TLS 1.3 support).
LibPath: here you can configure where are located the openSSL libraries
oslpNone: this is the default, the openSSL libraries should be in the same folder where is the binary or in a known path.
oslpDefaultFolder: sets automatically the openSSL path where the libraries should be located for all IDE personalities.
oslpCustomFolder: if this is the option selected, define the full path in the property LibPathCustom.
LibPathCustom: when LibPath = oslpCustomFolder define here the full path where are located the openSSL libraries.
UnixSymLinks: enable or disable the loading of SymLinks under Unix systems (by default is enabled, except under OSX64):
oslsSymLinksDefault: by default are enabled except under OSX64 (after MacOS Monterey fails trying to load the library without version.).
oslsSymLinksLoadFirst: Load SymLinks and do before trying to load the version libraries.
oslsSymLinksLoad: Load SymLinks after trying to load the version libraries.
oslsSymLinksDontLoad: don't load the SymLinks.
ECDHE: if enabled, uses ECDHE instead of RSA as key exchange. Recommended to enable ECDHE if you use OpenSSL 1.0.2.
CipherList: leave blank to use the default ciphers, if you want to customize the cipher list, set the value in this property. Example: ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256
CurveList: leave blank to use the default curves. You can set your own curve list names, for example: P-521:P-384:P-256:brainpoolP256r1
MinVersion: set here the minimum version accepted by the Server. By default, the value is tlsUndefined which means the minimum version is the same which has been set in the Version property. Example: if you want to set the Server to only accept TLS 1.2 and TLS 1.3 set the following values.
SSLOptions.Version := tls1_3;
SSLOptions.OpenSSL_Options.MinVersion := tls1_2;
ThreadPool: if enabled, when a thread is no longer needed this is put into a pool and marked as inactive (do not consume CPU cycles), it's useful if there are a lot of short-lived connections. The ThreadPool is not compatible with IOCP, so please don't enable it when IOCP is enabled.
MaxThreads: max number of threads to be created, by default is 0 meaning no limit. If max number is reached then the connection is refused.
PoolSize: size of ThreadPool, by default is 32.
WatchDog: if enabled, restarts the server after an unexpected disconnection.
Interval: seconds before reconnecting.
Attempts: maximum number of reconnection attempts; if zero, unlimited.
Throttle: used to limit the number of bits per second sent or received.