Qore WebSocketClient Module Reference  1.9.1
WebSocketClient::WebSocketClient Class Reference

the main websocket client class More...

Public Member Methods

 clearStats ()
 Clears performance statistics. More...
 
nothing clearWarningQueue ()
 Removes any warning Queue object from the Socket. More...
 
hash< auto > connect (*hash opts, *reference< hash > info)
 connects to the websocket server More...
 
 constructor (code cb, hash< auto > opts)
 creates the object and optionally sets logging targets More...
 
 destructor ()
 disconnects the connection and stops the event thread if connected
 
 disconnect (int cmd=WSCC_GoingAway)
 disconnect with the given close code
 
int getConnectionId ()
 returns the unique connection ID
 
hash< auto > getSchemes ()
 returns a hash of URL scheme information for URL schemes supported by this object
 
string getUrl ()
 returns the URL given in the constructor
 
hash< auto > getUsageInfo ()
 Returns performance statistics for the socket. More...
 
bool isOpen ()
 returns True if the connection is currently open and active, False if not
 
 pong ()
 Sends a PONG message to the server as a unidirectional keep-alive message. More...
 
 send (binary bin)
 Sends binary data over the web socket with timeout specified in options; if any errors occur, an exception is thrown. More...
 
 send (data msg, int op, bool fin)
 pushes an unencoded message on the connection's message queue; the message will be encoded with WebSocketUtil::ws_encode_message() before sending
 
 send (string str)
 Sends string data over the web socket with timeout specified in options; if any errors occur, an exception is thrown. More...
 
 setEventQueue ()
 Removes any Queue object so that socket events are no longer added to the Queue. More...
 
 setEventQueue (Qore::Thread::Queue queue, auto arg, *bool with_data)
 Sets a Queue object to receive socket events. More...
 
nothing setWarningQueue (int warning_ms, int warning_bs, Queue queue, auto arg, timeout min_ms=1s)
 Sets a Queue object to receive socket warnings. More...
 

Public Attributes

const DefaultTimeout = 15s
 default socket I/O operation timeout: 15 seconds
 
const DefaultUserAgent = sprintf("Qore-WebSocketClient/%s", WebSocketClient::Version)
 default user agent string for HTTP requests
 
const Version = "1.6"
 module version
 

Private Attributes

int cid = -1
 unique websocket connection ID; -1 when not connected
 
string url
 URL string.
 
*code yield
 callable object to yield the current thread's execution
 

Detailed Description

the main websocket client class

To use this class, create a WebSocketClient object and the call WebSocketClient::connect().

The WebSocketClient::connect() method starts a background thread to receive messages, which are then posted to the callback provided in the WebSocketClient::constructor().

To stop listening for web socket events, call WebSocketClient::disconnect().

The WebSocketClient class includes support for running in sandboxed Program objects with the following parse options set:

Member Function Documentation

◆ clearStats()

WebSocketClient::WebSocketClient::clearStats ( )

Clears performance statistics.

Example:
ws.clearStats();
Since
WebSocketClient 1.1
See also
WebSocketClient::getUsageInfo()

◆ clearWarningQueue()

nothing WebSocketClient::WebSocketClient::clearWarningQueue ( )

Removes any warning Queue object from the Socket.

Example:
ws.clearWarningQueue();
See also
WebSocketClient::setWarningQueue()
Since
WebSocketClient 1.1

◆ connect()

hash<auto> WebSocketClient::WebSocketClient::connect ( *hash  opts,
*reference< hash info 
)

connects to the websocket server

Example:
sub event(*data msg) {
if (!msg) {
printf("connection closed\n");
} else {
printf("%s msg: %y\n", now_us().format("YYYY-MM-DD HH:mm:SS.xx"), msg);
}
}
int sub raw_callback(hash<WsMsgInfo> event) {
printf("raw event: %y\n", event);
return WSC_Process;
}
WebSocketClient ws(\event(), {
"url": "ws://example.com:8080/path",
"raw_callback": \raw_callback(),
});
ws.connect();

This method starts a background thread to receive messages, which are then posted to the callback closure or call reference given as an argument. If the server disconnects the web socket connection, the callback will be called with no argument (ie NOTHING). In this case the event thread also terminates and the WebSocketClient object will be in a disconnected state.

To stop listening for web socket events, call WebSocketClient::disconnect().

If this method is called while a connection is already in progress, then the existing connection is first implicitly disconnected with close code WSCC_GoingAway.

Parameters
optsa hash with the following keys:
  • hdr: (optional) a hash giving header values for the connection request to the web socket server
infoa reference to a hash which will be set to information about the call setup
Returns
a hash with information about the HTTP response from the webn socket server corresponding to the return value of Qore::Socket::readHTTPHeader()
Exceptions
WEBSOCKET-ERRORthe option hash is missing either the 'url' or 'callback' keys or type error in the option hash

◆ constructor()

WebSocketClient::WebSocketClient::constructor ( code  cb,
hash< auto >  opts 
)

creates the object and optionally sets logging targets

