Changes

Jump to navigation Jump to search
4,895 bytes added ,  14:18, 27 February 2020
no edit summary
This page presents one of the [[Web Application]] services. It describes how to use the WebSockets API of BaseX. WebSocket is a communication protocol for providing '''full-duplex''' communication: Data can be sent in both directions and simultaneously.
Please note that the current WebSocket implementation relies on Jetty’s WebSocket servlet API. Other web servers may be supported in future versions.
=Introduction=
 
==Protocol==
 
Use WebSockets if you have to exchange data with a high frequency or if you have to send messages from the server to the client without techniques like [polling https://en.wikipedia.org/wiki/Polling_(computer_science)]. In contrast to REST, WebSockets use a single URL for the whole communication.
 
The WebSocket protocol was standardized in [https://tools.ietf.org/html/rfc6455 RFC 6455] by the IETF. After an initial HTTP request, all communication takes place over a single TCP connection. Unlike the HTTP protocol, a connection will be kept alive, and a server can send unsolicited data to the client.
 
For establishing a WebSocket connection, a handshake request is sent by the client. The web server returns a handshake response. If the handshake is successful, the persistent connection will be open until the client or the server closes it, an error occurs or a timeout happens. It is possible to transmit all kind of data, binary or text. '''The BaseX WebServer handles the handshake completely.''' You just have to define some limits of the connection in the <code>web.xml</code> and specify functions for WebSocket events like ''onConnect'' and ''onMessage''.
 
Notice that there is no specification of a message protocol. The WebSocket protocol just specifies the message architecture but not how the payload of the messages is formatted. To agree on a format between the server and the client one can use sub-protocols.
 
Some older browsers don’t support the WebSocket protocol. Therefore you can use fallback options like Ajax. JavaScript client libraries like SockJS can be used for building client applications. The library takes care of how to establish the real-time connection. If the WebSocket protocol isn’t supported, it uses polling. You have to provide server functions for the fallback solutions if you have to support fallbacks.
==Preliminaries==
There are a bunch of Annotations annotations depending to WebSockets for annotating XQuery functions. When a WebSocket-Message comes inmessage arrives at the server, an XQuery function will be invoked that matches the constraints indicated by its annotations. If a WebSocket function is requested (like connecting to the path <code>/</code>, sending a message to the path <code>/path</code>, …), the module directory and its sub-directories will be traversed, and all [[XQuery Extensions#Suffixes|XQuery files]] will be parsed for functions with WebSocket annotations. Sub-directories that include an {{Code|.ignore}} file will be skipped. To speed up processing, the functions of the existing XQuery modules are automatically cached in main memory. For further information on cache handling, check out the [[RESTXQ#Introduction|RESTXQ introduction]]. ==Configuration== * The WebSocket servlet can be enabled and disabled in the <code>web.xml</code> configuration file. You can specify further configuration options, such as <code>maxIdleTime</code>, <code>maxTextMessageSize</code>, and <code>maxBinaryMessageSize</code>.* The default limit for messges is 64 KB. If you a message exceeds the default or the specified limit, an error will be raised and the connection will be closed. =Annotations= To tag functions as WebSocket functions you have to use [[XQuery 3.0#Annotations|annotations]]. The annotation is written after the keyword ''declare'' and before the keyword ''function''. For the context of WebSockets there are some annotations listed below. Functions which are annotated with a WebSocket annotation will be called if the appropriate event occurs. For example, the function annotated with <code>ws:connect('/')</code> will be executed if a client establishes a connection with the WebSocket root path (which is, by default, <code>ws/</code>). By using annotations, it’s easy to provide an API for your WebSocket connection. You just have to specify what to do when a WebSocket Event occurs, annotate it with the corresponding annotation and the Servlet will do the rest for you.  ==%ws:connect(path)== Called directly after a successful WebSocket handshake. The <code>path</code> specifies the path which a client is connected to: <syntaxhighlight lang="xquery">declare %ws:connect('/') function local:connect() { };</syntaxhighlight> You can specify here how to handle your users, e. g. save a name as a WebSocket attribute. Furthermore, you can check header parameters for validity.  ==%ws:message(path, message)== Called when a client message arrives at the server. The <code>path</code> specifies the path which a client is connected to. The <code>message</code> string contains the name of the variable to which the message will be bound: <syntaxhighlight lang="xquery">declare %ws:message('/', '{$info}') function local:message($info) { };</syntaxhighlight> The value will be of type <code>xs:string</code> or <code>xs:base64Binary</code>. As there is no fixed message protocol, the client needs to take care of the message syntax. ==%ws:error(path, message)== Called when an error occurs. The <code>path</code> specifies the path which a client is connected to. The <code>message</code> string contains the name of the variable to which the message will be bound: <syntaxhighlight lang="xquery">declare %ws:error('/', '{$error}') function local:error($error) { };</syntaxhighlight> Usually, errors happen because of bad/malformed incoming packets. The WebSocket connection gets closed after the error handling. ==%ws:close(path)== Called when the WebSocket closes. The <code>path</code> specifies the path which a client is connected to:
If a Websocket Function is requested <syntaxhighlight lang="xquery">declare %ws:close(like connecting to the Path '/', message to the Path '/path', ...), the module directory and its sub-directories will be traversed, and all [[XQuery Extensions#Suffixes|XQuery files]] will be parsed for functions with Websocket annotations. Sub-directories that include an {function local:connect() {Code|.ignore}} the file will be skipped.;</syntaxhighlight>
To speed up processing, the functions of the existing XQuery modules are automatically cached in main memory:* Functions will The WebSocket is already closed when this annotation is called so there can be invalidated and parsed again if the timestamp of their module changesno return.
==Examples%ws:header-param(name, variable[, default])==
A first Websocket function is shown belowFor accessing connection-specific properties like the HTTP version. The value will be bound to the specified <code>variable</code>. If the property has no value, an optional <code>default</code> value will be assigned instead:
<pre classsyntaxhighlight lang="brush:xquery">module namespace page = 'http://basex.org/modules/web-page';import module namespace websocket = "http://basex.org/modules/Websocket";
declare
%ws:connectclose("/"'host', '{$host}') %ws:header-param('host', '{$host}')function pagelocal:connectclose( $host) { websocket admin:broadcastwrite-log('Connection was closed: ' || $host) json};</syntaxhighlight> The following parameters are available:serialize( {| class="wikitable" |- valign="top"! Name! Description|- valign="top"| <code>host</code>| The host of the request URI.|- valign="top"| <code>http-version</code>| The HTTP version used for the request.|- valign="top"| <code>is-secure</code>| Indicates if the connection is secure.|- valign="top"| <json typecode>origin</code>| The WebSocket origin.|- valign="objecttop"| <code>protocol-version</code> | The version of the used protocol.|- valign="top"| <typecode>Connectquery-string</typecode> | The query string of the request URI.|- valign="top"| <code>request-uri</jsoncode> )| The Request URI to use for this request.|- valign="top"| <code>sub-protocols</code> )| List of configured sub-protocols. |}; General information on the request can be retrieved via the [[Request Module]]. =Writing Applications= The [[WebSocket Module]] contains functions for interacting with other clients or manage specific clients. For example, you can store and access client-specific properties for a WebSocket connection or close the connection of clients. Note that one WebSocket connection can be opened per browser tab. In contrast, only one HTTP session exists for multiple tabs in in a browser. If you want to keep client-specific data on the web server, you can either store them in HTTP sessions or in the WebSocket connection. Note further that the results of functions annotated with <code>%ws:close</code> or <code>%ws:error</code> will not be transmitted to the client. Both annotations have rather been designed to gracefully close connections, write log data, remove clients from session data, etc. For keeping the connection alive it is recommendable to use heart-beats, and send regular pings to the server. There is no ideal timespan for sending pings: It should not be sent too often, but you should also consider possible network latencies. If your HTTP connection is secure, you should use the <code>wss</code> instead of the <code>ws</code> scheme. If you get the <code>[basex:ws] WebSocket connection required</precode>error, you may be attempting to call WebSocket functions from a non-WebSocket context. If you use a proxy server, check in the configuration if WebSockets are enabled. =Examples= ==Basic Example==
=Usage=* Enable the Websocket Servlet in the The following chapter explains how to create a simple basic web.xmlapplication with WebSockets. You can set here find another example in the maxIdleTime, maxTextMessageSize and maxBinaryMessageSize too.<pre class="brush:xml"><servlet> <servlet-name>wsservlet</servlet-name> <servlet-class>org.basex.http.ws.WsServlet</servlet-class> <init-param> <param-name>maxIdleTime</param-name> <param-value>100000</param-value> </init-param> <init-param> <param-name>maxTextMessageSize</param-name> <param-value>3000</param-value> </init-param></servlet><servlet-mapping> <servlet-name>wsservlet</servlet-name> <url-pattern>/ws/*</url-pattern></servlet-mapping></pre>* Annotate your specific XQuery-Functions with WebsocketAnnotations.* For using Websocket-Functions like broadcast or emit import the websocket-module: <BaseX source code>import module namespace websocket = "http://basex.org/modules/Websocket";</code>
=Annotations===websocket:connect(path)==Called when a Client-WebSocket-Connection successfully connected First of all, you have to ensure that the server. The <code>pathWsServlet</code> is enabled in your <code>web.xml</code> specifies file. It will be enabled if you use the Path the Client connected tostandard configuration of BaseX.
==websocket:message(pathFor establishing a connection to the WebSocket server,message)==Called when it is necessary that the server provides at least one function annotated with a Message arrives at WebSocket annotation. Let’s start by using the Server. The annotation <code>path%ws:connect('/')</code> specifies . In the connect function, a bidirectional communication with the Path client can be initialized: attributes such as the Client is id and name of a client can be set, or a welcome message can be emitted to other connected tousers, and so on. The <codesyntaxhighlight lang="xquery">messagedeclare %ws:connect('/')function example:connect() as empty-sequence() {};</codesyntaxhighlight> is the Message sent by the Client. Could be a Text-Message or a binary Message.
==websocket:close(path)==Called when The connect function is sufficient for creating the WebSocket closespersistent client/server connection. The In order to something sensible with the connection, you should implement a function annotated with <code>path%ws:message("/")</code> specifies the Path the Client is connected to.The WebSocket is already closed when this Annotation is called so there can be no return.:
<syntaxhighlight lang="xquery">import module namespace ws =websocket'http:error(path,message)==Called when an Error occurred. Usually, this happens because of bad/malformed incoming packets/basex. The <code>path<org/code> specifies the Path the Client is connected to. The <code>message<modules/code> is the Error-Message.The WebSocket gets closed after an error occurred.ws'
==websocketdeclare %ws:pathmessage(name'/',variable[,default]=='{$message}')function example:message( $message as xs:stringThe value of the first parameter will be assigned to the variable specified ) as the second parameter. The third parameter can be a default value. empty-sequence() { ws:emit($message)};</syntaxhighlight>
=Functions=In the function above, the [[WebSocket Module]] is imported, and the function <code>ws:emit</code> is used for forwarding the message to all connected clients.
==websocket:emit=={| width='100%'|The following client-| width='120' | '''Signatures'''|{{Func|websocket:emit|$message as xs:string/xsside code demonstrates a basic application of the WebSocket connection:base64Binary|empty-sequence()}}|-| '''Summary'''|Emits a <code>message</code> to all connected Members.|}
<syntaxhighlight lang==websocket:broadcast=="javascript">{| widthvar ws ='100%'|-| width='120' | '''Signatures'''|{{Func|websocketnew WebSocket("ws:broadcast|$message as xs//localhost:string8984/xs:base64Binary|empty-sequence(ws")}}|-| '''Summary'''|Broadcasts <code>message</code> to all connected Members exept to the caller.|};
ws.onmessage ==websocket:send==function(event) {| width='100%'|-| width='120' | '''Signatures'''|{{Func|websocket:send|$message as xs:string/xs:base64Binary, $id as xs:string |empty-sequence alert(event.data)}}|-| '''Summary'''|Sends a <code>message</code> to the user with the ID <code>$id</code>;|};
==websocket:id==function send(message) {| width='100%'|-| width='120' | '''Signatures''' ws.send(message);|{{Func|websocket:id||xs:string}};|-| '''Summary'''|Returns the ID of the current Websocket Connetion.|}</syntaxhighlight>
==websocket:ids=={| width='100%'|-| width='120' | '''Signatures'''|{{Func|websocket:ids||xs:The <code>send</code> function can be called to pass on a string*}}|-| '''Summary'''|Returns to the IDs of all current Websocket Connectionsserver.|}
==websocket:get=={| width='100%'|There are no heart-| width='120' | '''Signatures'''|{{Func|websocket:get|$key as xs:string|xs:string}}<br/>{{Func|websocket:get|$id as xs:string, $key as xs:string|xs:string}}|-| '''Summary'''|Returns the Websocket Attribute with the key <code>$key</code>beats in this example. If This means that the <code>$id</code> Parameter connection is set, it returns the Attribute of terminated if nothing happens for 5 minutes (standard timeout). It will also be closed if you send a Specific User with message that exceeds the ID <code>$id</code>|}standard text size.
==websocket:setChat Application=={| width='100%'|-| width='120' | '''Signatures'''|{{Func|websocket:set|$key as xs:string, $value as xs:string|empty-sequence()}}<br/>{{Func|websocket:set|$id as xs:string, $key as xs:string, $value as xs:string|empty-sequence()}}|-| '''Summary'''|Sets a Websocket Attribute with the key <code>$key</code> and the value $value. If the <code>$id</code> Parameter is set, the Attribute of a specific User with the ID <code>$id</code> is set.|}
==websocket:delete=={| width='100%'|-| width='120' | '''Signatures'''|{{Func|websocket:delete|$key as xs:string|empty-sequence()}}<br/>{{Func|websocket:delete|$id as xs:string, $key as xs:string|empty-sequence()}}|-| '''Summary'''|Removes a Session Attribute from In the current WebsocketClient. If the <code>$id</code> Parameter is setfull distributions of BaseX, the Attribute of you will find a specific User with the ID <code>$id</code> will little self-contained chat application that demonstrates how WebSockets can be deletedused in practice.|}
=Changelog=websocket:path=={| width='100%'|-| width='120' | '''Signatures'''|{{Func|websocket:path||xs:string}}<br/>{{Func|websocket:path|$id as xs:string|xs:string}}|-| '''Summary'''|Returns the Path of the current WebsocketClient. If the <code>$id</code> Parameter is set, the Path of a specific User with the ID <code>$id</code> will be returned.|}
=Parameters=* Http-WebSockets werre introduced with Version -> f9.e1.: ```%ws:param("Http-Version", "{$version}")```* Origin* Protocol-Version* QueryString* IsSecure* RequestURI* Host* Sec-WebSocket-Version* offset -> just for binary-Messages* len -> just for binary-Messages
Bureaucrats, editor, reviewer, Administrators
13,550

edits

Navigation menu