Main Page » XQuery » Functions » WebSocket Functions

WebSocket Functions

This module contains functions for accessing and addressing WebSocket connections. This module is mainly useful in the context of WebSockets.

Conventions

  • The module will be available if the basex-api library is found in the classpath. This is the case if you use one of the complete distributions of BaseX (zip, exe, war).
  • All functions and errors are in the http://basex.org/modules/ws namespace, to which the ws prefix is statically bound.
  • As WebSocket operations are side-effecting, all functions are flagged as nondeterministic. As a result, some query optimizations will be suppressed.

General Functions

ws:id

Signature
ws:id() as xs:string
SummaryReturns the ID of the current WebSocket.
Errors
not-foundNo WebSocket with the specified id exists.

ws:ids

Signature
ws:ids() as xs:string*admin
SummaryReturns the ids of all currently registered WebSockets.

ws:path

Signature
ws:path(  $id  as xs:string) as xs:stringadmin
SummaryReturns the path of the WebSocket with the specified $id.
Errors
not-foundNo WebSocket with the specified id exists.

ws:close

Updated: A close status and a reason can be supplied.

Signature
ws:close(  $id      as xs:string,  $status  as xs:integer  := 1000,  $reason  as xs:string  := '') as empty-sequence()admin
SummaryCloses the connection of the WebSocket with the specified $id. A close $status code (10004999, except for 1005 and 1006, which are reserved for internal use, see RFC 6455, Section 7.4) and a $reason string (at most 123 bytes in its UTF-8 representation) can be supplied; both will be transmitted to the client.
Errors
not-foundNo WebSocket with the specified id exists.

Sending Data

ws:send

Signature
ws:send(  $message  as item(),  $ids      as xs:string*) as empty-sequence()admin
SummarySends a $message to the clients with the specified $ids. Ids that cannot be assigned to clients will be ignored. The message will be handled as follows:
  • Items of type xs:base64Binary and xs:hexBinary will be transmitted as binary messages.
  • Maps and arrays will be serialized as JSON and transmitted as string messages.
  • All other items will be serialized with the default serialization options and transmitted as string messages.

ws:broadcast

Signature
ws:broadcast(  $message  as item()) as empty-sequence()admin
SummaryBroadcasts a $message to all connected clients except to the caller. Invocations of this convenience function are equivalent to ws:send($message, ws:ids()[. != ws:id()]). See ws:send for more details on the message handling.

ws:emit

Signature
ws:emit(  $message  as item()) as empty-sequence()admin
SummaryEmits a $message to all connected clients. Invocations of this function are equivalent to ws:send($message, ws:ids()). See ws:send for more details on the message handling.

ws:ping

Added: New function.

Signature
ws:ping(  $id  as xs:string) as empty-sequence()admin
SummarySends a ping frame to the client with the specified $id. Pings can be used as heart-beats for keeping connections alive: the client answers with a pong frame on the protocol level, and no message handlers will be invoked on either side.
Errors
not-foundNo WebSocket with the specified id exists.

ws:eval

Updated: All options of job:eval except service are supported.

Updated: The query result is sent as a single message, and errors are reported to the client.

Updated: A function item can be invoked instead of a query.

Signature
ws:eval(  $query     as (xs:string|xs:anyURI|fn(*)),  $bindings  as (map((xs:string|xs:QName), item()*)|array(*))?  := (),  $options   as map(*)?  := {}) as xs:stringadmin
SummarySchedules the evaluation of the supplied $query and returns the result to the calling WebSocket client. The query can be a URI or a string, and variables and the context value can be declared via $bindings (see xquery:eval for more details). Instead of a query, a function item can be supplied, which is invoked with the arguments of the $bindings array. All $options of job:eval except service are supported, and additionally:
optiondefaultdescription
serializer{} Serialization parameters for the query result.

The result is sent to the client as a single message. If the query fails, the error is sent instead.

Scheduling is recommended if the immediate query execution might be too time consuming and result in a timeout.

Examples
declare
  %ws:message('/tasks', '{$message}')
function local:message($message) {
  ws:eval('prof:sleep(10000), "Your message has been processed."')
};
Schedule a second query that will notify the client 10 seconds later that a message was processed.

WebSocket Attributes

ws:get

Signature
ws:get(  $id       as xs:string,  $key      as xs:string,  $default  as item()*  := ()) as item()*admin
SummaryReturns the value of the attribute with the specified $key for the WebSocket with the specified $id. If the attribute is unknown, an empty sequence or the optionally specified $default value will be returned instead.
Errors
not-foundNo WebSocket with the specified id exists.

ws:set

Signature
ws:set(  $id     as xs:string,  $key    as xs:string,  $value  as item()*) as empty-sequence()admin
SummaryAssigns the specified $value to the attribute with the specified $key for the WebSocket with the specified $id.
Errors
not-foundNo WebSocket with the specified id exists.

ws:delete

Signature
ws:delete(  $id   as xs:string,  $key  as xs:string) as empty-sequence()admin
SummaryDeletes the attribute with the specified $key from the WebSocket with the specified $id.
Errors
not-foundNo WebSocket with the specified id exists.

Examples

Example 1

import module namespace ws = "http://basex.org/modules/ws";

declare
  %ws:connect('/')
function local:connect() as empty-sequence() {
  let $id := ws:id()
  let $message := json:serialize({ 'type': 'Connect', 'id': $id })
  return ws:broadcast($message)
};
Explanation:
  • The function has a %ws:connect annotation. It gets called if a client successfully creates a WebSocket connection to the path / (check out WebSockets for further information).
  • A JSON response is generated, which contains the new client id and a Connect string.
  • This response will be sent to all other connected clients.

Example 2

import module namespace ws = "http://basex.org/modules/ws";

declare
  %ws:message('/', '{$message}')
function local:message(
  $message as xs:string
) as empty-sequence() {
  let $message := json:serialize({ 'message': $message })
  return ws:emit($message)
};
Explanation:
  • The function has a %ws:message annotation. It gets called if a client sends a new message.
  • A JSON response is generated, which contains the message string.
  • This response will be sent to all connected clients (including the calling client).

Errors

CodeDescription
not-foundNo WebSocket with the specified id exists.

Changelog

Version 13.0
  • Added: ws:ping
  • Updated: ws:close: optional close status and reason.
  • Updated: ws:eval: job options and serialization parameters.
  • Updated: ws:eval: a function item can be invoked instead of a query.
Version 9.2Version 9.1
  • Added: New module added.

⚡Generated with XQuery