Example:
sub event(*data msg) {
if (!msg) {
printf("connection closed\n");
} else {
printf("%s msg: %y\n", now_us().format("YYYY-MM-DD HH:mm:SS.xx"), msg);
}
}
int sub raw_callback(hash<WsMsgInfo> event) {
printf("raw event: %y\n", event);
return WSC_Process;
}
WebSocketClient ws(\event(), {
"url": "ws://example.com:8080/path",
"raw_callback": \raw_callback(),
});
Parameters
cbthe callback closure or call reference for received messages
optsan option hash for the HTTPClient constructor plus the following keys:
Exceptions
WEBSOCKET-ERRORunknown scheme, missing 'url' key in option hash; invalid option value
Since

◆ getUsageInfo()

hash<auto> WebSocketClient::WebSocketClient::getUsageInfo ( )

Returns performance statistics for the socket.

Example:
hash<auto> h = ws.getUsageInfo();
Returns
a hash with the following keys:
  • "bytes_sent": an integer giving the total amount of bytes sent
  • "bytes_recv": an integer giving the total amount of bytes received
  • "us_sent": an integer giving the total number of microseconds spent sending data
  • "us_recv": an integer giving the total number of microseconds spent receiving data
  • "arg": (only if warning values have been set with WebSocketClient::setWarningQueue()) the optional argument for warning hashes
  • "timeout": (only if warning values have been set with WebSocketClient::setWarningQueue()) the warning timeout in microseconds
  • "min_throughput": (only if warning values have been set with WebSocketClient::setWarningQueue()) the minimum warning throughput in bytes/sec
Since
WebSocketClient 1.1
See also
WebSocketClient::clearStats()

◆ pong()

WebSocketClient::WebSocketClient::pong ( )

Sends a PONG message to the server as a unidirectional keep-alive message.

Since
WebSocketClient 1.6.1

◆ send() [1/2]

WebSocketClient::WebSocketClient::send ( binary  bin)

Sends binary data over the web socket with timeout specified in options; if any errors occur, an exception is thrown.

Parameters
binSends the binary data over the socket
See also
Socket::send()

◆ send() [2/2]

WebSocketClient::WebSocketClient::send ( string  str)

Sends string data over the web socket with timeout specified in options; if any errors occur, an exception is thrown.

Parameters
strSends the string data over the socket
See also
Socket::send()

◆ setEventQueue() [1/2]

WebSocketClient::WebSocketClient::setEventQueue ( )

Removes any Queue object so that socket events are no longer added to the Queue.

Example:
ws.setEventQueue();
See also
I/O Event Handling for more information
Since
WebSocketClient 1.8

◆ setEventQueue() [2/2]

WebSocketClient::WebSocketClient::setEventQueue ( Qore::Thread::Queue  queue,
auto  arg,
*bool  with_data 
)

Sets a Queue object to receive socket events.

Example:
ws.setEventQueue(queue);
Parameters
queuethe Queue object to receive socket events; note that the Queue passed cannot have any maximum size set or a QUEUE-ERROR will be thrown
argan argument that will be included in each event hash in the arg key
with_dataif True, then the actual raw data transferred / received is also included in the events
Exceptions
QUEUE-ERRORthe Queue passed has a maximum size set
See also
I/O Event Handling for more information
Since
WebSocketClient 1.8

◆ setWarningQueue()

nothing WebSocketClient::WebSocketClient::setWarningQueue ( int  warning_ms,
int  warning_bs,
Queue  queue,
auto  arg,
timeout  min_ms = 1s 
)

Sets a Queue object to receive socket warnings.

Example:
ws.setWarningQueue(5000, 5000, queue, "socket-1");
Parameters
warning_msthe threshold in milliseconds for individual socket actions (send, receive, connect), if exceeded, a socket warning is placed on the warning queue with the following keys:
  • "type": a string with the constant value "SOCKET-OPERATION-WARNING"
  • "operation": a string giving the operation that caused the warning (ex: "connect")
  • "us": an integer giving the number of microseconds for the operation
  • "timeout": an integer giving the warning threshold in microseconds
  • "arg": if any "arg" argument is passed to the WebSocketClient::setWarningQueue() method, it will be included in the warning hash here
warning_bsvalue in bytes per second; if any call has performance below this threshold, a socket warning is placed on the warning queue with the following keys:
  • "type": a string with the constant value "SOCKET-THROUGHPUT-WARNING"
  • "dir": either "send" or "recv" depending on the direction of the data flow
  • "bytes": the amount of bytes sent
  • "us": an integer giving the number of microseconds for the operation
  • "bytes_sec": a float giving the transfer speed in bytes per second
  • "threshold": an integer giving the warning threshold in bytes per second
  • "arg": if any "arg" argument is passed to the WebSocketClient::setWarningQueue() method, it will be included in the warning hash here
queuethe Queue object to receive warning events
argan optional argument to be placed in the "arg" key in each warning hash (could be used to identify the socket for example)
min_msthe minimum transfer time with a resolution of milliseconds for a transfer to be eligible for triggering a warning; transfers that take less than this period of time are not eligible for raising a warning
Exceptions
QUEUE-ERRORthe Queue passed has a maximum size set
SOCKET-SETWARNINGQUEUE-ERRORat least one of warning_ms and warning_bs must be > 0
See also
WebSocketClient::clearWarningQueue()
Since
WebSocketClient 1.1
now_us
date now_us()
printf
string printf(string fmt,...)