WebSocket
The WebSocket
class allows you to open a WebSocket client connection with a server, send and receive data, and close the connection.
Las conexiones cliente WebSocket son útiles, por ejemplo, para recibir datos financieros en tiempo real o enviar y recibir mensajes de un chat.
Historia
Lanzamiento | Modificaciones |
---|---|
20 R2 | Añadidos |
Ejemplo
En este ejemplo, creamos un cliente WebSocket muy básico.
- 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")
- Conécte al servidor WebSocket desde un formulario 4D instanciando un 4D.WebSocket:
Form.webSocket:=4D.WebSocket.new($wssUrl; cs.WSConnectionHandler.new())
- Para enviar mensajes al servidor WebSocket desde el formulario 4D, puede escribir:
Form.webSocket.send("Hello world")
Objeto WebSocket
Los objetos WebSocket ofrecen las siguientes propiedades y funciones:
.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()
Historia
Lanzamiento | Modificaciones |
---|---|
20 R3 | Support of headers property in connectionHandler |
4D.WebSocket.new( url : Text { ; connectionHandler : Object } ) : 4D.WebSocket
Parámetros | Tipo | Descripción | |
---|---|---|---|
url | Text | -> | URL a la que conectarse |
connectionHandler | Object | -> | Objeto que declara las retrollamadas WebSocket |
Result | 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. Se pueden utilizar los siguientes patrones de URL:
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.
- Las retrollamadas se llaman automáticamente en el contexto del formulario o worker que inicia la conexión.
- El WebSocket será válido siempre y cuando el formulario o trabajador no esté cerrado.
Propiedad | Tipo | Descripción |
---|---|---|
onMessage | Function | Función de retrollamada para datos WebSocket. Llamada cada vez que el WebSocket ha recibido datos. The callback receives the following parameters:$1 : WebSocket object$2 : Object
|
onError | Function | Función de retrollamada para errores de ejecución. The callback receives the following parameters:$1 : WebSocket object$2 : Object
|
onTerminate | Function | Función de retrollamada cuando el WebSocket se termina. The callback receives the following parameters:$1 : WebSocket object$2 : Object
|
onOpen | Function | Función de retrollamada cuando el webSocket está abierto. The callback receives the following parameters:$1 : WebSocket object$2 : Object
|
dataType | Text | Tipo de datos recibidos o enviados. Valores disponibles: "text" (por defecto), "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*{; ... } }" |
Esta es la secuencia de llamadas de retorno:
onOpen
se ejecuta una vez- Zero or several
onMessage
are executed - Zero or one
onError
is executed (stops the processing) onTerminate
is always executed
Ejemplo
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
Descripción
The .dataType
property contains the type of the response body content. Puede ser "text", "blob" u "object".
Esta propiedad es de sólo lectura.
.handler
.handler : Object
Descripción
The .handler
property contains the accessor that gets the connectionHandler
object used to initiate the connection.
Esta propiedad es de sólo lectura.
.id
.id : Longint
Descripción
The .id
property contains the unique identifier of the connection.
Esta propiedad es de sólo lectura.
.send()
.send( message : Text )
.send( message : Blob )
.send( message : Object )
Parámetros | Tipo | Descripción | |
---|---|---|---|
message | Text, Blob, Object | -> | Mensaje a enviar |
Descripción
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:
Tipo | Contenido |
---|---|
Text | Texto en UTF-8 |
Blob | Datos binarios |
Object | Text in JSON UTF-8 (same result as with JSON Stringify ) |
.status
.status : Text
Descripción
The .status
property contains the current connection status (can be "Connecting", "Closing", "Closed", or "Connected").
Esta propiedad es de sólo lectura.
.terminate()
.terminate( { code : Integer { ; reason : Text } } )
Parámetros | Tipo | Descripción | |
---|---|---|---|
code | Integer | -> | Código de estado que explica por qué se cierra la conexión |
reason | Text | -> | La razón por la que se cierra la conexión |
Descripción
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):
- Si no se especifica, el código de cierre de la conexión se establece automáticamente en 1000 para un cierre normal o, en caso contrario, en otro valor estándar del rango 1001-1015 que indique la razón real por la que se cerró la conexión.
- Si se especifica, el valor de este parámetro de código anula el ajuste automático. El valor debe ser un número entero. O 1000, o un código personalizado en el rango 3000-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
Descripción
The .url
property contains the URL to which the WebSocket has connected. It is the URL you passed to the new()
function.
Esta propiedad es de sólo lectura.