Skip to main content
Version: Next

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. You can create a TCP connection using the 4D.TCPConnection.new() function, which returns a TCPConnection object.

Thanks to the standard Qodly server 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 function execution. If you want to "force" the closure of a connection at any moment, nullify its references by setting them to Null.

Example

This example defines a class that handles the connection lifecycle and events, showcasing how to work asynchronously:

// Class definition: cs.MyAsyncTCPConnection

constructor(url : string, 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
blob = convertFromString("Information", "UTF-8")
this.connection.send(blob)

// Callback called when the connection is successfully established
function onConnection(connection : 4D.TCPConnection , event : 4D.TCPEvent)
var info : string = "Connection established"

// Callback called when the connection is properly closed
function onShutdown(connection : 4D.TCPConnection, event : 4D.TCPEvent)
var info : string = "Connection closed"

// Callback called when receiving data from the server
function onData(connection : 4D.TCPConnection, event : 4D.TCPEvent)
var info : string = convertToString(event.data, "UTF-8")

//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)
var info : string = "Connection error"

// Callback called after onShutdown/onError just before the TCPConnection object is released
function onTerminate(connection : 4D.TCPConnection , event : 4D.TCPEvent)
var info : string = "Connection terminated"

Usage example

Create a 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:

callWorker("new process", "Async_TCP")

TCPConnection Object

A TCPConnection object is a non-sharable object.

TCPConnection objects provide the following properties and functions:


errors : collection
a collection of error objects associated with the connection
noDelay : boolean
whether Nagle's algorithm is disabled (true) or enabled (false)
.send( data : blob )
sends data to the server
.shutdown()
closes the write channel of the connection (client to server stream)
.wait()
.wait( timeout : Real )

waits until the TCP connection is closed or the specified timeout is reached

4D.TCPConnection.new()

4D.TCPConnection.new( serverAddress : string , serverPort : integer , options : object ) : 4D.TCPConnection

ParameterTypeDescription
serverAddressstringDomain name or IP address of the server
serverPortintegerPort number of the server
optionsobjectConfiguration options for the connection
ResultTCPConnectionNew TCPConnection object

Description

The 4D.TCPConnection.new() function creates a new TCP connection to the specified serverAddress and serverPort, using the defined options, and returns a 4D.HTTPRequest object.

options parameter

In the options parameter, pass an object that can contain the following properties:

PropertyTypeDescriptionDefault
onConnectionformulaCallback triggered when the connection is established.undefined
onDataformulaCallback triggered when data is receivedundefined
onShutdownformulaCallback triggered when the connection is properly closedundefined
onErrorformulaCallback triggered in case of an errorundefined
onTerminateformulaCallback triggered just before the TCPConnection is releasedundefined
noDelayBooleanRead-only Disables Nagle's algorithm if trueFalse

Callback functions

All callback functions receive two parameters:

ParameterTypeDescription
connectionTCPConnection objectThe current TCP connection instance.
eventTCPEvent objectContains information about the event.

Sequence of Callback Calls:

  1. onConnection is triggered when the connection is established.
  2. onData is triggered each time data is received.
  3. Either onShutdown or onError is triggered:
    • onShutdown is triggered when the connection is properly closed.
    • onError is triggered if an error occurs.
  4. onTerminate is always triggered just before the TCPConnection is released (connection is closed or an error occured).

TCPEvent object

A TCPEvent object is returned when a callback function is called.

.closed

closed : boolean

Description

The .closed property contains whether the connection is closed. Returns true if the connection is closed, either due to an error, a call to shutdown(), or closure by the server.

.errors

errors : collection

Description

The .errors property contains a collection of error objects associated with the connection. Each error object includes the error code, a description, and the signature of the component that caused the error.

PropertyTypeDescription
errorscollection4D error stack in case of error
[].errCodeinteger4D error code
[].messagestringDescription of the 4D error
[].componentSignaturestringSignature of the internal component which returned the error

.noDelay

noDelay : boolean

Description

The .noDelay property contains whether Nagle's algorithm is disabled (true) or enabled (false). This property is read-only.

.send()

.send( data : blob )

ParameterTypeDescription
datablobData to be sent

Description

The send() function sends data to the server. If the connection is not established yet, the data is sent once the connection is established.

.shutdown()

.shutdown()

ParameterTypeDescription
Does not require any parameters

Description

The shutdown() function closes the write channel of the connection (client to server stream) while keeping the read channel (server to client stream) open, allowing you to continue receiving data until the connection is fully closed by the server or an error occurs.

.wait()

.wait()
.wait( timeout : Real )

ParameterTypeDescription
timeoutRealMaximum wait time in seconds

Description

The wait() function waits until the TCP connection is closed or the specified timeout is reached

note

During the .wait() execution, callback functions are executed, whether they originate from other instances of the same class, or instances of any classes supporting the same callback mechanism (HTTPRequest, TCPConnection, SystemWorker). You can exit from a .wait() by calling shutdown() or terminate() (depending on the API) from a callback.