Changes

Jump to navigation Jump to search
2,978 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.
Use WebSockets if you have to exchange data with a high frequency or if you have to send messages from Please note that the server to the client without techniques like Pollingcurrent WebSocket implementation relies on Jetty’s WebSocket servlet API. Other web servers may be supported in future versions.
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. In contrast to the HTTP protocol, a connection will be kept alive, and a server can send unsolicited data to the client.=Introduction=
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. The timeout can be specified in the <code>web.xml</code> configuration file. It is possible to transmit all kind of data, binary or text. ==Protocol==
=Introduction=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==
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]].
=Usage=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.
* Enable the WebSocket servlet in the <code>web.xml</code>. You can set the maxIdleTime==%ws:error(path, maxTextMessageSize and maxBinaryMessageSize here too.* If you get a message that exceeds the maxTextMessageSize/maxBinaryMessageSize or, if not set, the default messageSize of Jetty of 65 536 bytes (64 kB) then the connection will be closed. In this case, the <code>ws:error</code> annotation will be called. ==
Called when an error occurs. The <pre class="brush:xml"code><servlet> <servlet-name>wsservletpath</servlet-name> <servlet-classcode>orgspecifies the path which a client is connected to.basex.http.ws.WsServlet</servlet-class> <init-param> <param-name>maxIdleTime</param-name> <param-value>100000The </param-valuecode> message</init-paramcode> <init-param> <param-string contains the 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.of the variable to which the message will be bound:
<syntaxhighlight lang=Annotations"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: <syntaxhighlight lang="xquery">declare %ws:close('/') function local:connect() { };</syntaxhighlight>
==ws:connect(path)==The WebSocket is already closed when this annotation is called so there can be no return.
Called directly after a successful WebSocket handshake. The <code>path</code> specifies the path to which a client is connected to.==%ws:header-param(name, variable[, default])==
==wsFor 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:message(path,message)==
Called when a <codesyntaxhighlight lang="xquery">message</code> arrives at the server. The <code>pathdeclare %ws:close('host', '{$host}') %ws:header-param('host', '{$host}')function local:close($host) { admin:write-log('Connection was closed: ' || $host)};</codesyntaxhighlight> specifies the path to which a client is connected to. The <code>message</code> is the <code>message</code> sent by the client. Could be a text-message or a binary-message.
==wsThe following parameters are available:close(path)==
Called when {| class="wikitable" |- valign="top"! Name! Description|- valign="top"| <code>host</code>| The host of the WebSocket closesrequest URI. |- valign="top"| <code>http-version</code>| The HTTP version used for the request.|- valign="top"| <code>pathis-secure</code> specifies | Indicates if the path to which a client connection is connected tosecure.|- valign="top"| <code>origin</code>| The WebSocket is already closed when origin.|- valign="top"| <code>protocol-version</code>| The version of the used protocol.|- valign="top"| <code>query-string</code>| The query string of the request URI.|- valign="top"| <code>request-uri</code>| The Request URI to use for this annotation is called so there can be no returnrequest.|- valign="top"| <code>sub-protocols</code>| List of configured sub-protocols.|}
==ws:error(path, message)==General information on the request can be retrieved via the [[Request Module]].
Called when an error has occurred. Usually, this happens because of bad/malformed incoming packets. The <code>path</code> specifies the path to which a client is connected to. The <code>message</code> is the error message. The WebSocket connection gets closed after the error handling.=Writing Applications=
==ws:header-param(name,variableThe [[WebSocket Module]] contains functions for interacting with other clients or manage specific clients. For example,default]==you can store and access client-specific properties for a WebSocket connection or close the connection of clients.
For accessing 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 parameters like data on the Http-Version web server, you can either store them in HTTP sessions or in the Sec-WebSocket-Versionconnection.
=Parameters=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.
* HttpFor keeping the connection alive it is recommendable to use heart-Version -> fbeats, and send regular pings to the server.e.: <code>%wsThere is no ideal timespan for sending pings:param("Http-Version"It should not be sent too often, "{$version}")</code>* Origin* Protocol-Version* QueryString* IsSecure* RequestURI* Host* Sec-WebSocket-Version* offset -> just for binary-Messages* len -> just for binary-Messagesbut you should also consider possible network latencies.
=Tipps=If your HTTP connection is secure, you should use the <code>wss</code> instead of the <code>ws</code> scheme.
* For interacting with other clients or manage specific clients If you should check out get the [[WebSocket Module]] as well.* The results of functions annotated with <code>%[basex:ws:close] WebSocket connection required</code> or <code>%ws:error</code> will not , you may be transmitted attempting to the client* For keeping the connection alive it is possible to implement heartcall WebSocket functions from a non-beats * Use <code>wss</code> instead of <code>ws</code> for a secure WebSocket connection* context. If you use a proxy server, check its in the configuration if WebSocket support is WebSockets are enabled.
=ExampleExamples=The following chapter explains how to create a simple basic webapplication with websockets. You can find another example in the BaseX source code. First of all include the WsServlet in your <code>web.xml</code>.
<pre class="brush:xml"><?xml version="1.0" encodingBasic Example="UTF-8"?><web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <display-name>BaseX: The XML Database and XQuery Processor</display-name> <description>HTTP Services</description> <!-- Global session and servlet listener --> <listener> <listener-class>org.basex.http.SessionListener</listener-class> </listener> <listener> <listener-class>org.basex.http.ServletListener</listener-class> </listener>
<!-- WebSocket Service (The following chapter explains how to create a simple basic web application with WebSockets. You can be disabled by removing this entry) --> <servlet> <servlet-name>WebSocket</servlet-name> <servlet-class>org.basex.http.wsfind another example in the BaseX source code.WsServlet</servlet-class> <init-param> <param-name>maxTextMessageSize</param-name> <param-value>3000</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>WebSocket</servlet-name> <url-pattern>/ws/*</url-pattern> </servlet-mapping>
<!-- Mapping for static resources (may be restricted First of all, you have to a sub path) --> <servlet> <servlet-name>default</servlet-name> <init-param> <param-name>useFileMappedBuffer</param-name> <param-value>false</param-value> ensure that the </init-paramcode> WsServlet</servlet> <servlet-mappingcode> is enabled in your <servlet-namecode>default</servlet-name> <url-pattern>/static/*</url-pattern> </servlet-mapping></web-app>.xml</precode>file. It will be enabled if you use the standard configuration of BaseX.
For establishing a connection to the WebSocket server , it is necessary that the server provides at least a one function annotated with a WebSocket annotation. Let’s start by using the annotation <code>%ws:connect("'/"')</code>.The In the connect function , a bidirectional communication with the client can set WebSocket specific be initialized: attributes like such as the id and nameof a client can be set, emit or a welcome message can be emitted to other connected users, write database entries, do nothing, ..and so on. <pre classsyntaxhighlight lang="brush:xquery">
declare
%ws:connect('/')
function example:connect() as empty-sequence() {
()
};
</presyntaxhighlight>
With The connect function is sufficient for creating the state until now you can create a connection between persistent client and /serverconnection. For doing sth. senseful In order to something sensible with the WebSocket connection , you should implement a function annotated with <code>%ws:message("/")</code>.: <pre classsyntaxhighlight lang="brush:xquery">
import module namespace ws = 'http://basex.org/modules/ws'
 
declare
%ws:message('/', '{$message}')
ws:emit($message)
};
</presyntaxhighlight> In the function above , the [[WebSocket Module]] is imported, and the WebSocketModule function <code>ws:emit</code> is used for forwarding the message to all connected clients. Notice that you have to import  The following client-side code demonstrates a basic application of the [[WebSocket Module]] before using it. connection:
It is possible now to write client functions which connect to a WebSocket, send messages to the WebSocket and receive messages from the WebSocket. <syntaxhighlight lang="javascript">The following client example provides basic code for handling the var ws = new WebSocket connection.("ws://localhost:8984/ws");
<pre>
var ws = new WebSocket("wss://localhost:8984/ws");
ws.onmessage = function(event) {
alert(event.data);
ws.send(message);
};
</presyntaxhighlightThe <code>send</code> function can be called to pass on a string to the server. There are no heart-beats in this example. This means that the connection is terminated if nothing happens for 5 minutes (standard timeout). It will also be closed if you send a message that exceeds the standard text size. ==Chat Application== In the full distributions of BaseX, you will find a little self-contained chat application that demonstrates how WebSockets can be used in practice. =Changelog=
There are no heart-beats in this exampleWebSockets werre introduced with Version 9. This means that the connection is terminated if nothing happens for 5 minutes (standard timeout).If you send a message which exceeds the textsize of 3kb defined in the <code>web.xml</code> the connection gets closed too1.
Bureaucrats, editor, reviewer, Administrators
13,550

edits

Navigation menu