TCPSocket
Version and platform compatibility
This feature was introduced in version 21.1.1 of the JourneyApps Container for iOS, Android and Desktop, and requires version 4.78.0 or greater of the JourneyApps Runtime.
TCPSocket support is currently only available for customers on the Enterprise plan.
The TCPSocket
API allows applications to directly connect with external devices over TCP sockets.
Checking if TCPSocket is supported
A TCPSocket.info()
function is available to check if the user's device has access to the TCP sockets. It returns an object:
supported
boolean
Indicates if TCPSocket is supported on the current device. Not supported on Web
Connecting to a TCP socket
To connect to a TCP socket, the host and port of the socket is required.
To connect, use var tcpSocket = TCPSocket.connect({host: host, port: port, timeout: timeout}, readHandler, closeHandler)
.
host
String hostname of socket, e.g. '10.0.0.1'.
port
Number of the port of the socket, e.g. 8080.
timeout
Number value in milliseconds. This value overrides the timeout period, which closes the TCP socket connection after network inactivity. Its default value is 10 seconds.
Note: This parameter was introduced in version 4.86.6 of the JourneyApps Runtime.
readHandler
Optional callback that gets called when data is present on the socket.
closeHander
Optional callback that gets called when an error occurs or socket closes. The closeHandler
will have an optional error parameter that will be a string, or null
/undefined
when there isn't an error.
Reading data
There are two ways to read data from the socket.
The readHandler
from the example above uses a callback with data in Uint8Array when there is data available.
A ReadableStream object is also available. To use the ReadableStream, the following can be used:
Data must be continually read when using the ReadableStream. In the example above, the data is read one second after previous reading.
ReadableStream methods can be used, including piping through other streams, e.g. TextDecoderStream:
Writing to a socket
The TCPSocket.connect
function returns a TCPSocket instance. This instance is used to write data to the socket in binary (Uint8Array) format.
Closing and resetting
To close a connection, call close()
on the connection object, e.g. tcpSocket.close()
.
To reset all the sockets, call TCPSocket.reset()
. This closes all open sockets.
There is also an isOpen
property on each connection object, e.g. tcpSocket.isOpen
that returns a boolean to check if the socket is open. Note that it may take some time after a socket has disconnected for the socket itself to register that it has closed.
Last updated