WebSocket
The WebSocket
class allows you to open a WebSocket client connection with a server, send and receive data, and close the connection.
Les connexions clientes WebSocket sont utiles, par exemple, pour recevoir des données financières en temps réel ou pour envoyer et recevoir des messages à partir d'une messagerie instantanée.
Historique
Release | Modifications |
---|---|
20 R2 | Ajout |
Exemple
Dans cet exemple, nous créons un client WebSocket très basique.
- Create the
WSConnectionHandler
user class containing callback function(s) used to handle WebSocket event callbacks:
// WSConnectionHandler class
Class constructor
Function onMessage($ws : 4D.WebSocket; $event : Object)
ALERT($event.data)
Function onTerminate($ws : 4D.WebSocket; $event : Object)
ALERT("Connection closed")
- Connexion au serveur WebSocket à partir d'un formulaire 4D en instanciant un 4D.WebSocket :
Form.webSocket:=4D.WebSocket.new($wssUrl; cs.WSConnectionHandler.new())
- Pour envoyer des messages au serveur WebSocket à partir du formulaire 4D, vous pouvez écrire :
Form.webSocket.send("Hello world")
Objet WebSocket
Les objets WebSocket exposent les propriétés et fonctions suivantes :
.dataType : Text the type of the response body content |
.handler : Object the accessor that gets the connectionHandler object used to initiate the connection |
.id : Longint the unique identifier of the connection |
.send( message : Text ) .send( message : Blob ) .send( message : Object ) sends message to the WebSocket server in the defined data type (Text, Blob, or Object) |
.status : Text the current connection status (can be "Connecting", "Closing", "Closed", or "Connected") |
.terminate( { code : Integer { ; reason : Text } } ) closes the WebSocket connection, along with optional code and reason parameters |
.url : Text the URL to which the WebSocket has connected |
4D.WebSocket.new()
Historique
Release | Modifications |
---|---|
20 R3 | Support of headers property in connectionHandler |
4D.WebSocket.new( url : Text { ; connectionHandler : Object } ) : 4D.WebSocket
Paramètres | Type | Description | |
---|---|---|---|
url | Text | -> | URL à laquelle se connecter |
connectionHandler | Object | -> | Objet déclarant les callbacks WebSocket |
Résultat | 4D.WebSocket | <- | New WebSocket object |
The 4D.WebSocket.new()
function creates and returns a new 4D.WebSocket
object connected to the WebSocket server at the address you passed in url. The 4D.WebSocket
object provides an API for creating and managing a WebSocket connection to a server, as well as sending and receiving data to and from the server.
In url, pass the URL to which the WebSocket server will respond. Les modèles d'URL suivants peuvent être utilisés :
ws://host[:port]path[?query]
for standard connectionswss://host[:port]path[?query]
for TLS secured connections
If the connection is not possible, a null
object is returned and an error is generated (that you can intercept using a method installed with ON ERR CALL
).
connectionHandler parameter
In connectionHandler, you can pass an object containing callback functions to be called according to connection events, as well as data type and headers to handle.
- Les callbacks sont automatiquement appelées dans le contexte du formulaire ou du worker qui initie la connexion.
- La WebSocket reste valide tant que le formulaire ou le worker n'est pas fermé.
Propriété | Type | Description |
---|---|---|
onMessage | Function | Fonction de callback pour les données WebSocket. Appelée à chaque fois que le WebSocket a reçu des données. The callback receives the following parameters:$1 : WebSocket object$2 : Object
|
onError | Function | Fonction de callback pour les erreurs d'exécution. The callback receives the following parameters:$1 : WebSocket object$2 : Object
|
onTerminate | Function | Fonction de callback lorsque la WebSocket est terminée. The callback receives the following parameters:$1 : WebSocket object$2 : Object
|
onOpen | Function | Fonction de callback lorsque la WebSocket est ouverte. The callback receives the following parameters:$1 : WebSocket object$2 : Object
|
dataType | Text | Type de données reçues ou envoyées. Valeurs disponibles : "text" (par défaut), "blob", "object". "text" = utf-8 |
headers | Object | Headers of the WebSocket.headers.*key*:=*value* (value can be a Collection if the same key appears multiple times)headers.Cookie:="*name*=*value* {; *name2*=*value2*{; ... } }" |
Voici la séquence des appels de callbacks :
onOpen
is executed once- Zero or several
onMessage
are executed - Zero or one
onError
is executed (stops the processing) onTerminate
is always executed
Exemple
You want to set headers in the WSConnectionHandler
user class:
// WSConnectionHandler class
Class constructor($myToken:Text)
// Creation of the headers sent to the server
This.headers:=New object("x-authorization";$myToken)
// We define two cookies
This.headers.Cookie:="yummy_cookie=choco; tasty_cookie=strawberry"
...
.dataType
.dataType : Text
Description
The .dataType
property contains the type of the response body content. Peut être "text", "blob" ou "object".
Cette propriété est en lecture seule.
.handler
.handler : Object
Description
The .handler
property contains the accessor that gets the connectionHandler
object used to initiate the connection.
Cette propriété est en lecture seule.
.id
.id : Longint
Description
The .id
property contains the unique identifier of the connection.
Cette propriété est en lecture seule.
.send()
.send( message : Text )
.send( message : Blob )
.send( message : Object )
Paramètres | Type | Description | |
---|---|---|---|
message | Text, Blob, Object | -> | Message à envoyer |
Description
The .send()
function sends message to the WebSocket server in the defined data type (Text, Blob, or Object).
The following contents are sent depending on the message type:
Type | Contenu |
---|---|
Text | Texte en UTF-8 |
Blob | Données binaires |
Object | Text in JSON UTF-8 (same result as with JSON Stringify ) |
.status
.status : Text
Description
The .status
property contains the current connection status (can be "Connecting", "Closing", "Closed", or "Connected").
Cette propriété est en lecture seule.
.terminate()
.terminate( { code : Integer { ; reason : Text } } )
Paramètres | Type | Description | |
---|---|---|---|
code | Integer | -> | Code de statut indiquant la cause de la fermeture de la connexion |
reason | Text | -> | Cause de la fermeture de la connexion |
Description
The .terminate()
function closes the WebSocket connection, along with optional code and reason parameters.
In code, you can pass a status code explaining why the connection is being closed (see also WebSocket Connection Close Code in the RFC6455):
- S'il n'est pas spécifié, le code de fermeture de la connexion est automatiquement fixé à 1000 pour une fermeture normale, ou à une autre valeur standard dans la plage 1001-1015 qui indique la raison réelle de la fermeture de la connexion.
- Si elle est spécifiée, la valeur de ce paramètre de code remplace le réglage automatique. La valeur doit être un nombre entier. Soit 1000, soit un code personnalisé compris entre 3000 et 4999. If you specify a code value, you should also specify a reason value.
In reason, you can pass a string describing why the connection is being closed.
.url
.url : Text
Description
The .url
property contains the URL to which the WebSocket has connected. It is the URL you passed to the new()
function.
Cette propriété est en lecture seule.