webSocketOpen()
Opens a WebSocket connection to the given url.
Synopsis
int webSocketOpen(string url [,mapping options])
Parameters
Parameter | Description | |
---|---|---|
url |
Url that should be connected to. The url scheme has to be "ws" or "wss" e.g.:
|
|
options | A mapping containing further options as key/value pairs. | |
"headers" |
An additional header, that is transferred to the server during the communication.
e.g.
|
|
"timeout" |
The maximum time until the connection attempt is canceled. In case of time out the return value is -2. Without this option, the time out is unlimited. |
|
"ignoreSslErrors" |
If you pass a value unequal to dyn_string or an empty dyn_string, all SSL errors are ignored. If you specify a dyn_string, you specify which SSL errors may be ignored. If there are other SSL errors, the function returns -1 and is terminated. For possible SSL error key words, see "sslErrors" in the netGet() variable "result". e.g.
|
|
"sslConfig" |
The sslConfig is a mapping that contains the certificate information required for secure communication and contains the following keys
Example: A PEM encoded certificate file can be loaded from the local disk like this: fileToString(getPath(CONFIG_REL_PATH, "certificate.pem"), cert) Then the returned string can be passed as value for the key "localCertificate". |
Return value
On success, a socket number >= 0 is returned, on error -1 is returned and on timeout -2 is returned.
Errors
Errors can be: invalid url (e.g. syntax error in url, Unsupported scheme), no more free sockets (system limit reached), argument error in options, error during connection (e.g. ssl error, network error, etc.)
On network errors, getLastError() can be used to get a more detailed error message.
Example
This example opens a WebSocket connection to the given url, writes data to the given WebSocket, reads the data and closes the connection.
#uses "CtrlHTTP"
main()
{
int webSocket = webSocketOpen("wss://localhost:40000/", makeMapping("ignoreSslErrors", true));
if (webSocket < 0)
{
DebugN("Not possible to open the web socket! Error: ", getLastError());
return;
}
string request = jsonEncode(makeMapping("method", "dummy", "connectionId", 12345678, "payload", data, "id", id));
int writeResult = webSocketWrite(webSocket, request);
if (writeResult != 0)
{
DebugN("Not possible to write! Error: ", getLastError());
}
else
{
anytype any;
int readResult = webSocketRead(webSocket, any);
if (readResult != 0)
{
DebugN("Not possible to read! Error: ", getLastError());
}
}
int closeResult = webSocketClose(webSocket);
if (closeResult < 0)
{
DebugN("Not possible to close the open web socket! Error: ", getLastError());
}
DebugN("The open web socket successfuly closed!");
}
Assignment
WebSocket functions
Availability
CTRL