TCPConnection
The TCPConnection
class allows you to manage Transmission Control Protocol (TCP) client connections to a server, enabling you to send and receive data, and handle connection lifecycle events using callbacks.
The TCPConnection
class is available from the 4D
class store. Puede crear una conexión TCP utilizando la función 4D.TCPConnection.new() que devuelve un TCPConnection object.
All TCPConnection
class functions are thread-safe.
Thanks to the standard 4D object refcounting, a TCPConnection is automatically released when it is no longer referenced. Consequently, the associated resources, are properly cleaned up without requiring explicit closure.
TCPConnection objects are released when no more references to them exist in memory. This typically occurs, for example, at the end of a method execution for local variables. If you want to "force" the closure of a connection at any moment, nullify its references by setting them to Null.
Historia
Lanzamiento | Modificaciones |
---|---|
20 R9 | New listener , address , and port attributes |
20 R8 | Clase añadida |
Ejemplos
The following examples demonstrate how to use the 4D.TCPConnection and 4D.TCPEvent classes to manage a TCP client connection, handle events, send data, and properly close the connection. Both synchronous and asynchronous examples are provided.
Ejemplo sincrónico
This example shows how to establish a connection, send data, and shut it down using a simple object for configuration:
var $domain : Text := "127.0.0.1"
var $port : Integer := 10000
var $options : Object := New object() // Configuration object
var $tcpClient : 4D.TCPConnection
var $message : Text := "test message"
// Open a connection
$tcpClient := 4D.TCPConnection.new($domain; $port; $options)
// Send data
var $blobData : Blob
TEXT TO BLOB($message; $blobData; UTF8 text without length)
$tcpClient.send($blobData)
// Shutdown
$tcpClient.shutdown()
$tcpClient.wait(0)
Ejemplo asincrónico
This example defines a class that handles the connection lifecycle and events, showcasing how to work asynchronously:
// Class definition: cs.MyAsyncTCPConnection
Class constructor($url : Text; $port : Integer)
This.connection := Null
This.url := $url
This.port := $port
// Connect to one of the servers launched inside workers
Function connect()
This.connection := 4D.TCPConnection.new(This.url; This.port; This)
// Disconnect from the server
Function disconnect()
This.connection.shutdown()
This.connection := Null
// Send data to the server
Function getInfo()
var $blob : Blob
TEXT TO BLOB("Information"; $blob)
This.connection.send($blob)
// Callback called when the connection is successfully established
Function onConnection($connection : 4D.TCPConnection; $event : 4D.TCPEvent)
ALERT("Connection established")
// Callback called when the connection is properly closed
Function onShutdown($connection : 4D.TCPConnection; $event : 4D.TCPEvent)
ALERT("Connection closed")
// Callback called when receiving data from the server
Function onData($connection : 4D.TCPConnection; $event : 4D.TCPEvent)
ALERT(BLOB to text($event.data; UTF8 text without length))
//Warning: There's no guarantee you'll receive all the data you need in a single network packet.
// Callback called when the connection is closed unexpectedly
Function onError($connection : 4D.TCPConnection; $event : 4D.TCPEvent)
ALERT("Connection error")
// Callback called after onShutdown/onError just before the TCPConnection object is released
Function onTerminate($connection : 4D.TCPConnection; $event : 4D.TCPEvent)
ALERT("Connection terminated")
Ejemplo de uso
Create a new method named AsyncTCP, to initialize and manage the TCP connection:
var $myObject : cs.MyAsyncTCPConnection
$myObject := cs.MyAsyncTCPConnection.new("myURL"; 10000)
$myObject.connect()
$myObject.getInfo()
$myObject.disconnect()
Call the AsyncTCP method in a worker:
CALL WORKER("new process"; "Async_TCP")
Objeto TCPConnection
A TCPConnection object is a non-sharable object.
TCPConnection objects provide the following properties and functions:
address : Text the IP addess or domain name of the remote machine |
closed : Boolean si la conexión está cerrada |
errors : Collection una colección de objetos de error asociados a la conexión |
listener : Object the TCPListener object that created the TCPConnection , if any |
noDelay : Boolean si el algoritmo de Nagle está desactivado ( true ) o activado (false ) |
port : Number the port number of the remote machine |
.send( data : Blob ) envía datos al servidor |
.shutdown() cierra el canal write de la conexión (cliente a servidor) |
.wait( { timeout : Real } ) espera hasta que se cierre la conexión TCP o se alcance el timeout especificado |
4D.TCPConnection.new()
4D.TCPConnection.new( serverAddress : Text ; serverPort : Number ; options : Object ) : 4D.TCPConnection
Parámetros | Tipo | Descripción | |
---|---|---|---|
serverAddress | Text | -> | Domain name or IP address of the server |
serverPort | Integer | -> | Número de puerto del servidor |
options | Object | -> | Configuración opciones para la conexión |
Resultado | TCPConnection | <- | New TCPConnection object |
Descripción
La función 4D.TCPConnection.new()
crea una nueva conexión TCP a la serverAddress y serverPort especificados, usando las opciones definidas, y devuelve un objeto 4D.HTTPRequest
.
Parámetro options
En el parámetro options, pase un objeto que puede contener las siguientes propiedades:
Propiedad | Tipo | Descripción | Por defecto |
---|---|---|---|
onConnection | Formula | Callback triggered when the connection is established. | Indefinido |
onData | Formula | Callback triggered when data is received | Indefinido |
onShutdown | Formula | Callback triggered when the connection is properly closed | Indefinido |
onError | Formula | Callback triggered in case of an error | Indefinido |
onTerminate | Formula | Callback triggered just before the TCPConnection is released | Indefinido |
noDelay | Boolean | Read-only Disables Nagle's algorithm if true | False |
Función callback (retrollamada)
All callback functions receive two parameters:
Parámetros | Tipo | Descripción |
---|---|---|
$connection | objeto TCPConnection | The current TCP connection instance. |
$event | objeto TCPEvent | Contains information about the event. |
Sequence of Callback Calls:
onConnection
is triggered when the connection is established.onData
is triggered each time data is received.- Either
onShutdown
oronError
is triggered:onShutdown
is triggered when the connection is properly closed.onError
is triggered if an error occurs.
onTerminate
is always triggered just before the TCPConnection is released (connection is closed or an error occured).
Objeto TCPEvent
Un objeto TCPEvent
es devuelto cuando se llama una función de retrollamada.
.dirección
address : Text
Descripción
The .address
property contains the IP addess or domain name of the remote machine.
.closed
closed : Boolean
Descripción
La propiedad .closed
contiene si la conexión está cerrada. Returns true
if the connection is closed, either due to an error, a call to shutdown()
, or closure by the server.
.errors
errors : Collection
Descripción
La propiedad .errors
contiene una colección de objetos de error asociados a la conexión. Each error object includes the error code, a description, and the signature of the component that caused the error.
Propiedad | Tipo | Descripción | |
---|---|---|---|
errors | Collection | Pila de error 4D en caso de error | |
[].errCode | Number | Código de error 4D | |
[].message | Text | Descripción del error 4D | |
[].componentSignature | Text | Firma del componente interno que ha devuelto el error |
.listener
listener : Object
Descripción
The .listener
property contains the TCPListener
object that created the TCPConnection
, if any. Esta propiedad es de solo lectura.
.noDelay
noDelay : Boolean
Descripción
La propiedad .noDelay
contiene si el algoritmo de Nagle está desactivado (true
) o activado (false
). Esta propiedad es de solo lectura.
.port
port : Number
Descripción
The .port
property contains the port number of the remote machine. Esta propiedad es de solo lectura.
.send()
.send( data : Blob )
Parámetros | Tipo | Descripción | |
---|---|---|---|
data | Blob | -> | Datos a enviar |
Descripción
La función send()
envía datos al servidor. If the connection is not established yet, the data is sent once the connection is established.
.shutdown()
.shutdown()
Parámetros | Tipo | Descripción | |
---|---|---|---|
No requiere ningún parámetro |
Descripción
La función shutdown()
cierra el canal write de la conexión (cliente a servidor) mientras se mantiene abierto el canal read (servidor al flujo del cliente) permitiéndole continuar recibiendo datos hasta que la conexión sea completamente cerrada por el servidor o se produzca un error.
.wait()
.wait( { timeout : Real } )
Parámetros | Tipo | Descripción | |
---|---|---|---|
timeout | Real | -> | Tiempo máximo de espera en segundos |
Descripción
La función wait()
espera hasta que se cierre la conexión TCP o se alcance el timeout
especificado
During the .wait()
execution, callback functions are executed, whether they originate from other SystemWorker
instances. Puede salir de un .wait()
llamando a shutdown()
desde una retrollamada.