Skip to main content
Version: v20 R3 BETA

WebSocketServer

Historique
VersionModifications
v20Ajout

La classe WebSocketServer vous permet de créer et configurer un serveur WebSocket en 4D. Une fois le serveur WebSocket 4D actif, vous pouvez ouvrir et utiliser les connexions WebSocket entre 4D et les clients en utilisant la classe WebSocketConnection.

À propos des serveurs WebSocket

Le protocole WebSocket fournit un canal de communication full-duplex entre un serveur WebSocket et un client (par exemple un navigateur Web). Pour plus d'informations sur les serveurs WebSocket, lisez cette page sur Wikipedia.

Voir aussi

Voir également cet article de blog sur le serveur WebSocket 4D.

Conditions requises

Pour créer et gérer votre serveur WebSocket dans 4D, vous devrez utiliser deux classes intégrées à 4D :

  • cette classe (4D.WebSocketServer) pour gérer le serveur lui-même,
  • la classe 4D.WebSocketConnection pour gérer les connexions et les messages.

De plus, vous devrez créer deux classes utilisateurs qui contiendront les fonctions de callback :

  • une classe utilisateur pour gérer les connexions serveur,
  • une classe utilisateur pour gérer les messages.

Vous devez créer le serveur WebSocket au sein d'un worker pour maintenir la connexion active.

The 4D Web Server must be started.

Exemple

Dans cet exemple de base, notre serveur WebSocket renverra les messages en majuscules.

  1. Créez le serveur WebSocket en utilisant un worker (obligatoire) et passez votre classe de connexion serveur en tant que paramètre :
    // Créer une instance de la classe utilisateur
// qui gérera les connexions vers le serveur
var $handler: cs.myServerHandler
$handler := cs.myServerHandler.new()

CALL WORKER("WebSocketServer"; Formula(wss := 4D.WebSocketServer.new($handler)))
// attribuer une variable (wss) au WebSocket vous permet
// d'appeler wss.terminate() par la suite
  1. Définissez la classe utilisateur myServerHandler contenant la ou les fonction(s) de callback utilisée(s) pour gérer les connexions au serveur :
// Classe myServerHandler

Function onConnection($wss: Object; $event: Object): Object
// retourne une instance de la classe utilisateur
// qui traitera les messages
return cs.myConnectionHandler.new()
  1. Définissez la classe utilisateur myConnectionHandler contenant la ou les fonction(s) de callback utilisée(s) pour gérer les messages :
// Classe myConnectionHandler

Function onMessage($ws : 4D.WebSocketConnection; $message : Object)
// renvoie le message en majuscules
$ws.send(Uppercase($message.data))

Client-Side JS

Voir cet article de blog pour un exemple de code Javascript côté client gérant une connexion WebSocket.

Objet WebSocketServer

Les objets WebSocketServer offrent les propriétés et fonctions suivantes :

.connections : Collection    toutes les connexions courantes gérées par le serveur WebSocket
.dataType : Text    le type de données reçues ou envoyées
.handler : Object    l'accesseur qui récupère l'objet WSSHandler utilisé pour initier le serveur WebSocket
.path : Text    le modèle du chemin d'accès au serveur WebSocket
.terminate()    closes the WebSocket server
.terminated : Boolean    True si le serveur WebSocket est fermé

4D.WebSocketServer.new()

4D.WebSocketServer.new( WSSHandler : Object { ; options : Object } ) : 4D.WebSocketServer

ParamètresTypeDescription
WSSHandlerObject->Object of the user class declaring the WebSocket Server callbacks
optionsObject->WebSocket configuration parameters
Résultat4D.WebSocketServer<-New WebSocketServer object

|

The 4D.WebSocketServer.new() function creates and starts a WebSocket server that will use the specified WSSHandler callbacks and (optionally) options, and returns a 4D.WebSocketServer object.

Calling this function requires that the 4D Web Server is started. The host and port of the WebSocket server are the same as the host and port of the 4D Web Server.

WSSHandler parameter

In the WSSHandler parameter, pass an instance of a user class that will be called every time an event occurs on the WebSocket server --essentially, connection events. The class should define the following callback functions (only onConnection is mandatory):

