SGC Web Sockets
SGC Web Sockets
SGC Web Sockets
5
Table of Contents
IDE Editions ............................................................................................................................... 5
Delphi supported IDE ......................................................................................................... 5
CBuilder supported IDE ...................................................................................................... 5
AppMethod supported IDE ................................................................................................. 5
FreePascal supported IDE ................................................................................................. 5
HTML supported IDE .......................................................................................................... 5
Free Version ....................................................................................................................... 6
Library .................................................................................................................................... 6
Installation .................................................................................................................................. 7
Delphi / CBuilder / Lazarus .................................................................................................... 7
HTML5 Builder ....................................................................................................................... 9
QuickStart ................................................................................................................................ 11
VCL Server ....................................................................................................................... 11
VCL Client ........................................................................................................................ 11
WebBrowser Client ........................................................................................................... 11
How To Use ...................................................................................................................... 12
Linux Compiler .................................................................................................................. 12
Linux (Lazarus) ................................................................................................................. 13
WebBrowser Test .................................................................................................................... 14
Custom Sub-Protocols ............................................................................................................. 15
Client Example Code ........................................................................................................ 15
Server Example Code ...................................................................................................... 16
Implementation ................................................................................................................. 17
Features ................................................................................................................................... 19
Authentication ...................................................................................................................... 19
Custom Objects .................................................................................................................... 21
Secure Connections ............................................................................................................. 22
Compression ........................................................................................................................ 24
Flash..................................................................................................................................... 25
Bindings................................................................................................................................ 26
Quality Of Service ................................................................................................................ 27
Queues ................................................................................................................................. 29
Transactions ......................................................................................................................... 31
SubProtocol .......................................................................................................................... 33
HTTP .................................................................................................................................... 34
Throttle ................................................................................................................................. 35
Server-sent Events (Push Notifications) .............................................................................. 36
LoadBalancing ..................................................................................................................... 39
HeartBeat ............................................................................................................................. 40
WatchDog............................................................................................................................. 41
Files ...................................................................................................................................... 42
Proxy .................................................................................................................................... 43
Logs...................................................................................................................................... 44
General .................................................................................................................................... 45
WebSocket Events ............................................................................................................... 45
WebSocket Parameters Connection .................................................................................... 46
Using inside a DLL ............................................................................................................... 47
TsgcWebSocketServer ............................................................................................................ 49
Methods ............................................................................................................................ 49
Properties ......................................................................................................................... 50
TsgcWebSocketHTTPServer................................................................................................... 53
Methods ............................................................................................................................ 54
Properties ......................................................................................................................... 54
TsgcWebSocketServer_HTTPAPI ........................................................................................... 56
Methods ............................................................................................................................ 56
TsgcWebSocketClient ............................................................................................................. 58
Methods ............................................................................................................................ 58
iii
sgcWebSockets 4.1.5
Properties ......................................................................................................................... 59
TsgcWebSocketClient_SocketIO ............................................................................................ 62
Methods ............................................................................................................................ 62
Properties ......................................................................................................................... 63
Properties ......................................................................................................................... 63
TsgcWebSocketClient_WinHTTP ............................................................................................ 65
Methods ............................................................................................................................ 65
Properties ......................................................................................................................... 65
TsgcWebSocketLoadBalancerServer ...................................................................................... 67
TsgcWebSocketProxyServer ................................................................................................... 68
TsgcIWWebSocketClient ......................................................................................................... 69
Methods ............................................................................................................................ 69
Properties ......................................................................................................................... 69
Connections ............................................................................................................................. 71
TsgcWSConnection ............................................................................................................. 71
Protocols .................................................................................................................................. 73
Protocols .............................................................................................................................. 73
Protocols Javascript ............................................................................................................. 75
Subprotocols ........................................................................................................................ 78
Default .............................................................................................................................. 79
Dataset ............................................................................................................................. 88
Files .................................................................................................................................. 97
WebRTC ......................................................................................................................... 102
WAMP............................................................................................................................. 105
WAMP 2.0....................................................................................................................... 112
MQTT.............................................................................................................................. 118
APIs ....................................................................................................................................... 121
WebSocket APIs ................................................................................................................ 121
API...................................................................................................................................... 122
API Blockchain ............................................................................................................... 122
API Bitfinex ..................................................................................................................... 124
API Pusher ..................................................................................................................... 129
Extensions ............................................................................................................................. 133
Extensions .......................................................................................................................... 133
Extensions | PerMessage-Deflate ...................................................................................... 134
Extensions | Deflate-Frame ................................................................................................ 135
Library .................................................................................................................................... 137
Library | Build ......................................................................................................................... 138
QuickStart .............................................................................................................................. 139
QuickStart | Library | Delphi ............................................................................................... 139
QuickStart | Library | C# ..................................................................................................... 140
Client ...................................................................................................................................... 141
Library | Client .................................................................................................................... 141
Library Client | SocketIO .................................................................................................... 143
Library | Client Protocol SGC ............................................................................................. 147
Server .................................................................................................................................... 150
Library | Server ................................................................................................................... 150
Library | Server Protocol SGC............................................................................................ 152
WebSockets ........................................................................................................................... 155
JSON ..................................................................................................................................... 156
JSON-RPC 2.0 ...................................................................................................................... 157
Parsers ........................................................................................................................... 157
WAMP .................................................................................................................................... 158
WebRTC ................................................................................................................................ 159
MQTT ..................................................................................................................................... 160
Server-Sent Events ................................................................................................................ 161
License................................................................................................................................... 163
iv
Introduction
WebSockets represent a long awaited evolution in client/server web technology. They allow a
long-held single TCP socket connection to be established between the client and server which
allows for bi-directional, full duplex, messages to be instantly distributed with little overhead
resulting in a very low latency connection.
Both the WebSocket API and the well as native WebSocket support in browsers such as
Google Chrome, Firefox, Opera and a prototype Silverlight to JavaScript bridge implementation
for Internet Explorer, there are now WebSocket library implementations in Objective-C, .NET,
Ruby, Java, node.js, ActionScript and many other languages.
The Internet wasn’t built to be all that dynamic. It was conceived to be a collection of HyperText
Markup Language (HTML) pages linking to one another to form a conceptual web of
information. Over time the static resources increased in number and richer items, such as
images, began to be part of the web fabric. Server technologies advanced allowing for dynamic
server pages - pages whose content was generated based on a query.
Soon the requirement to have more dynamic web pages lead to the availability of Dynamic
HyperText Markup Language (DHTML) all thanks to JavaScript (let’s pretend VBScript never
existed). Over the following years we saw cross frame communication in an attempt to avoid
page reloads followed by HTTP Polling within frames. Things started to get interesting with the
introduction of LiveConnect, then the forever frame technique, and finally, thanks to Microsoft,
we ended up with the XMLHttpRequest object and therefore Asynchronous JavaScript and XML
(AJAX). In turn, AJAX made XHR Long-Polling and XHR Streaming possible. But none of these
solutions offered a truly standardised cross browser solution to realtime bi-directional
communication between a server and a client.
WebSockets don’t make AJAX obsolete but they do supersede Comet (HTTP Long-
polling/HTTP Streaming) as the solution of choice for true realtime functionality. AJAX should
still be used for making short-lived web service calls, and if we eventually see a good uptake in
CORS supporting web services, it will get even more useful. WebSockets should now be the go
to standard for realtime functionality since they offer low latency bi-directional communication
over a single connection. Even if a web browser doesn’t natively support the WebSocket object
there are polyfill fallback options which all but guarantee any web browser can actually establish
a WebSocket connection.
1
sgcWebSockets 4.1.5
2
Introduction
Delphi
C# .NET
3
Overview
IDE Editions
Delphi supported IDE
CBuilder 2010
CBuilder XE
CBuilder XE2
CBuilder XE3
CBuilder XE4
CBuilder XE5
CBuilder XE6
CBuilder XE7
CBuilder XE8
CBuilder 10 Seattle
CBuilder 10.1 Berlin
CBuilder 10.2 Tokyo
AppMethod 2014
Lazarus
5
sgcWebSockets 4.1.5
HTML5 Builder
Free Version
Compiled *.dcu files provided with free version are using default Indy and Intraweb version. If
you have upgraded any of these packets, probably it won't work or you need to buy full source
code version.
Library
Just copy sgcWebSockets.dll to your Application folder or to a common path. Supported
languages:
Delphi
C# .NET
6
Overview
Installation
Delphi / CBuilder / Lazarus
2. From Delphi\CBuilder:
Add the directory where the files are unzipped {$DIR} to the Delphi\CBuilder library path
under Tools, Environment options, Directories
C++ Builder 2010 : Add the directory {$DIR}\libD2010 to the library path
C++ Builder XE : Add the directory {$DIR}\libDXE to the library path
C++ Builder XE2 : Add the directory {$DIR}\libDXE2\$(Platform) to the library
path
C++ Builder XE3 : Add the directory {$DIR}\libDXE3\$(Platform) to the library
path
C++ Builder XE4 : Add the directory {$DIR}\libDXE4\$(Platform) to the library
path
C++ Builder XE5 : Add the directory {$DIR}\libDXE5\$(Platform) to the library
path
C++ Builder XE6 : Add the directory {$DIR}\libDXE6\$(Platform) to the library
path
C++ Builder XE7 : Add the directory {$DIR}\libDXE7\$(Platform) to the library
path
C++ Builder XE8 : Add the directory {$DIR}\libDXE8\$(Platform) to the library
path
C++ Builder 10 : Add the directory {$DIR}\libD10\$(Platform) to the library
path
C++ Builder 10.1 : Add the directory {$DIR}\libD10_1\$(Platform) to the library
path
7
sgcWebSockets 4.1.5
For all CBuilder versions, Add dcp\$(Platform) to the library path (contains .bpi
files)
For AppMethod
3. From Delphi
Choose
File, Open and browse for the correct Packages\sgcWebSockets.groupproj (First
compile sgcWebSocketsX.dpk and then install dclsgcWebSocketsX.dpk)
sgcWebSocketsD7.groupproj : Delphi 7
sgcWebSocketsD2007.groupproj : Delphi 2007
sgcWebSocketsD2009.groupproj : Delphi 2009
sgcWebSocketsD2010.groupproj : Delphi 2010
sgcWebSocketsDXE.groupproj : Delphi XE
sgcWebSocketsDXE2.groupproj : Delphi XE2
sgcWebSocketsDXE3.groupproj : Delphi XE3
sgcWebSocketsDXE4.groupproj : Delphi XE4
sgcWebSocketsDXE5.groupproj : Delphi XE5
sgcWebSocketsDXE6.groupproj : Delphi XE6
sgcWebSocketsDXE7.groupproj : Delphi XE7
sgcWebSocketsDXE8.groupproj : Delphi XE8
sgcWebSocketsD10.groupproj : Delphi 10
sgcWebSocketsD10_1.groupproj : Delphi 10.1
sgcWebSocketsD10_2.groupproj : Delphi 10.2
4. From CBuilder
Choose
File, Open and browse for the correct Packages\sgcWebSockets.groupproj (First
compile sgcWebSocketsX.dpk and then install dclsgcWebSocketsX.dpk)
8
Overview
5. From AppMethod
Choose
File, Open and browse for the correct Packages\sgcWebSockets.groupproj
(First compile sgcWebSocketsX.dpk and then install dclsgcWebSocketsX.dpk)
sgcWebSocketsAppMethod.groupproj : AppMethod
6. From Lazarus
Compiled files are located on Lazarus Directory, inside this, there is a Indy directory with
latest Indy source version.
7. Demos
All demos are available in subdirectory Demos. Just open the project and run it. Intraweb
demos may need to modify some units due to different Intraweb Versions.
HTML5 Builder
1. Copy "esegece" directory into HTML5 Builder’s RPCL directory.
3. If you start a new project you will see a new palette called "SGC - WebSockets", drop a
sgcWebSocket component on a Form and configure required properties.
4. Demos
All demos are available in subdirectory Demos. Just open the project and run it.
9
QuickStart
QuickStart
Let's start with a basic example where we need to create a Server WebSocket and 2 client
WebSocket types: VCL Application Client and Web Browser Client.
VCL Server
3. On Events Tab, Double click OnMessage Event, and type following code:
sgcWebSocketServer1.Active := True;
5. Build Project and that's all, you have configured a basic WebSocket Server.
VCL Client
2. Drop a TsgcWebSocketClient in a Form and configure Host and Port Properties to connect to
Server.
sgcWebSocketClient1.Active := True;
5. Build Project and that's all, you have configured a basic WebSocket Client.
WebBrowser Client
<html>
11
sgcWebSockets 4.1.5
<head>
<script type="text/javascript"
src="http://host:port/sgcWebSockets.js"></script>
</head>
<body>
<a href="javascript:var socket = new
sgcWebSocket('ws://host:port');">Open</a>
<a href="javascript:socket.send('Hello Server From Web
Browser');">Send</a>
</body>
</html>
You need to replace host and port in this file for your custom Host and Port!!
3. Save File and that's all, you have configured a basic WebSocket Web Browser Client.
How To Use
1. Start VCL Server Application and press button to start WebSocket Server to listen new
connections.
2. Start VCL Client Application and press button1 to connect to server and press button2 to
send a message. On Server Side, you will see a message with text sent by VCL Client.
3. Open HTML file with your Web Browser (Chrome, Firefox, Safari or Internet Explorer 10+),
press Open to open a connection and press send, to send a message to server. On Server
Side, you will see a message with text sent by Web Browser Client.
Linux Compiler
program sgcWebSockets_linux;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils, sgcWebSocket;
var
oServer: TsgcWebSocketServer;
begin
try
oServer := TsgcWebSocketServer.Create(nil);
oServer.Port := 5000;
oServer.Active := True;
while oServer.Active do
Sleep(10);
12
QuickStart
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
Linux (Lazarus)
If you compile a Lazarus project for linux and you get this message:
13
sgcWebSockets 4.1.5
WebBrowser Test
TsgcWebSocketServer implements a built-in Web page where you can test WebSocket Server
connection with your favorite WebBrowser.
http://host:port/sgcWebSockets.html
Example: if you have configured your WebSocket Server on IP 127.0.0.1 and uses port 80, then
you need to type:
http://127.0.0.1:80/sgcWebSockets.html
Open
Close
Status
Send
14
QuickStart
Custom Sub-Protocols
Client can request that the server use a specific subprotocol by including the subprotocol name
in its handshake. If it is specified, the server needs to include one of the selected subprotocol
values in its response for the connection to be established.
In order to create your own subprotocol, you must inherit from TsgcWSProtocol_Client_Base
and TsgcWSProtocol_Server_Base in order to create your custom subprotocols.
unit sgcWebSocket_Protocol_Example_Client;
interface
{$I sgcVer.inc}
{$IFDEF SGC_PROTOCOLS}
uses
sgcWebSocket_Protocol_Base_Client, Classes,
sgcWebSocket_Classes;
type
TsgcWSProtocol_Example_Client =
class(TsgcWSProtocol_Client_Base)
{ from TsgcWSComponent }
protected
procedure DoEventConnect(aConnection: TsgcWSConnection);
override;
procedure DoEventMessage(aConnection: TsgcWSConnection; const
Text: string);
override;
procedure DoEventDisconnect(aConnection: TsgcWSConnection;
Code: Integer);
override;
{ from TsgcWSComponent }
public
constructor Create(aOwner: TComponent); override;
end;
{$ENDIF}
implementation
{$IFDEF SGC_PROTOCOLS}
constructor TsgcWSProtocol_Example_Client.Create(aOwner:
TComponent);
begin
inherited;
// ... here add your protocol name
FProtocol := 'MyProtocol';
end;
procedure
TsgcWSProtocol_Example_Client.DoEventConnect(aConnection:
TsgcWSConnection);
15
sgcWebSockets 4.1.5
begin
inherited;
// ... add your own code when client connects to server
end;
procedure
TsgcWSProtocol_Example_Client.DoEventDisconnect(aConnection:
TsgcWSConnection; Code: Integer);
begin
// ... add your own code when client disconnects from server
inherited;
end;
procedure
TsgcWSProtocol_Example_Client.DoEventMessage(aConnection:
TsgcWSConnection; const Text: string);
begin
// ... process messages received from server
// ... you can send a message to server using WriteData('your
message') method
end;
{$ENDIF}
end.
unit sgcWebSocket_Protocol_Example_Server;
interface
{$I sgcVer.inc}
{$IFDEF SGC_PROTOCOLS}
uses
sgcWebSocket_Protocol_Base_Server, Classes,
sgcWebSocket_Classes;
type
TsgcWSProtocol_Example_Server =
class(TsgcWSProtocol_Server_Base)
{ from TsgcWSComponent }
protected
procedure DoEventConnect(aConnection: TsgcWSConnection);
override;
procedure DoEventMessage(aConnection: TsgcWSConnection; const
Text: string);
override;
procedure DoEventDisconnect(aConnection: TsgcWSConnection;
Code: Integer);
override;
{ from TsgcWSComponent }
public
constructor Create(aOwner: TComponent); override;
end;
{$ENDIF}
implementation
{$IFDEF SGC_PROTOCOLS}
16
QuickStart
constructor TsgcWSProtocol_Example_Server.Create(aOwner:
TComponent);
begin
inherited;
// ... here add your protocol name
FProtocol := 'MyProtocol';
end;
procedure
TsgcWSProtocol_Example_Server.DoEventConnect(aConnection:
TsgcWSConnection);
begin
inherited;
// ... add your own code when a client connects to server
end;
procedure
TsgcWSProtocol_Example_Server.DoEventDisconnect(aConnection:
TsgcWSConnection; Code: Integer);
begin
// ... add your own code when a client disconnects from server
inherited;
end;
procedure
TsgcWSProtocol_Example_Server.DoEventMessage(aConnection:
TsgcWSConnection; const Text: string);
begin
inherited;
// ... process messages received from clients
// ... you can answer to client using
WriteData(aConnection.Guid, 'your message') method
// ... you can send a message to all clients using
BroadCast('your message') method
end;
{$ENDIF}
end.
Implementation
Once your custom subprotocol is implemented, then you only need to assign to your Client or
Server websocket component. Example:
procedure InitalizeClient;
var
oClient: TsgcWebSocketClient;
oProtocol: TsgcWSProtocol_Example_Client;
begin
oClient := TsgcWebSocketClient.Create(nil);
oProtocol := TsgcWSProtocol_Example_Client.Create(nil);
oProtocol.Client := oClient;
end;
procedure InitalizeServer;
var
oServer: TsgcWebSocketServer;
oProtocol: TsgcWSProtocol_Example_Server;
begin
17
sgcWebSockets 4.1.5
oClient := TsgcWebSocketServer.Create(nil);
oProtocol := TsgcWSProtocol_Example_Server.Create(nil);
oProtocol.Server := oServer;
end;
18
Topics
Features
Authentication
Supported by
TsgcWebSocketServer
TsgcWebSocketHTTPServer
TsgcWebSocketClient
Java script (*only URL Authentication is supported)
WebSockets Specification doesn't has any authentication method and Web Browsers
implementation don't allow to send custom headers on new WebSocket connections.
Authentication/ Enabled
Session: client need to do a 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. You can use a normal HTTP request to
get a session id using and passing user and password as parameters
http://host:port/sgc/req/auth/session/:user/:password
This returns a token that is used to connect to server using WebSocket connections:
ws://localhost/sgc/auth/session/:token
ws://host:port/sgc/auth/url/username/password
19
sgcWebSockets 4.1.5
You can define a list of Authenticated users, using Authentication/ AuthUsers property. You
need to define every item following this schema: user=password. Example:
admin=admin
user=1234
....
There is an event called OnAuthentication where you can handle authentication if user is not
in AuthUsers list, client don't send an authorization request... You can check User and
Password params and if correct, then set Authenticated variable to True. example:
20
Topics
Custom Objects
Supported by
TsgcWebSocketServer
TsgcWebSocketHTTPServer
TsgcWebSocketClient
TsgcWebSocketClient_SocketIO
You can create a new class called MyClass and create some properties, example:
TMyClass = class
private
FRegistered: Boolean;
FUser: String;
public
property Registered: Boolean read FRegistered write
FRegistered;
property User: String read FUser write FUser;
end;
Then, when a new client connects, OnConnect Event, create a new TMyClass and Assign to
Data:
Every time a new message is received by server, you can access to your custom object using
Connection.Data property.
procedure TfrmServerChat.WSServerDisconnect(Connection:
TsgcWSConnection;
Code: Integer);
var
oMyClass: TMyClass;
begin
oMyClass := TMyClass(Connection.Data);
if Assigned(oMyClass) then
begin
oMyClass.Free
Connection.Data := nil;
end;
end;
21
sgcWebSockets 4.1.5
Secure Connections
Supported by
TsgcWebSocketServer
TsgcWebSocketHTTPServer
TsgcWebSocketClient
TsgcWebSocketClient_SocketIO
Web Browsers
SSL support is based on Indy implementation, so you need to deploy openssl libraries in order
to use this feature. In Compiled Demos file, there is a directory called Third-Parties/ openssl,
where you can find the libraries need for every Delphi Version.
Server Side
SSL/ Enable
SSLOptions/ Password: this is optional and only needed if certificate has a password.
Client Side
TLS/ Enable
Events
There are 2 events which can be used to customize your SSL settings:
1. 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:
22
Topics
23
sgcWebSockets 4.1.5
Compression
Supported by
TsgcWebSocketServer
TsgcWebSocketHTTPServer
TsgcWebSocketClient
TsgcWebSocketClient_SocketIO
Web Browsers like Chrome
This is a feature that works very well when you need to send a lot of data, usually using a binary
message, because it compresses WebSocket message using protocol "PerMessage_Deflate"
which is supported by some browsers like Chrome.
When a client tries to connect to a WebSocket Server and this property is enabled, it sends a
header with this property enabled, if Server has activated this feature, it sends a response to
client with this protocol activated and all messages will be compressed; if Server doesn't has
this feature, then all messages will be sent without compression.
On Web Browsers, you don't need to do anything, if this extension is supported it will be used
automatically, if not, then messages will be sent without compression.
If WebSocket messages are small, is better don't enable this property because it consumes cpu
cycle to compress/decompress messages; but if you are using big amount of data, you will
notify and increase on messages exchange speed.
24
Topics
Flash
Supported by
TsgcWebSocketServer
TsgcWebSocketHTTPServer
WebSockets are supported natively by a wide range of web browsers (please check
http://caniuse.com/websockets), but there are some old versions that don't implement
WebSockets (like Internet Explorer 6, 7, 8 or 9). You can enable Flash Fallback for all these
browsers that don't implement WebSockets.
Almost all other or older browser support Flash installing Adobe Flash Player. To Support Flash
connection, you need to open port 843 on your server because Flash uses this port for security
reasons to check for cross-domain-access. If port 843 is not reachable, waits 3 seconds and
tries to connect to Server default port.
Flash is only applied if Browser doesn't support websockets natively. So, if you enable Flash
Fallback on server side, and Web Browser supports WebSockets natively, it will still use
WebSockets as transport.
To enable Flash Fallback, you need to access to FallBack / Flash property on server and
enable it. There are 2 properties more:
1. Domain: if you need to restrict flash connections to a single/multiple domains (by default all
domains are allowed). Example: This will allow access to domain swf.example.com
swf.example.com
2. Ports: if you need to restrict flash connections to a single/multiple ports (by default all ports
are allowed). Example: This will allow access to ports 123, 456, 457, and 458
123,456-458
Flash connections only support Text messages, binary messages are not supported.
25
sgcWebSockets 4.1.5
Bindings
Supported by
TsgcWebSocketServer
TsgcWebSocketHTTPServer
Usually Server have more than one IP, if you enable a WebSocket Server and set listening port
to 80, when server starts, tries to listen port 80 of ALL IP, so if you have 3 IP, it will block port 80
of each IP's.
Bindings allows to define which exact IP and Port are used by the Server. Example, if you need
to listen on port 80 for IP 127.0.0.1 (internal address) and 80.254.21.11 (public address), you
can do this before server is activated:
With WSServer.Bindings.Add do
begin
Port := 80;
IP := 127.0.0.1;
end;
With WSServer.Bindings.Add do
begin
Port := 80;
IP := 80.254.21.11;
end;
26
Topics
Quality Of Service
Supported by
TsgcWSPServer_sgc
TsgcWSPClient_sgc
TsgcWSPClient_MQTT
Java script
SGC Default Protocol and MQTT implements a QoS (Quality of Service) for message delivery,
there are 3 different types:
Level 0: "At most once", where messages are delivered according to the best efforts of
the underlying TCP/IP network. Message loss or duplication can occur. This level could
be used, for example, with ambient sensor data where it does not matter if an individual
reading is lost as the next one will be published soon after.
Level 1: "At least once", where messages are assured to arrive but duplicates may
occur.
Level 2: "Exactly once", where message are assured to arrive exactly once. This level
could be used, for example, with billing systems where duplicate or lost messages could
lead to incorrect charges being applied.
Level 0
The message is delivered according to the best efforts of the underlying TCP/IP network.
A response is not expected and no retry semantics are defined in the protocol. The
message arrives at the server either once or not at all.
Message and
Client Server
direction
Level 1
Message and
Client Server
direction
27
sgcWebSockets 4.1.5
If the client does not receive a ACKNOWLEDGMENT message (either within a time
period defined in the application, or if a failure is detected and the communications
session is restarted), the client may resend the PUBLISH message.
Level 2
Additional protocol flows above QoS level 1 ensure that duplicate messages are not
delivered to the receiving application. This is the highest level of delivery, for use when
duplicate messages are not acceptable. There is an increase in network traffic, but it is
usually acceptable because of the importance of the message content.
The table below shows the QoS level 2 protocol flow. There are two semantics available
for how a PUBLISH flow should be handled by the recipient.
Message and
Client Server
direction
QoS = 2
Message ID = x PUBLISH
Action: Store message
Action: Store ---------->
message
PUBREC
Message ID = x
<----------
Actions:
If a failure is detected, or after a defined time period, the protocol flow is retried from the
last unacknowledged protocol message. The additional protocol flows ensure that the
message is delivered to subscribers once only.
28
Topics
Queues
Supported by
TsgcWSPServer_sgc
TsgcWSPClient_sgc
Java script
Level 0
Message and
Client Server
direction
Queue = PUBLISH Action: Publish message to
0 ----------> subscribers
Level 1
29
sgcWebSockets 4.1.5
and
direction
Actions:
Deletes All
messages of this
PUBLISH
Queue = 1 channel
---------->
Store last message by
Channel
Level 2
Message
Client and Server
direction
PUBLISH
Queue = 2 Action: Store message
---------->
30
Topics
Transactions
Supported by
TsgcWSPServer_sgc
TsgcWSPClient_sgc
Java script
StartTransaction
Message and
Client Server
direction
Action: Creates a
STARTTRANSACTION new Queue to store
Channel = X
----------> all Messages of
specified channel
Action: Message is
PUBLISH
Channel = X stored on Server
---------->
Side.
Action: Server
Action: Client returns an
ACKNOWLEDGMENT
get confirmation Acknowledgment to
<----------
of message sent client because
message is stored.
.... .... ....
Commit
31
sgcWebSockets 4.1.5
direction
Channel COMMIT Action: Process all messages
=X ----------> queued by Transaction
RollBack
Message and
Client Server
direction
Channel ROLLBACK Action: Delete all messages
=X ----------> queued by Transaction
32
Topics
SubProtocol
Supported by
TsgcWebSocketServer
TsgcWebSocketHTTPServer
TsgcWebSocketClient
WebSocket provides a simple subprotocol negotiation, basically adds a header with protocols
name supported by request, this protocols are received and if receiver supports one of them,
sends a response with subprotocol supported.
sgcWebSockets supports several SubProtocols: MQTT, WAMP... and more. You can implement
your own subprotocols using a very easy method, just call RegisterProtocol and send
SubProtocol Name as argument.
Example: you need to connect to a server which implements subprotocol "Test 1.0"
33
sgcWebSockets 4.1.5
HTTP
Supported by
TsgcWebSocketHTTPServer
You can serve HTML pages statically, using DocumentRoot property, example: if you save
test.html in directory "C:\inetpub\wwwroot", and you set DocumentRoot to
"C:\inetpub\wwwroot". If a client tries to access to test.html, it will be served automatically,
example:
http://localhost/test.html
Or you can serve HTML or other resources dynamically by code, to do this, there is an event
called OnCommandGet that is fired every time a client requests a new HTML page, image,
javascript file... Basically you need to check which document is requesting client (using
ARequestInfo.Document) and send a response to client (using AResponseInfo.ContentText
where you send response content, AResponse.ContentType which is the type of response and
a AResponseInfo.ResponseNo with number of response code, usually is 200), example:
34
Topics
Throttle
Supported by
TsgcWebSocketServer
TsgcWebSocketHTTPServer
TsgcWebSocketClient
TsgcWebSocketClient_SocketIO
Bandwidth Throttling is supported by Server and Client components, if enabled, can limit the
amount of bits per second sent/received by socket. Indy uses a blocking method, so if a client is
limiting its reading, unread data will be inside client socket and server will be blocked from
writing new data to client. As much slower is client reading data, much slower is server writing
new data.
35
sgcWebSockets 4.1.5
TsgcWebSocketServer
TsgcWebSocketHTTPServer
Java script
SSE are not part of WebSockets, defines an API for opening an HTTP connection for receiving
push notifications from a server.
SSEs are sent over traditional HTTP. That means they do not require a special protocol or
server implementation to get working. In addition, Server-Sent Events have a variety of features
that WebSockets lack by design such as automatic reconnection, event IDs, and the ability to
send arbitrary events.
Events
JavaScript API
To subscribe to an event stream, create an EventSource object and pass it the URL of your
stream:
sse.addEventListener('message', function(e) {
console.log(e.data);
}, false);
sse.addEventListener('open', function(e) {
// Connection was opened.
}, false);
sse.addEventListener('error', function(e) {
if (e.readyState == EventSource.CLOSED) {
// Connection was closed.
}
}, false);
When updates are pushed from the server, the onmessage handler fires and new data is be
available in its e.data property. If the connection is closed, the browser will automatically
reconnect to the source after ~3 seconds (this is a default retry interval, you can change on
server side).
Fields
event
The event's type. If this is specified, an event will be dispatched on the browser to the listener
for the specified event name; the web site would use addEventListener() to listen for named
events. the onmessage handler is called if no event name is specified for a message.
36
Topics
data
The data field for the message. When the EventSource receives multiple consecutive lines that
begin with data:, it will concatenate them, inserting a newline character between each one.
Trailing newlines are removed.
id
The event ID to set the EventSource object's last event ID value to.
retry
The reconnection time to use when attempting to send the event. This must be an integer,
specifying the reconnection time in milliseconds. If a non-integer value is specified, the field is
ignored.
Examples of use:
To send a message to all Clients using url 'sse.html', use Broadcast method and Channel
parameter:
You can send a unique id with an stream event by including a line starting with "id:":
sse.addEventListener('notifications', function(e) {
console.log('notifications:' + e.data);
}, false);
37
sgcWebSockets 4.1.5
38
Topics
LoadBalancing
Supported by
TsgcWebSocketServer
TsgcWebSocketHTTPServer
TsgcWebSocketLoadBalancerServer
Load Balancing allows to distribute work between several back-end servers, every time a new
client request a connection, it connects to a load balancer server (which is connected to back-
end servers) and returns a connection string with information about host, port... which is used
by client to connect to a server. If you have for example 4 servers, with this method all servers
will have, more or less, the same number of connections, and work load will be similar.
If a client want to send a message to all clients of all servers, just use broadcast method, and
this message will be broadcast to all servers connected to Load Balancer Server.
2. Server and Client components, have a property called LoadBalancer, where you need
to set host and port of Load Balancer Server, and enabled True.
39
sgcWebSockets 4.1.5
HeartBeat
Supported by
TsgcWebSocketServer
TsgcWebSocketHTTPServer
TsgcWebSocketClient
TsgcWebSocketClient_SocketIO
On Server components, automatically sends a ping to all active WebSocket connections every x
seconds.
40
Topics
WatchDog
Supported by
TsgcWebSocketServer
TsgcWebSocketHTTPServer
TsgcWebSocketClient
TsgcWebSocketClient_SocketIO
41
sgcWebSockets 4.1.5
Files
Supported by
TsgcWSPServer_sgc
TsgcWSPClient_sgc
This protocol allows to send files from client to server and from server to client in an easy way.
You can send from really small files to big files using a low memory usage. You can set:
42
Topics
Proxy
Supported by
TsgcWebSocketClient
TsgcWebSocketClient_SocketIO
Proxy / Enabled
You can configure SOCKS proxies accessing to SOCKS property and setting Enable to True.
43
sgcWebSockets 4.1.5
Logs
Supported by
TsgcWebSocketServer
TsgcWebSocketHTTPServer
TsgcWebSocketClient
TsgcWebSocketClient_SocketIO
This is a useful feature that allows to debug WebSocket connections, to enable this, you need
to access to the following property:
LogFile/ Enabled
Once enabled, every time a new connection is established it will be logged in a text file. On
Server component, if file it's not created it will be created but with you can't access until server is
closed, if you want to open log file while server is active, log file needs to be created before start
server.
Example:
44
Topics
General
WebSocket Events
WebSocket connections have the following events:
OnConnect
Event raised when a new connection is established.
OnDisconnect
Event raised when a connection is closed.
OnError
Event raised when a connection has any error.
OnMessage
Event raised when a new text message is received.
OnBinary
Event raised when a new binary message is received.
45
sgcWebSockets 4.1.5
TsgcWebSocketClient
TsgcWebSocketClient_SocketIO
Java script
Sometimes is useful to pass parameters from client to server when a
new WebSocket connection is established. If you need to pass
some parameters to server, you can use the following property:
Options / Parameters
By default, si set to '/', if you need to pass a parameter like id=1, you
can set this property to '/?id=1'
Using Javascript, you can pass parameters using connection url, example:
<script src="http://localhost/sgcWebSockets.js"></script>
<script>
var socket = new sgcWebSocket('ws://localhost/?id=1');
</script>
46
Topics
47
Components
TsgcWebSocketServer
TsgcWebSocketServer implements Server WebSocket Component and can handle multiple
threaded client connections. Follow next steps to configure this component:
2. Set Port (default is 80). If you are behind a firewall probably you will need to configure it.
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
OnError: every time there is a WebSocket error (like mal-formed handkshake), this event is
fired.
OnMessage: every time a client sends a text message and it's received by server, this event
is fired.
OnBinary: every time a client sends a binary message and it's received by server, this event
is fired.
OnAuthentication: if authentication is enabled, this event if fired. You can check user and
password passed by client and enable/disable Authenticated Variable.
sgcWebSocketServer1.Active := True
Methods
49
sgcWebSockets 4.1.5
Stop: uses a secondary thread to disconnect from server, this prevents your
application freezes while try to disconnect.
Properties
user=password
Session: client need to do a 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.
Extensions: you can enable compression on messages sent (if client don't support
compression, messages will be exchanged automatically without compression).
50
Components
FallBack: if WebSockets protocol it's not supported natively by browser, you can enable the
following fallbacks:
Flash: if enabled, if browser hasn't native websocket implementation and has flash enabled,
it uses Flash as a Transport.
HeartBeat: if enabled try to keeps alive websocket client connections sending a ping every x
seconds.
LoadBalancer: it's a client which connects to Load Balancer Server to broadcast messages
and send information about 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
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:
51
sgcWebSockets 4.1.5
ReadEmptySource: max number of times an HTTP Connection is read and there is no data
received, 0 by default (means no limit). If limit is reached, then connection is closed.
SecurityOptions:
OriginsAllowed: define here which origins are allowed (by default accepts connections
from all origins), if origin is not in the list closes connection.
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-live
connections.
52
Components
TsgcWebSocketHTTPServer
TsgcWebSocketHTTPServer implements Server WebSocket Component and can handle
multiple threaded client connections as TsgcWebSocketServer, and allows to server HTML
pages using a built-in HTTP Server, sharing the same port for websocket connections and
HTTP requests.
2. Set Port (default is 80). If you are behind a firewall probably you will need to configure it.
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
OnError: every time there is a WebSocket error (like mal-formed handkshake), this event is
fired.
OnMessage: every time a client sends a text message and it's received by server, this event
is fired.
OnBinary: every time a client sends a binary message and it's received by server, this event
is fired.
OnCommandGet: this event is fired when HTTP Server receives a GET command
requesting a HTML page, an image... Example:
AResponseInfo.ContentText :=
'<HTML><HEADER>TEST</HEAD><BODY>Hello!</BODY></HTML>';
OnCommandOther: this event is fired when HTTP Server receives a command different of
GET.
OnCreateSession: this event is fired when HTTP Server creates a new session.
OnSessionStart: this event is fired when HTTP Server starts a new session.
53
sgcWebSockets 4.1.5
OnAuthentication: if authentication is enabled, this event if fired. You can check user and
password passed by client and enable/disable Authenticated Variable.
sgcWebSocketHTTPServer1.Active := True
Methods
Properties
DocumentRoot: here you can define a directory where you can put all html files (javascript,
html, css...) if a client sends a request, server automatically will search this file on this directory,
if it finds, it will be served.
Extensions: you can enable compression on messages sent (if client don't support
compression, messages will be exchanged automatically without compression).
AutoStartSession: if SessionState is active, when server gets a new http request, creates a
new session.
KeepAlive: if enabled, connection will stay alive after the response has been sent.
54
Components
55
sgcWebSockets 4.1.5
TsgcWebSocketServer_HTTPAPI
The HTTP Server API enables applications to communicate over HTTP without using Microsoft
Internet Information Server (IIS). Applications can register to receive HTTP requests for
particular URLs, receive WebSocket requests, and send WebSocket responses. The HTTP
Server API includes SSL support so that applications can exchange data over secure HTTP
connections without IIS. It is also designed to work with I/O completion ports.
2. Add which URL/s you need register, example: if connections to port 8080 with "/ws/"
parameter are websocket connections, register the following URL
WSServer.RegisteredURLs.Add('http://+:8080/ws/');
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
OnError: every time there is a WebSocket error (like mal-formed handkshake), this event is
fired.
OnMessage: every time a client sends a text message and it's received by server, this event
is fired.
OnBinary: every time a client sends a binary message and it's received by server, this event
is fired.
OnAuthentication: if authentication is enabled, this event if fired. You can check user and
password passed by client and enable/disable Authenticated Variable.
sgcWebSocketServer_HTTPAPI1.Active := True
Methods
56
Components
57
sgcWebSockets 4.1.5
TsgcWebSocketClient
TsgcWebSocketClient implements Client VCL WebSocket Component and can connect to a
WebSocket Server, it's based on Indy library. Follow next steps to configure this component:
2. Set Host and Port (default is 80) to connect to an available WebSocket Server. You can set
URL property and Host, Port, Parameters... will be updated from URL. Example:
wss://127.0.0.1:8080/ws/ will result:
Host := '127.0.0.1';
Port := 80;
TLS := True;
Options.Paramters := '/ws/';
3. You can select if you want TLS (secure connection) or not, by default is not Activated.
4. You can connect through a HTTP Proxy Server, you need to define proxy properties:
5. If server supports compression, you can enable compression to compress messages sent.
OnError: every time there is a WebSocket error (like mal-formed handkshake), this event is
fired
OnMessage: every time server sends a text message, this event is fired
OnBinary: every time server sends a binary message, this event is fired
sgcWebSocketClient1.Active := True
Methods
58
Components
Stop: uses a secondary thread to disconnect from server, this prevents your
application freezes while try to disconnect.
Properties
Session: client need to do a 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.
HeartBeat: if enabled try to keeps alive websocket a connection sending a ping every x
seconds.
LoadBalancer: it's a client which connects to Load Balancer Server to broadcast messages
and get information about servers.
Servers: here you can set manual WebSocket Servers to connect (if you don't make use of
Load Balancer Server get server connection methods), example:
http://127.0.0.1:80
http://127.0.0.2:8888
59
sgcWebSockets 4.1.5
LogFile: if enabled save 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.
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.
Proxy: here you can define if you want to connect through a HTTP Proxy Server. If you need
to connect to SOCKS proxies, just enable SOCKS.Enable property too.
60
Components
61
sgcWebSockets 4.1.5
TsgcWebSocketClient_SocketIO
TsgcWebSocketClient_SocketIO inherits all properties and methods from TsgcWebSocketClient
and allows to connect to a Socket.IO Server.
Methods
Examples:
SendDisconnect('/test');
SendDisconnect;
SendConnect: Only used for multiple sockets. Signals a connection to the endpoint. Once
the server receives it, it's echoed back to the client.
Example, if the client is trying to connect to the endpoint /test, a message like this will be
delivered:
SendConnect('[path] [query]');
Example:
SendConnect('/test?my=param');
To acknowledge the connection, the server echoes back the message. Otherwise, the
server might want to respond with a error packet.
SendHeartBeat: Sends a heartbeat. Heartbeats must be sent within the interval negotiated
with the server. It's up to the client to decide the padding (for example, if the heartbeat timeout
negotiated with the server is 20s, the client might want to send a heartbeat evert 15s).
Example:
SendHeartBeat;
Example: send a text message "Hi Folks", with id "fjghs121" to clients connected to
EndPoint "/test"
SendJSONMessage('{"a":"b"}');
62
Components
SendEvent: An event is like a json message, but has mandatory name and args fields. name
is a string and args an array.
The event names: 'message', 'connect', 'disconnect', 'open', 'close', 'error', 'retry',
'reconnect' are reserved, and cannot be used by clients or servers with this message
type.
SendEvent('test', ["1","2","3"]);
SendACK("2");
Example: send error "not authorized" with advise "connect with admin user"
SendNoop: No operation. Used for example to close a poll after the polling duration times
out.
Example:
SendNoop;
Properties
These events are only raised if "RawMessages" property is disabled and ioAPI0 is selected.
OnMessageDisconnect
OnMessageConnect
OnMessageHeartBeat
OnMessageText
OnMessageJSON
OnMessageEvent
OnMessageACK
OnMessageError
OnMessageNoop
Properties
63
sgcWebSockets 4.1.5
RawMessages: if not enabled (which is default) socket.io messages are processed and
specific socket.io messages events are raised, if enabled, then socket.io messages are not
processed and OnMessage event is raised.
64
Components
TsgcWebSocketClient_WinHTTP
TsgcWebSocketClient implements Client VCL WebSocket Component and can connect to a
WebSocket Server, it's based on WinHTTP API and requires Windows 8 or higher. Follow next
steps to configure this component:
2. Set Host and Port (default is 80) to connect to an available WebSocket Server. You can set
URL property and Host, Port, Parameters... will be updated from URL. Example:
wss://127.0.0.1:8080/ws/ will result:
Host := '127.0.0.1';
Port := 80;
TLS := True;
Options.Paramters := '/ws/';
3. You can select if you want TLS (secure connection) or not, by default is not Activated.
OnError: every time there is a WebSocket error (like mal-formed handkshake), this event is
fired
OnMessage: every time server sends a text message, this event is fired
OnBinary: every time server sends a binary message, this event is fired
sgcWebSocketClient_WinHTTP1.Active := True
Methods
Properties
Basic: client open websocket connection passing username and password inside
header.
65
sgcWebSockets 4.1.5
HeartBeat: if enabled try to keeps alive websocket a connection sending a ping every x
seconds.
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.
Proxy: here you can define if you want to connect through a HTTP Proxy Server.
66
Components
TsgcWebSocketLoadBalancerServer
TsgcWebSocketLoadBalancerServer allows to distribute messages across a group of servers
and distributes clients connections using a random sequence or less connections algorithm.
Load Balancer Server, inherits all methods and properties from TsgcWebSocketServer.
2. Set Port (default is 80). If you are behind a firewall probably you will need to configure it.
3.1 lbRandom: every time a new client request a new connection, it will return a random
server.
3.1 lbConnections: every time a new client request a new connection, it will return server
with less clients connected.
sgcWebSocketLoadBalancerServer1.Active := True
67
sgcWebSockets 4.1.5
TsgcWebSocketProxyServer
TsgcWebSocketProxyServer implements a WebSocket Server Component which listens client
websocket connections and forward data connections to a normal TCP/IP server. This is
specially useful for browser connections, because allows a browser to virtually connect to any
server.
68
Components
TsgcIWWebSocketClient
TsgcIWWebSocketClient implements Intraweb WebSocket Component and can connect to a
WebSocket Server. Follow next steps to configure this component:
2. Set Host and Port (default is 80) to connect to an available WebSocket Server. You can set
URL property and Host, Port, Parameters... will be updated from URL. Example:
wss://127.0.0.1:8080/ws/ will result:
Host := '127.0.0.1';
Port := 80;
TLS := True;
Paramters := '/ws/';
3. You can select if you want TLS (secure connection) or not, by default is not Activated.
Emulation: if browser don't support WebSockets, then it will use a loop AJAX callback
connection
OnAsyncError: every time there is a WebSocket error (like mal-formed handkshake), this
event is fired
sgcIWWebSocketClient1.Open;
Methods
Properties
69
sgcWebSockets 4.1.5
Connected: is a read-only variable and returns True if connection is Active, otherwise returns
False.
JSOpen: here you can include JavaScript Code on client side when a connection is opened.
JSClose: here you can include JavaScript Code on client side when a connection is closed.
JSMessage: here you can include JavaScript Code on client side when clients receives a
message from server. You can get Message String, using Javascript variable "text".
JSError: here you can include JavaScript Code on client side when an error is raised. You
can get Message Error, using Javascript variable "text".
70
Components
Connections
TsgcWSConnection
TsgcWSConnection is a wrapper of client WebSocket connections, you can access to this
object on Server or Client Events.
Methods
Disconnect: close client connection from server side. A "CloseCode" can be specified
optionally.
Properties
Data: user session data object, here you can pass a object and access this every time you
need, example: you can pass a connection to a database, user session properties...
71
sgcWebSockets 4.1.5
72
Components
Protocols
Protocols
With WebSockets you can implement Sub-protocols allowing to create customized
communications, for example: you can implement a sub-protocol over WebSocket protocol to
communicate a customized application using JSON messages, and you can implement another
sub-protocol using XML messages.
When a connection is open on Server side, it will validate if sub-protocol sent by client is
supported by server, if not, then it will close the connection. A server can implement several
sub-protocols, but only one can be used on a single connection.
Sub-protocols are very useful to create customized applications and be sure that all clients
support same communication interface.
Although protocol name is arbitrary, it's recommended to use unique names like
"dataset.esegece.com"
With sgcWebSockets package you can build your own protocols and you can use built-in sub-
protocols provided:
1. Protocol SGC: implemented using JSON-RPC 2.0 messages, provides following patterns:
RPC, PubSub, Transactional Messages, Messages Acknowledgment and more.
2. Protocol Dataset: inherits from Default Protocol, can send dataset changes (new record,
save record or delete record) from server to clients.
3. Protocol Files: implemented using binary messages, provides support for send files: packet
size, authorization, QoS, message acknowledgment and more.
4. Protocol WebRTC: open source project aiming to enable the web with Real Time
Communication (RTC) capabilities.
5. Protocol WAMP 1.0: open WebSocket subprotocol that provides two asynchronous
messaging patterns: RPC and PubSub.
6. Protocol WAMP 2.0: open WebSocket subprotocol that provides two asynchronous
messaging patterns: RPC and PubSub.
If you need to use more than one protocol using a single connection (example: you may
need to use default protocol to handle Remote Procedure Calls and Dataset protocol to
handle database connections) you can assign a "Broker" to each protocol component and all
messages will be exchanged using this intermediary protocol (you can check "Tickets Demo" to
get a simple example of this).
Protocols can be registered at runtime, just call Method RegisterProtocol and pass protocol
component as parameter.
Javascript Reference
73
sgcWebSockets 4.1.5
Here you can get more information about common javascript library used on sgcWebSockets.
74
Components
Protocols Javascript
Default Javascript sgcWebSockets uses sgcWebSocket.js file.
Here you can find available methods, you need to replace {%host%} and {%port%} variables as
needed, example: if you have configured your sgcWebSocket server to listen port 80 on
www.example.com website you need to configure your access to sgcWebSocket.js file as:
<script src="http://www.example.com:80/sgcWebSockets.js"></script>
Open Connection
<script src="http://{%host%}:{%port%}/sgcWebSockets.js"></script>
<script>
var socket = new sgcWebSocket('ws://{%host%}:{%port%}');
</script>
URL: websocket server location, you can use "ws:" for normal websocket
connections and "wss:" for secured websocket connections.
sgcWebSocket('ws://127.0.0.1')
sgcWebSocket('wss://127.0.0.1')
Protocol: if server accepts one or more protocol, you can define which is the
protocol you want to use.
sgcWebSocket('ws://127.0.0.1', 'esegece.com')
sgcWebSocket('ws://127.0.0.1')
<script src="http://{%host%}:{%port%}/sgcWebSockets.js"></script>
<script>
var socket = new
sgcWebSocket({"host":"ws://{%host%}:{%port%}","user":"admin","password
":"1234"});
75
sgcWebSockets 4.1.5
</script>
Send Message
<script src="http://{%host%}:{%port%}/sgcWebSockets.js"></script>
<script>
var socket = new sgcWebSocket('ws://{%host%}:{%port%}');
socket.send('Hello sgcWebSockets!');
</script>
<script src="http://{%host%}:{%port%}/sgcWebSockets.js"></script>
<script>
var socket = new sgcWebSocket('ws://{%host%}:{%port%}');
socket.on('message', function(event)
{
alert(event.message);
}
</script>
<script src="http://{%host%}:{%port%}/sgcWebSockets.js"></script>
<script>
var socket = new sgcWebSocket('ws://{%host%}:{%port%}');
socket.on('stream', function(event)
{
document.getElementById('image').src =
URL.createObjectURL(event.stream);
event.stream = "";
}
</script>
<script src="http://{%host%}:{%port%}/sgcWebSockets.js"></script>
<script>
var socket = new sgcWebSocket('ws://{%host%}:{%port%}');
socket.on('stream', function(event)
{
sgcWSStreamRead(evt.stream, function(header, stream) {
document.getElementById('text').innerHTML = header;
document.getElementById('image').src =
URL.createObjectURL(event.stream);
event.stream = "";
}
}
</script>
76
Components
<script src="http://{%host%}:{%port%}/sgcWebSockets.js"></script>
<script>
var socket = new sgcWebSocket('ws://{%host%}:{%port%}');
socket.on('open', function(event)
{
alert('sgcWebSocket Open!');
};
socket.on('close', function(event)
{
alert('sgcWebSocket Closed!');
};
socket.on('error', function(event)
{
alert('sgcWebSocket Error: ' + event.message);
};
</script>
Close Connection
<script src="http://{%host%}:{%port%}/sgcWebSockets.js"></script>
<script>
socket.close();
</script>
<script src="http://{%host%}:{%port%}/sgcWebSockets.js"></script>
<script>
socket.state();
</script>
77
sgcWebSockets 4.1.5
Subprotocols
78
Components
Default
Protocol Default
This is default sub-protocol implemented using "JSONRPC 2.0" messages, every time you send
a message using this protocol, a JSON object is created with following properties:
jsonrpc: A String specifying the version of the JSON-RPC protocol. MUST be exactly "2.0".
method: A String containing the name of the method to be invoked. Method names that begin
with the word rpc followed by a period character (U+002E or ASCII 46) are reserved for rpc-
internal methods and extensions and MUST NOT be used for anything else.
params: A Structured value that holds the parameter values to be used during the invocation of
the method. This member MAY be omitted.
id: An identifier established by the Client that MUST contain a String, Number, or NULL value if
included. If it is not included it is assumed to be a notification. The value SHOULD normally not
be Null [1] and Numbers SHOULD NOT contain fractional parts [2]
Features
Publish/subscribe message pattern to provide one-to-many
message distribution and decoupling of applications.
A messaging transport that is agnostic to the content of the payload
Acknowledgment of messages sent.
Supports transactional messages through server local transactions. When
the client commits the transaction, the server processes all messages
queued. If client rollback the transaction, then all messages are deleted.
Implements QoS (Quality of Service) for message delivery.
Components
TsgcWSPClient_sgc: Server Protocol Default VCL Component.
Browser Test
If you want to test this protocol with your favorite WebBrowser, please type this url (you need to
define your custom host and port)
http://host:port/esegece.com.html
79
sgcWebSockets 4.1.5
TsgcWSPServer_sgc
This is Server Protocol Default Component, you need to drop this component in the form and
select a TsgcWebSocketServer Component using Server Property.
Methods
Publish: sends a message to all subscribed clients.
RPCResult: if a call RPC from client is successful, server will respond with this method.
RPCError: if a call RPC from client it has an error, server will respond with this method.
Broadcast: sends a message to all connected clients, if you need to broadcast a message to
selected channels, use Channel argument.
Properties
RPCAuthentication: if enabled, every time a client requests a RPC, method name needs to
be authenticated against a username and password.
Methods: is a list of allowed methods. Every time a client sends a RPC first it will search if
this method is defined on this list, if it's not in this list, OnRPCAuthentication event will be fired.
Events
OnRPCAuthentication: if RPC Authentication is enabled, this event is fired to define if a
client can call this method or not.
80
Components
TsgcWSPClient_sgc
This is Client Protocol Default Component, you need to drop this component in the form and
select a TsgcWebSocketClient Component using Client Property.
Methods
Publish: sends a message to all subscribed clients.
RPC: Remote Procedure Call, client request a method and response will be handled
OnRPCResult or OnRPCError events.
Notify: client sends a notification to a server, this notification don't need a response.
Broadcast: sends a message to all connected clients, if you need to broadcast a message to
selected channels, use Channel argument.
GetSession: requests to server session id, data session is received OnSession Event.
Events
OnEvent: this event is fired every time a client receives a message from a custom channel.
OnRPCResult: this event is fired when client receives successful response from server after a
RPC is sent.
OnRPCError: this event is fired when client receives error response from server after a RPC is
sent.
OnAcknowledgment: this event is fired when client receives error an acknowledgment from
server that message has been received.
OnSession: this event is fired after a successful connection or after a GetSession request.
Properties
81
sgcWebSockets 4.1.5
Queue: disabled by default, if True all text/binary messages are not processed and queued
until queue is disabled.
Level 0: "At most once", the message is delivered according to the best efforts of the
underlying TCP/IP network. A response is not expected and no retry semantics are
defined in the protocol. The message arrives at the server either once or not at all.
Level 1: "At least once", the receipt of a message by the server is acknowledged by an
ACKNOWLEDGMENT message. If there is an identified failure of either the
communications link or the sending device, or the acknowledgement message is not
received after a specified period of time, the sender resends the message. The message
arrives at the server at least once. A message with QoS level 1 has an ID param in the
message.
Level 2: "Exactly once", where message are assured to arrive exactly once. This level
could be used, for example, with billing systems where duplicate or lost messages could
lead to incorrect charges being applied. If there is an identified failure of either the
communications link or the sending device, or the acknowledgement message is not
received after a specified period of time, the sender resends the message.
82
Components
TsgcIWWSPClient_sgc
This is Intraweb Client Protocol Default Component, you need to drop this component in the
form and select a TsgcIWWebSocketClient Component using Client Property.
Methods
WriteData: sends a message to a server. If you need to send a message to a custom
TsgcWSProtocol_Server_sgc, use "Guid" Argument. If you need to send a message to a single
channel, use "Channel" Argument.
83
sgcWebSockets 4.1.5
Here you can find available methods, you need to replace {%host%} and {%port%} variables as
needed, example: if you have configured your sgcWebSocket server to listen port 80 on
www.example.com website you need to configure:
<script src="http://www.example.com:80/sgcWebSockets.js"></script>
<script src="http://www.example.com:80/esegece.com.js"></script>
Open Connection
<script src="http://{%host%}:{%port%}/sgcWebSockets.js"></script>
<script src="http://{%host%}:{%port%}/esegece.com.js"></script>
<script>
var socket = new sgcws('ws://{%host%}:{%port%}');
</script>
Send Message
<script src="http://{%host%}:{%port%}/sgcWebSockets.js"></script>
<script src="http://{%host%}:{%port%}/esegece.com.js"></script>
<script>
var socket = new sgcws('ws://{%host%}:{%port%}');
socket.send('Hello sgcWebSockets!');
</script>
Call RPC
<script src="http://{%host%}:{%port%}/sgcWebSockets.js"></script>
<script src="http://{%host%}:{%port%}/esegece.com.js"></script>
<script>
84
Components
Call Notify
<script src="http://{%host%}:{%port%}/sgcWebSockets.js"></script>
<script src="http://{%host%}:{%port%}/esegece.com.js"></script>
<script>
var socket = new sgcws('ws://{%host%}:{%port%}');
var params = {param:10};
socket.notify('test', JSON.stringify(params));
</script>
socket.starttransaction('sgc:test');
socket.publish('Message1', 'sgc:test');
socket.publish('Message2', 'sgc:test');
socket.publish('Message3', 'sgc:test');
socket.commit('sgc:test');
</script>
85
sgcWebSockets 4.1.5
<script>
var socket = new sgcws('ws://{%host%}:{%port%}');
socket.on('open', function(event)
{
alert('sgcWebSocket Open!');
};
socket.on('close', function(event)
{
alert('sgcWebSocket Closed!');
};
socket.on('error', function(event)
{
alert('sgcWebSocket Error: ' + event.message);
};
</script>
Get Session
<script src="http://{%host%}:{%port%}/sgcWebSockets.js"></script>
<script src="http://{%host%}:{%port%}/esegece.com.js"></script>
<script>
var socket = new sgcws('ws://{%host%}:{%port%}');
socket.on('sgcsession', function(event)
{
alert(event.guid);
};
socket.getsession();
</script>
Close Connection
<script src="http://{%host%}:{%port%}/sgcWebSockets.js"></script>
<script src="http://{%host%}:{%port%}/esegece.com.js"></script>
<script>
socket.close();
</script>
socket.state();
</script>
Set QoS
<script src="http://{%host%}:{%port%}/sgcWebSockets.js"></script>
<script src="http://{%host%}:{%port%}/esegece.com.js"></script>
<script>
var socket = new sgcws('ws://{%host%}:{%port%}');
socket.qoslevel1();
socket.publish('message', 'channel');
</script>
86
Components
socket.queuelevel2();
socket.publish('message1', 'channel1');
socket.publish('message2', 'channel1');
</script>
87
sgcWebSockets 4.1.5
Dataset
Protocol Dataset
This protocol inherits from Protocol Default and it's useful if you want to broadcast dataset
changes over clients connected to this protocol.
It uses "JSON-RPC 2.0" Object, and every time there is a dataset change, it sends all field
values (* only fields supported) using Dataset Object.
To allow component to search records on dataset, you need to specify which fields are the Key,
example: if in your dataset, ID field is the key you will need to write a code like this
Components
TsgcWSPServer_Dataset: Server Protocol Dataset VCL Component.
Browser Test
If you want to test this protocol with your favorite WebBrowser, please type this url (you need to
define your custom host and port)
http://host:port/dataset.esegece.com.html
88
Components
TsgcWSPServer_Dataset
This is Server Protocol Dataset Component, you need to drop this component in the form and
select a TsgcWebSocketServer Component using Server Property and select a Dataset
Component using Dataset Property.
NotifyUpdates: if enabled, every time dataset server changes, server broadcasts this
change to all connected clients.
NotifyDeletes: if enabled, every time a record is deleted, server broadcasts this to all
connected clients.
AutoSynchronize: if enabled, every time a client connects to server, server will sent
metadata and all dataset records to client.
Methods
BroadcastRecord: sends dataset record values to all connected clients.
Events
These events are specific on dataset protocol.
89
sgcWebSockets 4.1.5
90
Components
TsgcWSPClient_Dataset
This is Client Protocol Dataset Component, you need to drop this component in the form and
select a TsgcWebSocketClient Component using Client Property and select a Dataset
Component using Dataset Property.
Methods
Subscribe_all: subscribe to all available channels
Events
These events are specific on dataset protocol.
procedure OnMetaData(Connection:
TsgcWSConnection; const JSON: TsgcObjectJSON);
var
i: integer;
vFieldName, vDataType: string;
vDataSize: Integer;
vKeyField: Boolean;
begin
for i:= 0 to JSON.Count -1 do
begin
vFieldName := JSON.Item[i].Node['fieldname'].Value;
91
sgcWebSockets 4.1.5
vDataType := JSON.Item[i].Node['datatype'].Value;
vDataSize := JSON.Item[i].Node['datasize'].Value;
vKeyField := JSON.Item[i].Node['keyfield'].Value;
end;
end;
Properties
AutoSubscribe: enabled by default, if True, client subscribes to all available channels after
successful connection.
ApplyUpdates: if enabled, every time client receives a dataset update from server, it will be
saved on client side.
NotifyUpdates: if enabled, every time dataset client changes, is sends a message to server
notifying this change.
92
Components
TsgcIWWSPClient_Dataset
This is Intraweb Client Protocol Dataset Component, you need to drop this component in the
form and select a TsgcIWWebSocketClient Component using Client Property and select a
Dataset Component using Dataset Property.
Methods
Subscribe_New: fired on new dataset record
Subscribe_Update: fired on post dataset record
Subscribe_Delete: fired on delete dataset record
93
sgcWebSockets 4.1.5
Here you can find available methods, you need to replace {%host%} and {%port%} variables as
needed, example: if you have configured your sgcWebSocket server to listen port 80 on
www.example.com website you need to configure:
<script src="http://www.example.com:80/sgcWebSockets.js"></script>
<script
src="http://www.example.com:80/dataset.esegece.com.js"></script>
Open Connection
<script src="http://{%host%}:{%port%}/sgcWebSockets.js"></script>
<script
src="http://{%host%}:{%port%}/dataset.esegece.com.js"></script>
<script>
var socket = new sgcws_dataset('ws://{%host%}:{%port%}');
</script>
Send Message
<script src="http://{%host%}:{%port%}/sgcWebSockets.js"></script>
<script
src="http://{%host%}:{%port%}/dataset.esegece.com.js"></script>
<script>
var socket = new sgcws_dataset('ws://{%host%}:{%port%}');
socket.send('Hello sgcWebSockets!');
</script>
94
Components
socket.on('sgcdataset', function(evt){
95
sgcWebSockets 4.1.5
}
else if (evt.channel == "sgc@dataset@delete") {
}
});
</script>
Close Connection
<script src="http://{%host%}:{%port%}/sgcWebSockets.js"></script>
<script
src="http://{%host%}:{%port%}/dataset.esegece.com.js"></script>
<script>
socket.close();
</script>
96
Components
Files
Protocol Files
This protocol allows to send files using binary websocket transport. It can handle big files with a
low memory usage.
Features
Publish/subscribe message pattern to provide one-to-many
message distribution and decoupling of applications.
Acknowledgment of messages sent.
Implements QoS (Quality of Service) for file delivery.
Optionally can request Authorization for files received.
Low memory usage.
Components
TsgcWSPServer_Files: Server Protocol Files VCL Component.
Classes
TsgcWSMessageFile: object which encapsulates file packet information.
97
sgcWebSockets 4.1.5
TsgcWSPServer_Files
This is Server Files Protocol Component, you need to drop this component in the form and
select a TsgcWebSocketServer Component using Server Property.
Methods
SendFile: sends a file to a client, you can set the following parameters
aSize: size of every packet in bytes.
aData: user custom data, here you can write any text you think is useful for client.
aChannel: if you only want to send data to all clients subscribed to this channel.
aQoS: type of quality of service.
BroadcastFile: sends a file to all connected clients. You can set several parameters:
aSize: size of every packet in bytes.
aData: user custom data, here you can write any text you think is useful for client.
aChannel: if you only want to send data to all clients subscribed to this channel.
aExclude: connection guids separated by comma, which you don't want to send this file.
aInclude: connection guids separated by comma, which you want to send this file.
aQoS: type of quality of service.
Properties
Files: files properties.
Events
OnFileBeforeSent: fired before a file is sent. You can use this event to check file data before
is sent.
98
Components
99
sgcWebSockets 4.1.5
TsgcWSPClient_Files
This is Server Files Protocol Component, you need to drop this component in the form and
select a TsgcWebSocketClient Component using Client Property.
Methods
SendFile: sends a file to server, you can set the following parameters
aSize: size of every packet in bytes.
aData: user custom data, here you can write any text you think is useful for server.
aQoS: type of quality of service.
Properties
Files: files properties
Events
OnFileBeforeSent: fired before a file is sent. You can use this event to check file data before
is sent.
100
Components
TsgcWSMessageFile
This object is passed as a parameter every time a file protocol event is raised.
Properties
BufferSize: default size of packet.
Channel: if specified, this file only will be sent to clients subscribed to specific
channel.
Method: internal method.
FileId: identifier of a file, is unique for all files received / sent.
Data: user custom data. Here user can set whatever text.
FileName: name of file.
FilePosition: file position in bytes.
FileSize: Total file size in bytes.
Id: identifier of a packet, is unique for every packet.
QoS: quality of service of message.
Streaming: for internal use.
Text: for internal use.
101
sgcWebSockets 4.1.5
WebRTC
Protocol WebRTC
WebRTC (Web Real-Time Communication) is an API definition being drafted by the World Wide
Web Consortium (W3C) to enable browser to browser applications for voice calling, video chat
and P2P file sharing without plugins.The RTC in WebRTC stands for Real-Time
Communications, technology that enables audio/video streaming and data sharing between
browser clients (peers). As a set of standards, WebRTC provides any browser with the ability to
share application data and perform teleconferencing peer to peer, without the need to install
plug-ins or third-party software.
WebRTC components are accessed with JavaScript APIs. Currently in development are the
Network Stream API, which represents an audio or video data stream, and the PeerConnection
API, which allows two or more users to communicate browser-to-browser. Also under
development is a DataChannel API that enables communication of other types of data for real-
time gaming, text chat, file transfer, and so forth.
Components
TsgcWSPServer_WebRTC: Server Protocol WebRTC VCL Component.
Browser Test
If you want to test this protocol with your favorite WebBrowser, please type this url (you need to
define your custom host and port)
http://host:port/webrtc.esegece.com.html
102
Components
TsgcWSPServer_WebRTC
This is Server Protocol WebRTC Component, you need to drop this component in the form and
select a TsgcWebSocketServer Component using Server Property.
103
sgcWebSockets 4.1.5
Here you can find available methods, you need to replace {%host%} and {%port%} variables as
needed, example: if you have configured your sgcWebSocket server to listen port 80 on
www.example.com website you need to configure:
<script src="http://www.example.com:80/sgcWebSockets.js"></script>
<script
src="http://www.example.com:80/webrtc.esegece.com.js"></script>
Open Connection
When a websocket connection is opened, browser request access to local camera
and microphone, you need to allow access.
<script src="http://{%host%}:{%port%}/sgcWebSockets.js"></script>
<script src="http://{%host%}:{%port%}/webrtc.esegece.com.js"></script>
<script>
var socket = new sgcws_webrtc('ws://{%host%}:{%port%}');
</script>
<script src="http://{%host%}:{%port%}/sgcWebSockets.js"></script>
<script src="http://{%host%}:{%port%}/webrtc.esegece.com.js"></script>
<script>
var socket = new sgcws_webrtc('ws://{%host%}:{%port%}');
socket.on('sgcmediastart', function(event)
{
socket.webrtc_connect('custom channel');
}
</script>
104
Components
WAMP
Protocol WAMP
WAMP is an open WebSocket subprotocol that provides two asynchronous messaging patterns:
RPC and PubSub.
What is RPC?
Remote Procedure Call (RPC) is a messaging pattern involving peers to two roles: client and
server.
A server provides methods or procedure to call under well known endpoints.
A client calls remote methods or procedures by providing the method or procedure endpoint and
any arguments for the call.
The server will execute the method or procedure using the supplied arguments to the call and
return the result of the call to the client.
What is PubSub?
Publish & Subscribe (PubSub) is a messaging pattern involving peers of three roles: publisher,
subscriber and broker.
A publisher sends (publishes) an event by providing a topic (aka channel) as the abstract
address, not a specific peer.
A subscriber receives events by first providing topics (aka channels) he is interested.
Subsequently, the subscriber will receive any events publishes to that topic.
The broker sits between publishers and subscribers and mediates messages publishes to
subscribers. A broker will maintain lists of subscribers per topic so it can dispatch new published
events to the appropriate subscribers.
A broker may also dispatch events on it's own, for example when the broker also acts as an
RPC server and a method executed on the server should trigger a PubSub event.
In summary, PubSub decouples publishers and receivers via an intermediary, the broker.
Components
TsgcWSPServer_WAMP: Server Protocol WAMP VCL Component.
Browser Test
If you want to test this protocol with your favorite WebBrowser, please type this url (you need to
define your custom host and port)
http://host:port/wamp.esegece.com.html
105
sgcWebSockets 4.1.5
TsgcWSPServer_WAMP
This is Server Protocol WAMP Component, you need to drop this component in the form and
select a TsgcWebSocketServer Component using Server Property.
Methods
CallResult: When the execution of the remote procedure finishes successfully, the server
responds by sending a message with result.
CallError: When the remote procedure call could not be executed, an error or exception
occurred during the execution or the execution of the remote procedure finishes unsuccessfully
for any other reason, the server responds by sending a message with error details.
Event: Subscribers receive PubSub events published by subscribers via the EVENT message.
Events
OnCall: event fired when server receives RPC called by client
OnPrefix: Procedures and Errors are identified using URIs or CURIEs, this event is fired when
a client sends a new prefix
106
Components
TsgcWSPClient_WAMP
This is Client Protocol WAMP Component, you need to drop this component in the form and
select a TsgcWebSocketClient Component using Client Property.
Methods
Prefix: Procedures and Errors are identified using URIs or CURIEs, client uses this method to
send a new prefix.
Subscribe: A client requests access to a valid topicURI (or CURIE from Prefix) to receive
events published to the given topicURI. The request is asynchronous, the server will not return
an acknowledgement of the subscription.
Publish: The client will send an event to all clients connected to the server who have
subscribed to the topicURI.
Events
OnWelcome: is the first server-to-client message sent by a WAMP server
OnCallError: event fired when the remote procedure call could not be executed, an error or
exception occurred during the execution or the execution of the remote procedure finishes
unsuccessfully for any other reason, the server responds by sending a message with error
details
107
sgcWebSockets 4.1.5
OnCallResult: event fired when the execution of the remote procedure finishes successfully,
the server responds by sending a message with result.
OnEvent: event fired when client receive PubSub events published by subscribers via the
EVENT message.
108
Components
Here you can find available methods, you need to replace {%host%} and {%port%} variables as
needed, example: if you have configured your sgcWebSocket server to listen port 80 on
www.example.com website you need to configure:
<script src="http://www.example.com:80/sgcWebSockets.js"></script>
<script src="http://www.example.com:80/wamp.esegece.com.js"></script>
Open Connection
<script src="http://{%host%}:{%port%}/sgcWebSockets.js"></script>
<script src="http://{%host%}:{%port%}/wamp.esegece.com.js"></script>
<script>
var socket = new sgcws_wamp('ws://{%host%}:{%port%}');
</script>
Subscribe to a TopicURI
<script src="http://{%host%}:{%port%}/sgcWebSockets.js"></script>
<script src="http://{%host%}:{%port%}/wamp.esegece.com.js"></script>
<script>
var socket = new sgcws_wamp('ws://{%host%}:{%port%}');
socket.subscribe('sgc:test)
</script>
UnSubscribe to a TopicURI
<script src="http://{%host%}:{%port%}/sgcWebSockets.js"></script>
<script src="http://{%host%}:{%port%}/wamp.esegece.com.js"></script>
<script>
var socket = new sgcws_wamp('ws://{%host%}:{%port%}');
socket.unsubscribe('sgc:test)
</script>
Publish message
<script src="http://{%host%}:{%port%}/sgcWebSockets.js"></script>
<script src="http://{%host%}:{%port%}/wamp.esegece.com.js"></script>
<script>
var socket = new sgcws_wamp('ws://{%host%}:{%port%}');
socket.publish('sgc:channel', 'Test Message', [], []);
</script>
109
sgcWebSockets 4.1.5
Close Connection
110
Components
<script src="http://{%host%}:{%port%}/sgcWebSockets.js"></script>
<script src="http://{%host%}:{%port%}/wamp.esegece.com.js"></script>
<script>
socket.close();
</script>
111
sgcWebSockets 4.1.5
WAMP 2.0
Protocol WAMP 2
WAMP provides Unified Application Routing in an open WebSocket protocol that works with
different languages.
Using WAMP you can build distributed systems out of application components which are loosely
coupled and communicate in (soft) real-time.
At its core, WAMP offers two communication patterns for application components to talk to each
other:
WAMP is easy to use, simple to implement and based on modern Web standards: WebSocket,
JSON and URIs.
Components
TsgcWSPClient_WAMP2: Client Protocol WAMP2 VCL Component.
112
Components
TsgcWSPClient_WAMP2
This is Client Protocol WAMP Component, you need to drop this component in the form and
select a TsgcWebSocketClient Component using Client Property.
Session Methods
ABORT: Both the Router and the Client may abort the opening of a WAMP
session by sending an ABORT message.
GOODBYE: A WAMP session starts its lifetime with the Router sending a
WELCOME message to the Client and ends when the underlying transport
disappears or when the WAMP session is closed explicitly by a GOODBYE
message sent by one Peer and a GOODBYE message sent from the other Peer
in response.
Publish/Subscribe Methods
PUBLISH: When a Publisher requests to publish an event to some
topic, it sends a PUBLISH message to a Broker:
If the Broker is able to fulfill and allowing the publication, the Broker
will send the event to all current Subscribers of the topic of the
published event.
By default, publications are unacknowledged, and the Broker will not
respond, whether the publication was successful indeed or not.
113
sgcWebSockets 4.1.5
RPC Methods
CALL: When a Caller wishes to call a remote procedure, it sends a
CALL message to a Dealer:
INVOCATION: If the Dealer is able to fulfill (mediate) the call and it allows the
call, it sends a INVOCATION message to the respective Callee implementing the
procedure:
114
Components
YIELD: If the Callee is able to successfully process and finish the execution of
the call, it answers by sending a YIELD message to the Dealer:
Events
OnWAMPSession: After the underlying transport has been established, the opening of a
WAMP session is initiated by the Client sending a HELLO message to the Router
OnWAMPAbort: Both the Router and the Client may abort the opening of a WAMP
session by sending an ABORT message.
OnWAMPGoodBye: A WAMP session starts its lifetime with the Router sending
a WELCOME message to the Client and ends when the underlying transport disappears or when
the WAMP session is closed explicitly by a GOODBYE message sent by one Peer and
a GOODBYE message sent from the other Peer in response.
115
sgcWebSockets 4.1.5
OnWAMPSubscribed: If the Broker is able to fulfill and allow the subscription, it answers by
sending a SUBSCRIBED message to the Subscriber
OnWAMPPublished: If the Broker is able to fulfill and allowing the publication, and
PUBLISH.Options.acknowledge == true, the Broker replies by sending a PUBLISHED message
to the Publisher:
OnWAMPResult: The Dealer will then send a RESULT message to the original Caller:
116
Components
OnWAMPRegistered: If the Dealer is able to fulfill and allowing the registration, it answers by
sending a REGISTERED message to the Callee:
117
sgcWebSockets 4.1.5
MQTT
Protocol MQTT
The protocol runs over TCP/IP, or over other network protocols that provide
ordered, lossless, bi-directional connections. Its features include:
Features
Publish/subscribe message pattern to provide one-to-many
message distribution and decoupling of applications.
Acknowledgment of messages sent.
Implements QoS (Quality of Service) for message delivery (all levels: At
most once, At least once and Exactly once)
Last Will Testament.
Secure connections.
HeartBeat and Watchdog.
Authentication to server.
Components
TsgcWSPClient_MQTT: MQTT Client Component.
118
Components
TsgcWSPClient_MQTT
This is Client Protocol MQTT Component, you need to drop this component in the form and
select a TsgcWebSocketClient Component using Client Property.
Methods
Connect: this method is called automatically after a successful websocket connection.
Ping: Sends a ping to server, usually to keep connection alive. If you enable HeartBeat
property, ping will be sent automatically by defined interval.
Publish: sends a message to all subscribed clients. There are the following parameters:
Topic: is the channel where the message will be published.
Text: is the text of message.
QoS: is the Quality Of Service of published message. There are 3 possibilities:
mtqsAtMostOnce: (by default) the message is delivered according to the best
efforts of the underlying TCP/IP network. A response is not expected and no retry
semantics are defined in the protocol. The message arrives at the server either
once or not at all.
mtqsAtLeastOnce: the receipt of a message by the server is acknowledged by
an ACKNOWLEDGMENT message. If there is an identified failure of either the
communications link or the sending device, or the acknowledgement message is
not received after a specified period of time, the sender resends the message.
The message arrives at the server at least once. A message with QoS level 1 has
an ID param in the message.
mtqsExactlyOnce: where message are assured to arrive exactly once. This level
could be used, for example, with billing systems where duplicate or lost messages
could lead to incorrect charges being applied. If there is an identified failure of
either the communications link or the sending device, or the acknowledgement
message is not received after a specified period of time, the sender resends the
message.
Retain: if True, Server MUST store the Application Message and its QoS, so that it can
be delivered to future subscribers whose subscriptions match its topic name. By default is
False.
Events
OnMQTTBeforeConnect: this event is fired before a new connection is established. There are
2 parameters:
CleanSession: if True (by default), server must discard any previous session and start a
new session. If false, server must resume communication.
ClientIdentifier: every new connection needs a client identifier, this is set automatically
by component, but can be modified if needed.
OnMQTTConnect: this event is fired when client is connected to MQTT server. There are 2
parameters:
Session: if True, server has created a new session. If false, session has resume a
previous session.
ReturnCode: returns a code with the result of connection.
OnQTTDisconnect: this event is fired when client is disconnected from MQTT server.
119
sgcWebSockets 4.1.5
OnMQTTPing: this event is fired when client receives an acknowledgment from a ping
previously sent.
OnMQTTPubAck: this event is fired when receives the response to a Publish Packet with QoS
level 1. There is one parameter:
PacketIdentifier: is packet identifier sent initially.
OnMQTTPubComp: this event is fired when receives the response to a PubRel Packet. It is
the fourth and final packet of the QoS 2 protocol exchange. There is one parameter:
PacketIdentifier: is packet identifier sent initially.
OnMQTTPublish: this event is fired when client receives a message from server. There are 2
parameters:
Topic: is the topic name of published message.
Text: is the text of published message.
OnMQTTPubRec: this event is fired when receives the response to a Publish Packet with QoS
2. It is the second packet of the QoS 2 protocol exchange. There is one parameter:
PacketIdentifier: is packet identifier sent initially.
Properties
Authentication: disabled by default, if True an UserName and Password are sent to server to
try user authentication.
HeartBeat: eanbled by default, if True, send a ping every X seconds (set by Interval property)
to keep alive connection.
120
Components
APIs
WebSocket APIs
There are several implementations based on WebSockets: finance, message publishing,
queues... sgcWebSockets implements the most important APIs based on WebSocket protocol.
In order to use an API, just attach API component to client and all messages will be handled by
API component (only one API component can be attached to a client).
List of APIs:
2. Bitfinex: Bitfinex is one of the world's largest and most advanced cryptocurrency trading
platform. Users can exchange Bitcoin, Ethereum, Ripple, EOS, Bitcoin Cash, Iota, NEO,
Litecoin, Ethereum Classic...
3. Pusher: Pusher is an easy and realiable platform with flexible pub/sub messaging, live user
lists, authentication...
APIs can be registered at runtime, just call Method RegisterAPI and pass API component as
parameter.
121
sgcWebSockets 4.1.5
API
API Blockchain
Blockchain
Blockchain WebSocket API allows developers to receive Real-Time notifications about new
transactions and blocks.
{
"op": "utx",
"x": {
"lock_time": 0,
"ver": 1,
"size": 192,
"inputs": [
{
"sequence": 4294967295,
"prev_out": {
"spent": true,
"tx_index": 99005468,
"type": 0,
"addr": "1BwGf3z7n2fHk6NoVJNkV32qwyAYsMhkWf",
"value": 65574000,
"n": 0,
"script":
"76a91477f4c9ee75e449a74c21a4decfb50519cbc245b388ac"
},
"script":
"483045022100e4ff962c292705f051c2c2fc519fa775a4d8955bce1a3e29884b27852
77999ed02200b537ebd22a9f25fbbbcc9113c69c1389400703ef2017d80959ef0f1d68
5756c012102618e08e0c8fd4c5fe539184a30fe35a2f5fccf7ad62054cad29360d871f
8187d"
}
],
"time": 1440086763,
"tx_index": 99006637,
"vin_sz": 1,
"hash":
"0857b9de1884eec314ecf67c040a2657b8e083e1f95e31d0b5ba3d328841fc7f",
"vout_sz": 1,
"relayed_by": "127.0.0.1",
"out": [
{
"spent": false,
122
Components
"tx_index": 99006637,
"type": 0,
"addr": "1A828tTnkVFJfSvLCqF42ohZ51ksS3jJgX",
"value": 65564000,
"n": 0,
"script":
"76a914640cfdf7b79d94d1c980133e3587bd6053f091f388ac"
}
]
}
}
{
"op": "block",
"x": {
"txIndexes": [
3187871,
3187868
],
"nTx": 0,
"totalBTCSent": 0,
"estimatedBTCSent": 0,
"reward": 0,
"size": 0,
"blockIndex": 190460,
"prevBlockIndex": 190457,
"height": 170359,
"hash":
"00000000000006436073c07dfa188a8fa54fefadf571fd774863cda1b884b90f",
"mrklRoot":
"94e51495e0e8a0c3b78dac1220b2f35ceda8799b0a20cfa68601ed28126cfcc2",
"version": 1,
"time": 1331301261,
"bits": 436942092,
"nonce": 758889471
}
}
123
sgcWebSockets 4.1.5
API Bitfinex
Bitfinex
Bitfinex is one of the world's largest and most advanced cryptocurrency trading platform. Users
can exchange Bitcoin, Ethereum, Ripple, EOS, Bitcoin Cash, Iota, NEO, Litecoin, Ethereum
Classic...
Each message sent and received via the Bitfinex's websocket channel is encoded in JSON
format
Trading pairs symbols are formed prepending a "t" before the pair (i.e
tBTCUSD, tETHUSD).
Margin currencies symbols are formed prepending a "f" before the currency (i.e
fUSD, fBTC, ...)
After a successful connection, OnBitfinexConnect event is raised and you get Bitfinex API
Version number as parameter.
If server sends any information, this can be handle using OnBitfinexInfoMessage event, where
a Code and a Message are parameters with information about message sent by server.
Example codes:
In case of error, OnBitfinexError will be raised, and information about error provided. Example
error codes:
In order to change the configuration, call Configuration method and pass as a parameter one
of the following flags:
There are channels which are public and there is no need to authenticate against server. All
messages are raised OnBitfinexUpdate event.
SubscribeTicker
124
Components
The ticker is a high level overview of the state of the market. It shows you the current best bid
and ask, as well as the last trade price. It also includes information such as daily volume and
how much the price has moved over the last day.
// Trading pairs
[
CHANNEL_ID,
[
BID,
BID_SIZE,
ASK,
ASK_SIZE,
DAILY_CHANGE,
DAILY_CHANGE_PERC,
LAST_PRICE,
VOLUME,
HIGH,
LOW
]
]
// Funding pairs
[
CHANNEL_ID,
[
FRR,
BID,
BID_PERIOD,
BID_SIZE,
ASK,
ASK_PERIOD,
ASK_SIZE,
DAILY_CHANGE,
DAILY_CHANGE_PERC,
LAST_PRICE,
VOLUME,
HIGH,
LOW
]
]
SubscribeTrades
This channel sends a trade message whenever a trade occurs at Bitfinex. It includes all the
pertinent details of the trade, such as price, size and time.
125
sgcWebSockets 4.1.5
SubscribeOrderBook
The Order Books channel allow you to keep track of the state of the Bitfinex order book. It is
provided on a price aggregated basis, with customizable precision. After receiving the response,
you will receive a snapshot of the book, followed by updates upon any changes to the book.
SubscribeRawOrderBook
126
Components
PRICE,
AMOUNT
],
...
]
]
SubscribeCandles
[
CHANNEL_ID,
[
[
MTS,
OPEN,
CLOSE,
HIGH,
LOW,
VOLUME
],
...
]
]
127
sgcWebSockets 4.1.5
This channel allows you to keep up to date with the status of your account. You can receive
updates on your positions, your balances, your orders and your trades.
Use Authenticate method in order to Authenticate against server and set required parameters.
Once authenticated, you will receive updates of: Orders, positions, trades, funding offers,
funding credits, funding loans, wallets, balance info, margin info, funding info, funding trades...
You can request UnAuthenticate method if you want log off from server.
128
Components
API Pusher
Pusher
Pusher it's an easy and reliable platform with nice features based on websocket protocol:
flexible pub/sub messaging, live user lists (presence), authentication...
Data is sent bidirectionally over a WebSocket as text data containing UTF8 encoded JSON
(Binary WebSocket frames are not supported).
You can call Ping method to test connection to server. Essentially any messages received from
the other party are considered to mean that the connection is alive. In the absence of any
messages either party may check that the other side is responding by sending a ping message,
to which the other party should respond with a pong.
After a successful connection, OnPusherConnect event is raised and you get following fields:
In case of error, OnPusherError will be raised, and information about error provided. An error
may be sent from Pusher in response to invalid authentication, an invalid command, etc.
4000-4099
Indicates an error resulting in the connection being closed by Pusher, and that attempting
to reconnect using the same parameters will not succeed.
4100-4199
Indicates an error resulting in the connection being closed by Pusher, and that the client
may reconnect after 1s or more.
4200-4299
129
sgcWebSockets 4.1.5
Indicates an error resulting in the connection being closed by Pusher, and that the client
may reconnect immediately.
4300-4399
Channels
Channels are a fundamental concept in Pusher. Each application has a number of channels,
and each client can choose which channels it subscribes to.
Channels provide:
It's strongly recommended that channels are used to filter your data and that it is not achieved
using events. This is because all events published to a channel are sent to all subscribers,
regardless of their event binding.
Channels don’t need to be explicitly created, and are instantiated on client demand. This means
that creating a channel is easy. Just tell a client to subscribe to it.
Public Channels
Public channels should be used for publicly accessible data as they do not require any form
authorisation in order to be subscribed to.
You can subscribe and unsubscribe from channels at any time. There’s no need to wait for the
Pusher to finish connecting first.
APIPusher.Subscribe('my-channel');
If you are subscribed successfully OnPusherSubscribe event will be raised, if there is an error
you will get a message in OnPusherError event.
130
Components
Private Channels
Requires Indy 10.5.7 or later
Private channels should be used when access to the channel needs to be restricted in some
way. In order for a user to subscribe to a private channel permission must be authorised.
APIPusher.Subscribe('my-private-channel', pscPrivateChannel);
If you are subscribed successfully OnPusherSubscribe event will be raised, if there is an error
you will get a message in OnPusherError event.
Presence Channels
Requires Indy 10.5.7 or later
Presence channels build on the security of Private channels and expose the additional feature
of an awareness of who is subscribed to that channel. This makes it extremely easy to build
chat room and “who’s online” type functionality to your application. Think chat rooms,
collaborators on a document, people viewing the same web page, competitors in a game, that
kind of thing.
Presence channels are subscribed to from the client API in the same way as private channels
but the channel name must be prefixed with presence-. As with private channels a HTTP
Request is made to a configurable authentication URL to determine if the current user has
permissions to access the channel.
Information on users subscribing to, and unsubscribing from a channel can then be accessed by
binding to events on the presence channel and the current state of users subscribed to the
channel is available via the channel.members property.
APIPusher.Subscribe('my-presence-channel', pscPresenceChannel,
'{"user_id":"John_Smith","user_info":{"name":"John Smith"}}');
If you are subscribed successfully OnPusherSubscribe event will be raised, if there is an error
you will get a message in OnPusherError event.
Publish Messages
Not only you can receive messages from subscribed channels, you can send messages to other
subscribed users.
Call method Publish to send a message to all subscribed users of channel.
APIPusher.Publish('my-event', 'my-channel');
131
sgcWebSockets 4.1.5
Publish no more than 10 messages per second per client (connection). Any events triggered
above this rate limit will be rejected by Pusher API. This is not a system issue, it is a client
issue. 100 clients in a channel sending messages at this rate would each also have to be
processing 1,000 messages per second! Whilst some modern browsers might be able to handle
this it’s most probably not a good idea.
132
Components
Extensions
Extensions
WebSocket protocol is designed to be extended. WebSocket Clients may request extensions
and WebSocket Servers may accept some or all extensions requested by clients.
Extensions supported:
133
sgcWebSockets 4.1.5
Extensions | PerMessage-Deflate
PerMessage is a WebSocket protocol extension, if the extension is supported by Server and
Client, both can compress transmitted messages:
This extension allows to customize Server and Client size of sliding window used by LZ77
algorithm (between 8 - 15). As greater is this value, more probably will find and eliminate
duplicates but consumes more memory and cpu cycles. 15 is default value.
By default, previous messages are used to compression and decompression, if messages are
similar, this improves the compression ratio. If Enabled, then each message is compressed
using only its message data. By default is disabled.
MemLevel
This value is not negotiated between Server and Client. when set to 1, it uses the least memory,
but slows down the compression algorithm and reduces the compression ratio; when set to 9, it
uses the most memory and delivers the best performance. By default is set to 1.
* Indy version provided with Rad Studio XE2 raises an exception because zlib version mismatch
with initialization functions, to fix this, just update your Indy version to latest.
134
Components
Extensions | Deflate-Frame
Is a WebSocket protocol extension which allows the compression of frames sent using
WebSocket protocol, supported by webkit browsers like chrome or safari. This extension is
supported on Server and Client Components.
* Indy version provided with Rad Studio XE2 raises an exception because zlib version mismatch
with initialization functions, to fix this, just update your Indy version to latest.
135
Library
Library
DLL
The sgcWebSockets.dll will need to be on any machine that your program will run on. It needs
to be in the path. Typically, you would install it in the same directory as your executable, or in
the C:\Windows\System32 or C:\Windows\SysWOW64 directory.
Delphi
Include the files sgcWebSocketLib.pas, sgcWebSocketLib_Types.pas and
sgcWebSocketLib_Const.pas in your project. These files are Pascal import units which defines
all of the sgcWebSocket methods and events defined.
Example of use: open a new websocket client connection to host '127.0.0.1' and port 8080.
sgcWebSocketLib.Instance.Client_Initialize('127.0.0.1', 8080);
sgcWebSocketLib.Instance.Client_Start;
QuickStart
C# (C Sharp .NET)
Include the file sgcWebSocketLib.cs in your project. That file defines all of the sgcWebSocket
methods and events defined.
Example of use: open a new websocket client connection to host '127.0.0.1' and port 8080.
sgcWebSocketLib.Instance.Client_Initialize("127.0.0.1", 8080);
sgcWebSocketLib.Instance.Client_Start();
QuickStart
137
sgcWebSockets 4.1.5
Library | Build
138
Library
QuickStart
QuickStart | Library | Delphi
Let's start with a basic example where we need to create a Client WebSocket.
sgcWebSocketLib.Instance.Client_OnConnect(WSClientConnect);
sgcWebSocketLib.Instance.Client_OnDisconnect(WSClientDisconnect);
sgcWebSocketLib.Instance.Client_OnError(WSClientError);
sgcWebSocketLib.Instance.Client_OnMessage(WSClientMessage);
sgcWebSocketLib.Instance.Client_Initialize('127.0.0.1', 80);
sgcWebSocketLib.Instance.Client_Start;
sgcWebSocketLib.Instance.Client_WriteData('Hello World');
sgcWebSocketLib.Instance.Client_Stop;
139
sgcWebSockets 4.1.5
QuickStart | Library | C#
Let's start with a basic example where we need to create a Client WebSocket.
sgcWebSocketLib.Instance.Client_OnConnect(OnConnectEvent);
sgcWebSocketLib.Instance.Client_OnDisconnect(OnDisconnectEvent);
sgcWebSocketLib.Instance.Client_OnError(OnError);
sgcWebSocketLib.Instance.Client_OnMessage(OnMessageEvent);
sgcWebSocketLib.Instance.Client_Initialize('127.0.0.1', 80);
sgcWebSocketLib.Instance.Client_Start();
sgcWebSocketLib.Instance.Client_WriteData('Hello World');
sgcWebSocketLib.Instance.Client_Stop();
140
Library
Client
Library | Client
Create WebSocket Clients to connect to WebSocket Servers. Library client is based on VCL
WebSocket Client, more info.
Methods
Creates a new websocket client. aID parameter is used if you want to create multiple
instances of a client.
This method needs to be called before a new connection is started. You can define which
is the Server Host and Port where you want to connect.
Client_Finalize
Events
Client_OnConnect(aOnConnect: TsgcWSClient_OnConnect;
141
sgcWebSockets 4.1.5
Client_OnDisconnect(aOnDisconnect: TsgcWSClient_OnDisconnect;
aID: WideString = '')
Client_OnMessage(aOnMessage: TsgcWSClient_OnMessage;
aID: WideString = '')
Event raised when client receives a new text message from server.
Client_OnBinary(aOnBinary: TsgcWSClient_OnBinary;
aID: WideString = '')
Event raised when client receives a new Binary message from server.
Types
142
Library
Create SocketIO clients to connect to SocketIO WebSocket Servers. Library client is based on
VCL WebSocket SocketIO Client, more info.
Methods
Creates a new websocket client. aID parameter is used if you want to create multiple
instances of a client.
This method needs to be called before a new connection is started. You can define which
is the Server Host and Port where you want to connect.
Client_SocketIO_Finalize
Only used for multiple sockets. Signals a connection to the endpoint. Once the server
receives it, it's echoed back to the client.
143
sgcWebSockets 4.1.5
Sends a heartbeat. Heartbeats must be sent within the interval negotiated with the
server. It's up to the client to decide the padding (for example, if the heartbeat timeout
negotiated with the server is 20s, the client might want to send a heartbeat evert 15s).
An event is like a json message, but has mandatory name and args fields. name is a
string and args an array.
The event names: 'message', 'connect', 'disconnect', 'open', 'close', 'error', 'retry',
'reconnect' are reserved, and cannot be used by clients or servers with this message
type.
No operation. Used for example to close a poll after the polling duration times out.
Events
Client_SocketIO_OnConnect(aOnConnect: TsgcWSClient_OnConnect;
aID: WideString = '')
Client_SocketIO_OnDisconnect(aOnDisconnect: TsgcWSClient_OnDisconnect;
aID: WideString = '')
Client_SocketIO_OnMessage(aOnMessage: TsgcWSClient_OnMessage;
aID: WideString = '')
Event raised when client receives a new text message from server.
144
Library
Client_SocketIO_OnBinary(aOnBinary: TsgcWSClient_OnBinary;
aID: WideString = '')
Event raised when client receives a new Binary message from server.
Client_SocketIO_OnMessageDisconnect(aOnMessageDisconnect:
TsgcWSClient_SocketIO_OnMessageDisconnect; aID: WideString = '')
Client_SocketIO_OnMessageConnect(aOnMessageConnect:
TsgcWSClient_SocketIO_OnMessageConnect; aID: WideString = '')
Client_SocketIO_OnMessageHeartBeat(aOnMessageHeartBeat:
TsgcWSClient_SocketIO_OnMessageHeartBeat; aID: WideString = '')
Client_SocketIO_OnMessageEvent(aOnMessageEvent:
TsgcWSClient_SocketIO_OnMessageEvent; aID: WideString = '')
Client_SocketIO_OnMessageText(aOnMessageText:
TsgcWSClient_SocketIO_OnMessageText; aID: WideString = '')
Client_SocketIO_OnMessageJSON(aOnMessageJSON:
TsgcWSClient_SocketIO_OnMessageJSON; aID: WideString = '')
Client_SocketIO_OnMessageACK(aOnMessageACK:
TsgcWSClient_SocketIO_OnMessageACK; aID: WideString = '')
Client_SocketIO_OnMessageError(aOnMessageError:
TsgcWSClient_SocketIO_OnMessageError; aID: WideString = '')
Client_SocketIO_OnMessageNoop(aOnMessageNoop:
TsgcWSClient_SocketIO_OnMessageNoop; aID: WideString = '')
145
sgcWebSockets 4.1.5
Types
146
Library
Create WebSocket Clients to connect to WebSocket Servers. Library client is based on VCL
WebSocket Client using protocol SGC, more info.
Methods
Creates a new websocket client. aID parameter is used if you want to create multiple
instances of a client.
This method needs to be called before a new connection is started. You can define which
is the Server Host and Port where you want to connect.
Client_Finalize
147
sgcWebSockets 4.1.5
Events
Client_sgc_OnConnect(aOnConnect: TsgcWSClient_OnConnect;
aID: WideString = '')
Client_sgc_OnDisconnect(aOnDisconnect: TsgcWSClient_OnDisconnect;
aID: WideString = '')
Client_sgc_OnMessage(aOnMessage: TsgcWSClient_OnMessage;
aID: WideString = '')
Event raised when client receives a new text message from server.
Client_sgc_OnBinary(aOnBinary: TsgcWSClient_OnBinary;
aID: WideString = '')
Event raised when client receives a new Binary message from server.
148
Library
Client_sgc_OnSubscription(aOnSubscription:
TsgcWSP_sgc_OnSubscription; aID: WideString = '')
Client_sgc_OnUnSubscription(aOnUnSubscription:
TsgcWSP_sgc_OnUnSubscription; aID: WideString = '')
Client_sgc_OnAcknowledgment(aOnAcknowledgment :
TsgcWSPClient_sgc_OnAcknowledgment; aID: WideString
= '')
Event raised when client receives an Acknowledgment from server that message has
been received.
Server_sgc_OnRPCResult(aOnRPCResult : TsgcWSPClient_sgc_OnRPCResult;
aID: WideString = '')
Event raised when server sends a response to client after a Remote Procedure Call.
Types
149
sgcWebSockets 4.1.5
Server
Library | Server
Create WebSocket Servers. Library server is based on VCL WebSocket Server, more info.
Methods
Creates a new websocket server. aID parameter is used if you want to create multiple
instances of a server.
This method needs to be called before a new connection is started. You can define which
is the Port to listen client connections.
Server_Finalize
Starts a server.
Stops a server.
Events
150
Library
Server_OnConnect(aOnConnect: TsgcWSServer_OnConnect;
aID: WideString = '')
Server_OnDisconnect(aOnDisconnect: TsgcWSServer_OnDisconnect;
aID: WideString = '')
Server_OnMessage(aOnMessage: TsgcWSServer_OnMessage;
aID: WideString = '')
Event raised when server receives a new text message from client.
Server_OnBinary(aOnBinary: TsgcWSServer_OnBinary;
aID: WideString = '')
Event raised when server receives a new Binary message from client.
Server_OnAuthentication(aOnAuthentication
: TsgcWSServer_OnAuthentication; aID: WideString = '')
Types
151
sgcWebSockets 4.1.5
Create WebSocket Servers. Library server is based on VCL WebSocket Server using SGC
Protocol, more info.
Methods
Creates a new websocket server. aID parameter is used if you want to create multiple
instances of a server.
This method needs to be called before a new connection is started. You can define which
is the Port to listen client connections.
Server_Finalize
Starts a server.
Stops a server.
152
Library
Events
Server_sgc_OnConnect(aOnConnect: TsgcWSServer_OnConnect;
aID: WideString = '')
Server_sgc_OnDisconnect(aOnDisconnect: TsgcWSServer_OnDisconnect;
aID: WideString = '')
Server_sgc_OnMessage(aOnMessage: TsgcWSServer_OnMessage;
aID: WideString = '')
Event raised when server receives a new text message from client.
Server_sgc_OnBinary(aOnBinary: TsgcWSServer_OnBinary;
aID: WideString = '')
Event raised when server receives a new Binary message from client.
Server_sgc_OnSubscription
(aOnSubscription: TsgcWSP_sgc_OnSubscription; aID: WideString = '')
Server_sgc_OnUnSubscription
(aOnUnSubscription: TsgcWSP_sgc_OnUnSubscription; aID: WideString = '')
Server_sgc_OnNotification(aOnNotification
: TsgcWSPServer_sgc_OnNotification; aID: WideString = '')
Server_sgc_OnRPC(aOnRPC: TsgcWSPServer_sgc_OnRPC;
aID: WideString = '')
Event raised when server receives a Remote Procedure Call from a client.
Server_sgc_OnRPCAuthentication(aOnRPCAuthentication
: TsgcWSPServer_sgc_OnRPCAuthentication; aID: WideString = '')
153
sgcWebSockets 4.1.5
Types
154
Reference
WebSockets
WebSocket is a web technology providing for bi-directional, full-duplex communications
channels, over a single Transmission Control Protocol (TCP) socket.
The WebSocket API is being standardized by the W3C, and the WebSocket protocol has been
standardized by the IETF as RFC 6455.
WebSocket is designed to be implemented in web browsers and web servers, but it can be
used by any client or server application. The WebSocket protocol makes possible more
interaction between a browser and a web site, facilitating live content and the creation of real-
time games. This is made possible by providing a standardized way for the server to send
content to the browser without being solicited by the client, and allowing for messages to be
passed back and forth while keeping the connection open. In this way a two-way (bi-direction)
ongoing conversation can take place between a browser and the server. A similar effect has
been done in non-standardized ways using stop-gap technologies such as comet.
In addition, the communications are done over the regular TCP port number 80, which is of
benefit for those environments which block non-standard Internet connections using a firewall.
WebSocket protocol is currently supported in several browsers including Firefox, Google
Chrome, Internet Explorer and Safari. WebSocket also requires web applications on the server
to be able to support it.
More Information
Browser Support
155
sgcWebSockets 4.1.5
JSON
JSON or JavaScript Object Notation, is a text-based open standard designed for human-
readable data interchange. It is derived from the JavaScript scripting language for representing
simple data structures and associative arrays, called objects. Despite its relationship to
JavaScript, it is language-independent, with parsers available for many languages.
The JSON format is often used for serializing and transmitting structured data over a network
connection. It is used primarily to transmit data between a server and web application, serving
as an alternative to XML.
More Information
156
Reference
JSON-RPC 2.0
JSON-RPC is a stateless, light-weight remote procedure call (RPC) protocol. Primarily this
specification defines several data structures and the rules around their processing. It is
transport agnostic in that the concepts can be used within the same process, over sockets, over
http, or in many various message passing environments. It uses JSON (RFC 4627) as data
format.
Example: client call method subtract with 2 params (42 and 23). Server sends a result of 19.
Client To Server --> {"jsonrpc": "2.0", "method": "subtract", "params": [42, 23],
"id": 1}
Parsers
sgcWebSockets provides a built-in JSON component, but you can use your own JSON parser.
Just implement following interfaces located at sgcJSON.pas:
IsgcJSON
IsgcObjectJSON
To use your own JSON parser or use some of the JSON parsers provided, just call
SetJSONClass in your initialization method. For example: if you want use XSuperObject JSON
parser, just call:
SetJSONClass(TsgcXSOJSON)
More information
157
sgcWebSockets 4.1.5
WAMP
The WebSocket Application Messaging Protocol (WAMP) is an open WebSocket subprotocol
that provides two asynchronous messaging patterns: RPC and PubSub.
The WebSocket Protocol is already built into modern browsers and provides bidirectional, low-
latency message-based communication. However, as such, WebSocket it is quite low-level and
only provides raw messaging.
Modern Web applications often have a need for higher level messaging patterns such as
Publish & Subscribe and Remote Procedure Calls.
This is where The WebSocket Application Messaging Protocol (WAMP) enters. WAMP adds the
higher level messaging patterns of RPC and PubSub to WebSocket - within one protocol.
More Information
158
Reference
WebRTC
WebRTC is a free, open project that enables web browsers with Real-Time Communications
(RTC) capabilities via simple Javascript APIs. The WebRTC components have been optimized
to best serve this purpose. The WebRTC initiative is a project supported by Google, Mozilla and
Opera.
WebRTC offers web application developers the ability to write rich, realtime multimedia
applications (think video chat) on the web, without requiring plugins, downloads or installs. It's
purpose is to help build a strong RTC platform that works across multiple web browsers, across
multiple platforms.
More Information
159
sgcWebSockets 4.1.5
MQTT
MQTT (MQ Telemetry Transport or Message Queue Telemetry Transport) is an ISO standard
(ISO/IEC PRF 20922) publish-subscribe-based "lightweight" messaging protocol for use on top
of the TCP/IP protocol. It is designed for connections with remote locations where a "small code
footprint" is required or the network bandwidth is limited. The publish-subscribe messaging
pattern requires a message broker. The broker is responsible for distributing messages to
interested clients based on the topic of a message. Andy Stanford-Clark and Arlen Nipper of
Cirrus Link Solutions authored the first version of the protocol in 1999.
The specification does not specify the meaning of "small code footprint" or the meaning of
"limited network bandwidth". Thus, the protocol's availability for use depends on the context. In
2013, IBM submitted MQTT v3.1 to the OASIS specification body with a charter that ensured
only minor changes to the specification could be accepted.MQTT-SN is a variation of the main
protocol aimed at embedded devices on non-TCP/IP networks, such as ZigBee.
Historically, the "MQ" in "MQTT" came from IBM's MQ Series message queuing product line.
However, queuing itself is not required to be supported as a standard feature in all situations.
Specification
More Info
160
Reference
Server-Sent Events
Server-sent events (SSE) is a technology for where a browser gets automatic updates from a
server via HTTP connection. The Server-Sent Events EventSource API is standardized as part
of HTML5 by the W3C.
A server-sent event is when a web page automatically gets updates from a server. This was
also possible before, but the web page would have to ask if any updates were available. With
server-sent events, the updates come automatically.
Examples: Facebook/Twitter updates, stock price updates, news feeds, sport results, etc.
More information
Browser Support
161
License
License
eSeGeCe Components End-User License Agreement
eSeGeCe Components ("eSeGeCe") End-User License Agreement ("EULA") is a legal
agreement between you (either an individual or a single entity) and the Author of eSeGeCe for
all the eSeGeCe components which may include associated software components, media,
printed materials, and "online" or electronic documentation ("eSeGeCe components"). By
installing, copying, or otherwise using the eSeGeCe components, you agree to be bound by the
terms of this EULA. This license agreement represents the entire agreement concerning the
program between you and the Author of eSeGeCe, (referred to as "LICENSER"), and it
supersedes any prior proposal, representation, or understanding between the parties. If you do
not agree to the terms of this EULA, do not install or use the eSeGeCe components.
The eSeGeCe components is protected by copyright laws and international copyright treaties,
as well as other intellectual property laws and treaties. The eSeGeCe components is licensed,
not sold.
The eSeGeCe components is a freeware. You may evaluate it for free and You can use the
eSeGeCe components for commercial purpose. If you want SOURCE CODE you need to pay
the registration fee. You must NOT give the license keys and/or the full editions of eSeGeCe
(including the DCU editions and Source editions) to any third individuals and/or entities. And
you also must NOT use the license keys and/or the full editions of eSeGeCe from any third
individuals' and/or entities'.
1. GRANT OF LICENSE
The eSeGeCe components is licensed as follows:
(a) Installation and Use.
LICENSER grants you the right to install and use copies of the eSeGeCe components on your
computer running a validly licensed copy of the operating system for which the eSeGeCe
components was designed [e.g., Windows 95, Windows NT, Windows 98, Windows 2000,
Windows 2003, Windows XP, Windows ME, Windows Vista, Windows 7, Windows 10].
(b) Royalty Free.
You may create commercial applications based on the eSeGeCe components and distribute
them with your executables, no royalties required.
(c) Modifications (Source editions only).
You may make modifications, enhancements, derivative works and/or extensions to the
licensed SOURCE CODE provided to you under the terms set forth in this license agreement.
(d) Backup Copies.
You may also make copies of the eSeGeCe components as may be necessary for backup and
archival purposes.
2. DESCRIPTION OF OTHER RIGHTS AND LIMITATIONS
(a) Maintenance of Copyright Notices.
You must not remove or alter any copyright notices on any and all copies of the eSeGeCe
components.
(b) Distribution.
You may not distribute registered copies of the eSeGeCe components to third parties.
Evaluation editions available for download from the eSeGeCe official websites may be freely
distributed.
You may create components/ActiveX controls/libraries which include the eSeGeCe components
for your applications but you must NOT distribute or publish them to third parties.
(c) Prohibition on Distribution of SOURCE CODE (Source editions only).
You must NOT distribute or publish the SOURCE CODE, or any modification, enhancement,
derivative works and/or extensions, in SOURCE CODE form to third parties.
You must NOT make any part of the SOURCE CODE be distributed, published, disclosed or
otherwise made available to third parties.
(d) Prohibition on Reverse Engineering, Decompilation, and Disassembly.
163
sgcWebSockets 4.1.5
You may not reverse engineer, decompile, or disassemble the eSeGeCe components, except
and only to the extent that such activity is expressly permitted by applicable law notwithstanding
this limitation.
(e) Rental.
You may not rent, lease, or lend the eSeGeCe components.
(f) Support Services.
LICENSER may provide you with support services related to the eSeGeCe components
("Support Services"). Any supplemental software code provided to you as part of the Support
Services shall be considered part of the eSeGeCe components and subject to the terms and
conditions of this EULA.
eSeGeCe is licensed to be used by only one developer at a time. And the technical support will
be provided to only one certain developer.
(g) Compliance with Applicable Laws.
You must comply with all applicable laws regarding use of the eSeGeCe components.
3. TERMINATION
Without prejudice to any other rights, LICENSER may terminate this EULA if you fail to comply
with the terms and conditions of this EULA. In such event, you must destroy all copies of the
eSeGeCe components in your possession.
4. COPYRIGHT
All title, including but not limited to copyrights, in and to the eSeGeCe components and any
copies thereof are owned by LICENSER or its suppliers. All title and intellectual property rights
in and to the content which may be accessed through use of the eSeGeCe components is the
property of the respective content owner and may be protected by applicable copyright or other
intellectual property laws and treaties. This EULA grants you no rights to use such content. All
rights not expressly granted are reserved by LICENSER.
5. NO WARRANTIES
LICENSER expressly disclaims any warranty for the eSeGeCe components. The eSeGeCe
components is provided "As Is" without any express or implied warranty of any kind, including
but not limited to any warranties of merchantability, non-infringement, or fitness of a particular
purpose. LICENSER does not warrant or assume responsibility for the accuracy or
completeness of any information, text, graphics, links or other items contained within the
eSeGeCe components. LICENSER makes no warranties respecting any harm that may be
caused by the transmission of a computer virus, worm, time bomb, logic bomb, or other such
computer program. LICENSER further expressly disclaims any warranty or representation to
Authorized Users or to any third party.
6. LIMITATION OF LIABILITY
In no event shall LICENSER be liable for any damages (including, without limitation, lost profits,
business interruption, or lost information) rising out of "Authorized Users" use of or inability to
use the eSeGeCe components, even if LICENSER has been advised of the possibility of such
damages. In no event will LICENSER be liable for loss of data or for indirect, special, incidental,
consequential (including lost profit), or other damages based in contract, tort or otherwise.
LICENSER shall have no liability with respect to the content of the eSeGeCe components or
any part thereof, including but not limited to errors or omissions contained therein, libel,
infringements of rights of publicity, privacy, trademark rights, business interruption, personal
injury, and loss of privacy, moral rights or the disclosure of confidential information.
164
Index
165
A
A Protocol WebRTC Javascript ................. 104
API Bitfinex .............................................124 Protocols15, 73, 75, 79, 84, 88, 94, 97, 102,
API Blockchain .......................................122 104, 105, 109, 112, 118, 147, 152
API Pusher .............................................129 Protocols Javascript ................................. 75
APIs ............................... 121, 122, 124, 129 Proxy ........................................................ 43
Authentication ........................................... 19 Q
B Quality ...................................................... 27
Bindings .................................................... 26 Service ................................................. 27
C Quality Of Service .................................... 27
Compression ............................................ 24 Queues .................................................... 29
Custom Objects ........................................ 21 QuickStart Library C............................... 140
Custom Sub .............................................. 15 QuickStart Library Delphi ....................... 139
D S
Deflate-Frame.........................................135 Secure Connections................................. 22
Delphi Editions............................................ 5 Server-Sent Events .......................... 36, 161
E Service ..................................................... 27
Editions ....................................................... 5 Quality .................................................. 27
Extensions ..............................................133 SubProtocol ............................................. 33
F T
Files .......................................................... 42 Throttle ..................................................... 35
Flash ......................................................... 25 Transactions ............................................ 31
G TsgcIWWebSocketClient ......................... 69
Guid .......................................................... 88 TsgcIWWSPClient_Dataset ..................... 93
H TsgcIWWSPClient_sgc ............................ 83
HeartBeat ................................................. 40 TsgcWebSocketClient.............................. 58
HTTP ........................................................ 34 TsgcWebSocketClient_SocketIO............. 62
I TsgcWebSocketClient_WinHTTP ............ 65
Installation .................................................. 7 TsgcWebSocketHTTPServer ................... 53
Introduction ................................................. 1 TsgcWebSocketLoadBalancerServer ...... 67
J TsgcWebSocketProxyServer ................... 68
JSON ................................................88, 156 TsgcWebSocketServer ............................ 49
L TsgcWebSocketServer_HTTPAPI ........... 56
Library137, 138, 139, 140, 141, 143, 147, TsgcWSConnection ................................. 71
150, 152 TsgcWSMessageFile ............................. 101
Library Build............................................138 TsgcWSPClient_Dataset ......................... 91
Library Client ..........................141, 143, 147 TsgcWSPClient_Files ............................ 100
Library Client Protocol SGC ...................147 TsgcWSPClient_MQTT.......................... 119
Library Client SocketIO ..........................143 TsgcWSPClient_sgc ................................ 81
Library Server .................................150, 152 TsgcWSPClient_WAMP ........................ 107
Library Server Protocol SGC ..................152 TsgcWSPClient_WAMP2 ...................... 113
License ...................................................163 TsgcWSProtocol_Client_dataset ............. 91
LoadBalancing .......................................... 39 TsgcWSProtocol_Client_sgc ................... 81
Logs .......................................................... 44 TsgcWSProtocol_Server_dataset............ 89
M TsgcWSProtocol_Server_sgc .................. 80
MQTT .....................................................160 TsgcWSPServer_Dataset ........................ 89
O TsgcWSPServer_Files ............................. 98
Overview................................................... 11 TsgcWSPServer_sgc ............................... 80
P TsgcWSPServer_WAMP ....................... 106
PerMessage-Deflate ...............................134 TsgcWSPServer_WebRTC ................... 103
Protocol Dataset .................................88, 94 U
Protocol Dataset Javascript...................... 94 Using DLL ................................................ 47
Protocol Default ............................79, 84, 88 W
Protocol Default Javascript....................... 84 WAMP .................................................... 158
Protocol Files ............................................ 97 WatchDog ................................................ 41
Protocol MQTT .......................................118 Web Browser Test ................................... 14
Protocol WAMP ..............................105, 109 WebRTC ................................................ 159
Protocol WAMP Javascript .....................109 WebSocket Events................................... 45
Protocol WAMP2 ....................................112 WebSocket Parameters Connection........ 46
Protocol WebRTC ..........................102, 104 WebSockets ............................... 45, 46, 155
166
167