Saltar para o conteúdo principal
Versão: 20 R5 BETA

WebSocket

The WebSocket class allows you to open a WebSocket client connection with a server, send and receive data, and close the connection.

As ligações cliente WebSocket são úteis, por exemplo, para receber dados financeiros em tempo real ou enviar e receber mensagens de um chat.

História
ReleaseMudanças
20 R2Adicionado

Exemplo

Neste exemplo, criamos um cliente WebSocket muito básico.

  1. 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")
  1. Conecte-se ao servidor WebSocket a partir de um formulário 4D instanciando um 4D.WebSocket:
Form.webSocket:=4D.WebSocket.new($wssUrl; cs.WSConnectionHandler.new())
  1. Para enviar mensagens para o servidor WebSocket a partir do formulário 4D, pode escrever:
Form.webSocket.send("Hello world")

Objeto WebSocket

Os objetos WebSocket fornecem as seguintes propriedades e funções:

.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()

História
ReleaseMudanças
20 R3Support of headers property in connectionHandler

4D.WebSocket.new( url : Text { ; connectionHandler : Object } ) : 4D.WebSocket

ParâmetroTipoDescrição
urlText->URL a que se deve ligar
connectionHandlerObject->Objeto que declara as chamadas de retorno WebSocket
Resultados4D.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. Podem ser utilizados os seguintes padrões de URL:

  • ws://host[:port]path[?query] for standard connections
  • wss://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.

  • As chamadas de retorno são chamadas automaticamente no contexto do formulário ou do worker que inicia a ligação.
  • The WebSocket will be valid as long as the form or worker is not closed.
PropriedadeTipoDescrição
onMessageFunctionFunção de retorno de chamada para dados WebSocket. Chamado sempre que o WebSocket tiver recebido dados. The callback receives the following parameters:
  • $1: WebSocket object
  • $2: Object
    • $2.type (text): always "message"
    • $2.data (text, blob, or object, see dataType): Received data
    onErrorFunctionFunção de retorno de chamada para erros de execução. The callback receives the following parameters:
  • $1: WebSocket object
  • $2: Object
    • $2.type (text): always "error"
    • $2.errors: collection 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
    onTerminateFunctionFunção de retorno de chamada quando o WebSocket é terminado. The callback receives the following parameters:
  • $1: WebSocket object
  • $2: Object
    • $2.code (number, read-only): unsigned short containing the close code sent by the server.
    • $2.reason (text, read-only): Reason why the server closed the connection. This is specific to the particular server and sub-protocol.
    • $2.wasClean (boolean, read-only): Indicates whether or not the connection was cleanly closed.
    onOpenFunctionFunção de retorno de chamada quando o websocket está aberto. The callback receives the following parameters:
  • $1: WebSocket object
  • $2: Object
    • $2.type (text): always "open"
    dataTypeTextTipo de dados recebidos ou enviados. Valores disponíveis: "text" (padrão), "blob", "object". "text" = utf-8
    headersObjectHeaders of the WebSocket.
  • Syntax for standard key assignment: headers.*key*:=*value* (value can be a Collection if the same key appears multiple times)
  • Syntax for Cookie assignment (particular case): headers.Cookie:="*name*=*value* {; *name2*=*value2*{; ... } }"
  • Aqui está a sequência de chamadas de retorno:

    1. onOpen is executed once
    2. Zero or several onMessage are executed
    3. Zero or one onError is executed (stops the processing)
    4. onTerminate is always executed

    Exemplo

    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

    Descrição

    The .dataType property contains the type of the response body content. Pode ser "text", "blob" ou "object".

    Esta propriedade é só de leitura.

    .handler

    .handler : Object

    Descrição

    The .handler property contains the accessor that gets the connectionHandler object used to initiate the connection.

    Esta propriedade é só de leitura.

    .id

    .id : Longint

    Descrição

    The .id property contains the unique identifier of the connection.

    Esta propriedade é só de leitura.

    .send()

    .send( message : Text )
    .send( message : Blob )
    .send( message : Object )

    ParâmetroTipoDescrição
    messageText, Blob, Object->Mensagem a enviar

    Descrição

    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:

    TipoConteúdo
    TextTexto em UTF-8
    BlobDados binários
    ObjectText in JSON UTF-8 (same result as with JSON Stringify)

    .status

    .status : Text

    Descrição

    The .status property contains the current connection status (can be "Connecting", "Closing", "Closed", or "Connected").

    Esta propriedade é só de leitura.

    .terminate()

    .terminate( { code : Integer { ; reason : Text } } )

    ParâmetroTipoDescrição
    codeInteger->Código de estado que explica porque é que a ligação está a ser encerrada
    reasonText->O motivo pelo qual a ligação está a fechar

    Descrição

    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):

    • If unspecified, a close code for the connection is automatically set to 1000 for a normal closure, or otherwise to another standard value in the range 1001-1015 that indicates the actual reason the connection was closed.
    • Se especificado, o valor desse parâmetro de código substitui a configuração automática. O valor deve ser um número inteiro. Ou 1000, ou um código personalizado no intervalo 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

    Descrição

    The .url property contains the URL to which the WebSocket has connected. It is the URL you passed to the new() function.

    Esta propriedade é só de leitura.