Changes

Jump to navigation Jump to search
2,772 bytes added ,  15:43, 27 February 2020
no edit summary
=Conventions=
* The module will be available if the {{Code|basex-api}} package must be included library is found in the classpath. This is always the case if you use one of the complete distributions of BaseX (zip, exe, war) of BaseX.* All functions and errors are assigned to the <code><nowiki>http://basex.org/modules/websocketws</nowiki></code> namespace. The module must be imported in , which is statically bound to the query prolog:<pre class="brush:xquery">import module namespace websocket = "http://basex{{Code|ws}} prefix.org/modules/Websocket";* As sessions are side-effecting operations, all functions are flagged as ''non-deterministic''.As a result, some query optimizations will be suppressed..</pre>
=General Functions= ==ws:id== {| width='100%'|-| width='120' | '''Signatures'''|{{Func|ws:id||xs:string}}|-| '''Summary'''|Returns the ID of the current WebSocket.|-| '''Errors'''|{{Error|not-found|#Errors}} No WebSocket with the specified id exists.|} ==ws:ids== {| width='100%'|-| width='120' | '''Signatures'''|{{Func|ws:ids||xs:string*}}|-| '''Summary'''|Returns the ids of all currently registered WebSockets.|} ==ws:path== {| width='100%'|-| width='120' | '''Signatures'''|{{Func|ws:path|$id as xs:string|xs:string}}|-| '''Summary'''|Returns the path of the WebSocket with the specified {{Code|$id}}.|-| '''Errors'''|{{Error|not-found|#Errors}} No WebSocket with the specified id exists.|} ==ws:close== {| width='100%'|-| width='120' | '''Signatures'''|{{Func|ws:close|$id as xs:string|empty-sequence()}}|-| '''Summary'''|Closes the connection of the WebSocket with the specified {{Code|$id}}.|-| '''Errors'''|{{Error|not-found|#Errors}} No WebSocket with the specified id exists.|} =Sending Data= ==ws:send==
==websocket:send==
{| width='100%'
|-
| width='120' | '''Signatures'''
|{{Func|websocketws:send|$message as xs:anyAtomicTypeitem(), $ids as xs:string* |empty-sequence()}}
|-
| '''Summary'''
|Sends a <code>$message</code> which may to the clients with the specified <code>$ids</code>. Ids that cannot be assigned to clients will be ignored. The message will be handled as follows:* Items of type xs:string, {{Code|xs:base64Binary, or }} and {{Code|xs:hexBinary to the user}} will be transmitted as binary messages.* Function items (smaps, arrays) will be serialized as JSON and transmitted as string messages.* All other items will be serialized with the ID(s) <code>$ids</code>default serialization options and transmitted as string messages.
|}
==websocketws:broadcast== 
{| width='100%'
|-
| width='120' | '''Signatures'''
|{{Func|websocketws:broadcast|$message as xs:anyAtomicType|empty-sequence()}}
|-
| '''Summary'''
|Broadcasts a <code>$message</code> which may be of type xs:string, xs:base64Binary, or xs:hexBinary to all connected clients except to the caller. Invocations of this convenience function are equivalent to <code>ws:send($message, ws:ids()[. != ws:id()])</code>. See [[#ws:send|ws:send]] for more details on the message handling.
|}
==websocketws:emit== 
{| width='100%'
|-
| width='120' | '''Signatures'''
|{{Func|websocketws:emit|$message as xs:anyAtomicType|empty-sequence()}}
|-
| '''Summary'''
|Emits a <code>$message</code> which may be to all connected clients. Invocations of type xsthis function are equivalent to <code>ws:stringsend($message, xsws:ids())</code>. See [[#ws:base64Binary, or xssend|ws:hexBinary to all connected clientssend]] for more details on the message handling.
|}
==websocketws:ideval== 
{| width='100%'
|-
| width='120' | '''Signatures'''
|{{Func|websocketws:ideval|$query as xs:anyAtomicItem|xs:string}}<br />{{Func|ws:eval|$query as xs:anyAtomicItem, $bindings as map(*)?|xs:string}}<br />{{Func|ws:eval|$query as xs:anyAtomicItem, $bindings as map(*)?, $options as map(*)?|xs:string}}<br />
|-
| '''Summary'''
|Returns Schedules the ID evaluation of the current supplied {{Code|$query}} and returns the result to the calling WebSocket client. The query can be a URI or a string, and variables and context items can be declared via {{Code|$bindings}} (see {{Function|XQuery|xquery:eval}} for more details). The following {{Code|$options}} can be supplied:* {{Code|base-uri}}: sets the [https://www.w3.org/TR/xquery-31/#dt-static-base-uri base-uri property] for the query. This URI will be used when resolving relative URIs, such as with {{Code|fn:doc}}.* {{Code|id}}: sets a custom job id. The id must not start with the standard <code>job</code> prefix, and it can only be assigned if no job with the same name exists.Query scheduling is recommendable if the immediate query execution might be too time consuming and lead to a timeout.|-| '''Errors'''|{{Error|overflow|#Errors}} Query execution is rejected, because too many jobs are queued or being executed. <br/>{{Error|id|#Errors}} The specified id is invalid or has already been assigned.|-| '''Examples'''|* Schedule a second query that will notify the client WebSocket connection10 seconds later that a message was processed:<syntaxhighlight lang="xquery">declare %ws:message('/tasks', '{$message}')function local:message($message) { ws:eval('prof:sleep(10000), "Your message has been processed."')}; </syntaxhighlight>
|}
=WebSocket Attributes=websocket ==ws:idsget== 
{| width='100%'
|-
| width='120' | '''Signatures'''
|{{Func|websocketws:idsget|$id as xs:string, $name as xs:string|item()*}}<br/>{{Func|ws:get|$id as xs:string, $name as xs:string, $default as item()*|item()*}}
|-
| '''Summary'''
|Returns the IDs value of all current an attribute with the specified {{Code|$name}} from the WebSocket connectionswith the specified {{Code|$id}}. If the attribute is unknown, an empty sequence or the optionally specified {{Code|$default}} value will be returned instead.|-| '''Errors'''|{{Error|not-found|#Errors}} No WebSocket with the specified id exists.
|}
==websocketws:pathset== 
{| width='100%'
|-
| width='120' | '''Signatures'''
|{{Func|websocketws:path|set|$id as xs:string, $name as xs:string, $value as item()*|empty-sequence()}}
|-
| '''Summary'''
|Returns the path specified {{Code|value}} of the current WebSocketClientattribute with the specified {{Code|$name}} from the WebSocket with the specified {{Mono|$id}}.|-| '''Errors'''|{{Error|not-found|#Errors}} No WebSocket with the specified id exists.<br>{{Error|set|#Errors}} The supplied value cannot be materialized.
|}
==websocketws:pathdelete== 
{| width='100%'
|-
| width='120' | '''Signatures'''
|{{Func|websocketws:pathdelete|$id as xs:string|, $name as xs:string|empty-sequence()}}
|-
| '''Summary'''
|Returns Deletes an attribute with the specified {{Code|$name}} from the path of specific user WebSocket with the ID <code>specified {{Mono|$id</code>}}.|-| '''Errors'''|{{Error|not-found|#Errors}} No WebSocket with the specified id exists.
|}
=Example 1Examples= ==CodeExample 1== <pre classsyntaxhighlight lang="brush:xquery">import module namespace ws = "http://basex.org/modules/ws"; 
declare
module namespace websocketexample = %ws:connect('http://basex.org/modules/web-page';)function local:connect() as empty-sequence() { let $id : Import the WebSocket module = ws:id()import module namespace websocket let $message := "httpjson:serialize(map { 'type': 'Connect', 'id': $id }) return ws:broadcast($message)};</syntaxhighlight> '''Explanation:''' * The function has a <code>%ws:connect</basexcode> annotation.orgIt gets called if a client successfully creates a WebSocket connection to the path <code>/modules</Websocket";code> (check out [[WebSockets]] for further information).* A JSON response is generated, which contains the new client id and a <code>Connect</code> string.* This response will be sent to all other connected clients. ==Example 2==
%ws:connect("/") function websocketexample:connect( ) { let $client-id := websocket:id() let $client-path := websocket:path() let $response := json:serialize( <json typesyntaxhighlight lang="objectxquery"> <messageType>UserConnected</messageType> <clientId>{$client-id}</clientId> <clientPath>{$client-path}</clientPath> </json> ) return websocket:broadcast($response) };</pre>==Explanation==* First of all: include the websocket import module* The <code>$namespace ws= "http:connect("/")</code> annotation gets called if a client successfully creates a websocket to the path "/" (checkout [[WebSockets]] for further information)basex.* Get the <code>client-id<org/code> and the <code>client-path<modules/code> with <code>websocket:id()</code> and <code>websocket:path()</code>* Create a json-result * Broadcast the result to all connected clients without the calling clientws";
=Example 2=
==Code==
<pre class="brush:xquery">
module namespace websocketsexample = 'http://basex.org/modules/web-page';
(: Import the Websockets module :)
import module namespace websocket = "http://basex.org/modules/Websocket";
declare
%ws:message("'/"',"'{$message}"') function websocketsexamplelocal:message( $message as xs:string ){ let $clientas empty-ids := websocket:idssequence(){ let $fist-client-id message := fnjson:headserialize(map { 'message': $client-idsmessage }) let $send-to-id return ws:= websocket:sendemit($message,$first-client-id) let $path-first-client };</syntaxhighlight> '''Explanation:= websocket''' * The function has a <code>%ws:pathmessage</code> 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 ($first-including the calling client-id). =Errors= let $response :{| class="wikitable" width= json:serialize("100%" <json type! width="object110">|Code|Description <messageType>PathFirstClient</messageType>|- <path>|{{$pathCode|set}}|The supplied value cannot be materialized.|-first|{{Code|not-clientfound}}|No WebSocket with the specified id exists.|}</path> </json> ) =Changelog= return websocket:emit($response) };Version 9.2 * Added: [[#ws:eval|ws:eval]]
</pre>==Explanatation==* First of all, import the websocket This module* The annotation <code>$ws:message("/",{$message}")</code> gets called if a message arrives at the server (checkout [[WebSockets]] for further information)was introduced with Version 9.* With <code>websocket:ids()</code> you will get the ids of all connected clients1.* The function <code>websocket:send($message,$first-client-id)</code> sends the <code>$message</code> to the client with the id <code>$first-client-id</code>* <code>websocket:path($first-client-id)</code> returns the path of the client with the id <code>$first-client-id</code>* To emit a message to all connected clients you call <code>websocket:emit($response)</code>
Bureaucrats, editor, reviewer, Administrators
13,550

edits

Navigation menu