PropriétéTypeDescriptionPar défaut
onConnectionFunction(mandatory) Callback when a new client connection is started (see below)undefined
onOpenFunctionCallback when the WebSocket server is started (see below)undefined
onTerminateFunctionCallback when the WebSocket server is terminated (see below)undefined
onErrorFunctionCallback when an error has occurred (see below)undefined

WSHandler.onConnection(WSServer : Object ; event : Object) : Object | null

ParamètresTypeDescription
WSServer4D.WebSocketServer<-Current WebSocket server object
evénementObject<-Paramètres
typeText"connection"
requestObjectrequest object. Contains information on the connection request (see below)
RésultatObject->connectionHandler object (see below). If this function returns a connectionHandler object, a 4D.WebSocketConnection object is automatically created and added to the collection of connections. This object is then received as parameter in each function of the connectionHandler object. If the returned value is null or undefined, the connection is cancelled.

This callback is called when the handshake is complete. It must be called with a valid connectionHandler object to create the WebSocket connection, otherwise the connection is cancelled.

WSHandler.onOpen(WSServer : Object ; event : Object)

ParamètresTypeDescription
WSServer4D.WebSocketServer<-Current WebSocket server object
evénementObject<-Paramètres
typeText"open"

Event emitted when the websocket server is started.

WSHandler.onTerminate(WSServer : Object ; event : Object)

ParamètresTypeDescription
WSServer4D.WebSocketServer<-Current WebSocket server object
evénementObject<-Paramètres
typeText"terminate"

Event emitted when the HTTP server or the WebSocket server is closed.

WSHandler.onError(WSServer : Object ; event : Object)

