WebSocket protocol starts with an HTTP Handshake similar to normal HTTP Request, this handshake has an address request, origin, protocols supported... sometimes is useful to add some custom headers. sgcWebSockets supports customize HandShake Headers using OnHandshake event of Client WebSocket Component. There is a parameter called Headers which is a TStringList that contains a list of headers will be sent to Server, you can modify these headers or add your custom headers.

Example: add header "x-my-header" with value "test"

 

procedure OnClientHandshake(Connection: TsgcWSConnection; var Headers: TStringList);

begin

  Headers.Add('x-my-hader: test');

end;

TsgcWSHTTPWebBrokerBridgeServer use TIdHttpWebBrokerBridge as server base and is useful if you want to use a single server for DataSnap, HTTP and WebSocket connections.

TsgcWSHTTPWebBrokerBridgeServer inherits from TsgcWebSocketHTTPServer, so you can refer to this server.

Follow next steps to replace TIdHttpWebBrokerBridge for TsgcWSHTTPWebBrokerBridgeServer :

 1. Create a new instance of TsgcWSHTTPWebBrokerBridgeServer.

 2. Replace all calls to TIdHttpWebBrokerBridge for TsgcWSHTTPWebBrokerBridgeServer.

 3. To Handle WebSocket connections just refer to TsgcWebSocketHTTPServer.

Upload files to a websocket server is very easy, just send file as binary data. Example of HTML client:

 

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Upload Files</title>

</head>

<body>

    <h2>File Upload</h2>

    Select file

    <input type="file" id="filename" />

    <br>

    <input type="button" value="Connect" onclick="connectChatServer()" />

    <br>

    <input type="button" value="Upload" onclick="sendFile()" />

    <script>

        var ws;

        function connectChatServer() {

            ws = new WebSocket("ws://127.0.0.1");

            ws.binaryType = "arraybuffer";

            ws.onopen = function() {

                alert("Connected.")

            };

            ws.onmessage = function(evt) {

                alert(evt.msg);

            };

            ws.onclose = function() {

                alert("Connection is closed...");

            };

            ws.onerror = function(e) {

                alert(e.msg);

            }

        }

        function sendFile() {

            var file = document.getElementById('filename').files[0];

            var reader = new FileReader();

            var rawData = new ArrayBuffer();            

            reader.loadend = function() {

            }

            reader.onload = function(e) {

                rawData = e.target.result;

                ws.send(rawData);

                alert("the File has been transferred.")

            }

            reader.readAsArrayBuffer(file);

        }

    </script>

</body>

</html>

Once binary message is received by server, just create a TFileStream and copy binary data. Example of Server:

procedure OnWSServerBinary(Connection: TsgcWSConnection; const Data: TMemoryStream);

var

  oFile: TFileStream;

begin

  oFile := TFileStream.Create('file.dat', fmCreate);

  Try

    oFile.CopyFrom(Data, Data.Size);

  Finally

    oFile.Free;

  End;

end;

 

From sgcWebSockets 4.1.6 default SGC Protocol supports wildcards in Subscribe, UnSubscribe and Publish methods, websocket protocol.

Channel is a string used by server to filter messages for each connected client. A channel can consists of one or more levels, usually each topic is separated by a forward slash. Example

  weather/usa/california/San Francisco/Silicon Valley

 

When a client subscribe to a channel it can use exact channel name or can subscribe to more channels at once by using wildcards. Example:

 

  weather/usa/california/*

  weather/usa/*

 

Wildcards only works for active channels, so you can create some persistent channels before server is started:

 

  WSPPROTOCOL.Subscriptions.Add(NewGuid + '_' + 'weather/usa/california';

  WSPPROTOCOL.Subscriptions.Add(NewGuid + '_' + 'weather/usa';

 

Implemented from sgcWebSockets 4.1.4

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"

Client.Host := server host;

Client.Port := server.port;

Client.RegisterProtocol('Test 1.0');

Client.Active := True;

 

 

When a client sends a binary message to server, sometimes is useful set an ID to identify binary message when is received. There are 2 functions in sgcWebSocket_Helpers which can be used to set a short description of binary packet, basically adds a header to stream which is used to identify binary packet.

 

Before send a binary message, call sgcWSStreamWrite method to encode stream.

   vID := '00001';

   sgcWSStreamWrite(vID, oStream);

   Client.WriteData(oStream);

 

When binary message is received, call sgcWSStreamRead method to decode stream.

   sgcWSStreamRead(oStream, vID);

 

The only limitation is that text used to identify binary message, has a maximum length of 10 characters (this can be modified if you have access to source code).