ParamètresTypeDescription
WSServer4D.WebSocketServer<-Current WebSocket server object
evénementObject<-Paramètres
typeText"error"
errorsCollectionCollection of 4D error stack in case of execution error
  • [].errCode (number) - 4D error code
  • [].message (text) - Description of the 4D error
  • [].componentSignature (text) - Signature of the internal component which returned the error
  • Event emitted when an error occurs on the WebSocket server.

    Example of WSSHandler class

    This example of a basic chat feature illustrates how to handle WebSocket server connections in a WSSHandler class.

    //myWSServerHandler class 

    Function onConnection($wss : Object; $event : Object) : Object

    If (VerifyAddress($event.request.remoteAddress))
    // The VerifyAddress method validates the client address
    // The returned WSConnectionHandler object will be used
    // by 4D to instantiate the 4D.WebSocketConnection object
    // related to this connection
    return cs.myConnectionHandler.new()
    // See connectionHandler object
    Else
    // The connection is cancelled
    return Null
    End if

    Function onOpen($wss : Object; $event : Object)
    LogFile("*** Server started")

    Function onTerminate($wss : Object; $event : Object)
    LogFile("*** Server closed")

    Function onError($wss : Object; $event : Object)
    LogFile("!!! Server error: "+$event.errors.first().message)

    request object

    A request object contains the following properties:

    ParamètresTypeDescription
    headersObjectThe client HTTP GET request. headers.key=value (value can be a collection if the same key appears multiple times)
    queryObjectObject that contains the URL parameters. For example, if parameters are: ?key1=value1&key2=value2 -> query.key1=value1, query.key2=value2
    urlTextcontains only the URL that is present in the actual HTTP request. Ex: GET /status?name=ryan HTTP/1.1 -> url="/status?name=ryan"
    remoteAddressTextIP Address of the client

    connectionHandler object

    As a result of the WSHandler.onConnection callback, pass a connectionHandler object, which is an instance of a user class that will be called every time an event occurs in the WebSocket connection --essentially, messages received. The class should define the following callback functions (only onMessage is mandatory):

    ParamètresTypeDescription
    onMessageFunction(mandatory) Function called when a new message is received from this connection
    onOpenFunctionFunction called when the 4D.WebSocketConnection is created
    onTerminateFunctionFunction called when this connection is terminated
    onErrorFunctionFunction called when an error occured

    connectionHandler.onMessage(ws : 4D.WebSocketConnection ; event : Object)

    ParamètresTypeDescription
    ws4D.WebSocketConnection<-Current WebSocket connection object
    evénementObject<-Paramètres
    typeText"message"
    dataTexte / Blob / Objetdata sent by the client

    This Callback for WebSocket data. Called each time the WebSocket receives data.

    connectionHandler.onOpen(ws : 4D.WebSocketConnection ; event : Object)

    ParamètresTypeDescription
    ws4D.WebSocketConnection<-Current WebSocket connection object
    evénementObject<-Paramètres
    typeText"open"

    Called when the connectionHandler object is created (after WSS.onConnection event).

    connectionHandler.onTerminate(ws : 4D.WebSocketConnection ; event : Object)

    ParamètresTypeDescription
    ws4D.WebSocketConnection<-Current WebSocket connection object
    evénementObject<-Paramètres
    typeText"terminate"
    codeNumberStatus code indicating why the connection has been closed. If the WebSocket does not return an error code, code is set to 1005 if no error occurred or to 1006 if there was an error.
    reasonTextString explaining why the connection has been closed. If the websocket doesn't return an reason, code is undefined

    Function called when the WebSocket is closed.

    connectionHandler.onError(ws : 4D.WebSocketConnection ; event : Object)

    ParamètresTypeDescription
    ws4D.WebSocketConnection<-Current WebSocket connection object
    evénementObject<-Paramètres
    typeText"error"
    errorsCollectionCollection of 4D errors stack in case of execution error
  • [].errCode (number) - 4D error code
  • [].message (text) - Description of the 4D error
  • [].componentSignature (text) - Signature of the internal component which returned the error
  • Function called when an error has occurred.

    Example of connectionHandler class

    This example of a basic chat feature illustrates how to handle messages in a connectionHandler class.

    // myConnectionHandler Class

    Function onMessage($ws : 4D.WebSocketConnection; $message : Object)
    // Resend the message to all chat clients
    This.broadcast($ws;$message.data)

    Function onOpen($ws : 4D.WebSocketConnection; $message : Object)
    // Send a message to new connected users
    $ws.send("Welcome on the chat!")
    // Send "New client connected" message to all other chat clients
    This.broadcast($ws;"New client connected")

    Function onTerminate($ws : 4D.WebSocketConnection; $message : Object)
    // Send "Client disconnected" message to all other chat clients
    This.broadcast($ws;"Client disconnected")

    Function broadcast($ws : 4D.WebSocketConnection; $message:text)
    var $client:4D.WebSocketConnection
    // Resend the message to all chat clients
    For each ($client; $ws.wss.connections)
    // Check that the id is not the current connection
    If ($client.id#$ws.id)
    $client.send($message)
    End if
    End for each

    options parameter

    In the optional options parameter, pass an object that contains the following properties:

    PropriétéTypeDescriptionPar défaut
    pathTextRepresents the path to access the WebSocket server. If no path is defined, the WebSocket server manages all the connectionsundefined
    dataTypeTextType of the data received through the connectionHandler.onMessage and the data send by WebSocketConnection.send() function. Values: "text", "blob","object"). If "object": (send) transforms object into a json format and sends it; (reception): receives json format and transforms it into objecttext

    .connections

    .connections : Collection

    Description

    La propriété .connections contient toutes les connexions courantes gérées par le serveur WebSocket. Chaque élément de la collection est un objet WebSocketConnection.

    When a connection is terminated, its status changes to "Closed" and it is removed from this collection.

    .dataType

    .dataType : Text

    Description

    La propriété .dataType contient le type de données reçues ou envoyées.

    Cette propriété est en lecture seule.

    .handler

    .handler : Object

    Description

    La propriété .handler contient l'accesseur qui récupère l'objet WSSHandler utilisé pour initier le serveur WebSocket.

    .path

    .path : Text

    Description

    La propriété .path contient le modèle du chemin d'accès au serveur WebSocket. Si aucun chemin n'a été défini, le serveur WebSocket gère toutes les connexions.

    Cette propriété est en lecture seule.

    .terminate()

    .terminate()

    ParamètresTypeDescription
    Ne requiert aucun paramètre

    |

    Description

    La fonction .terminate() closes the WebSocket server.

    .terminated

    .terminated : Boolean

    Description

    La propriété .terminated contient True si le serveur WebSocket est fermé.

    Cette propriété est en lecture seule.