net.connect

net.connect

net.connect

Function

Establish a TCP, UDP or WebSocket client connection.

Syntax

Parameters

ParametersTypeRequiredDefault valueDescription
configObjectYesNoneConnection configuration object. Public fields and protocol fields are shown below.

Connection configuration field

FieldTypeApplicable typeRequiredDefault valueDescription
typeStringAllYesNoneThe connection protocol type. Optional values are tcp, udp, ws.
hostStringtcp/udpYesNoneRemote host name or IP address, such as 127.0.0.1, example.com.
portInttcp/udpYesNoneThe remote port number, ranging from 0 to 65535.
timeoutInttcpNo0TCP connection, read and write timeout, in milliseconds; less than or equal to 0 means no timeout is set.
urlStringwsYesNoneWebSocket full connection address, such as ws://127.0.0.1:9002/ws.

Return Value

TypeDescription
TcpClient/UdpSocket/WsSocketPress type to return the corresponding connection handle.

Connection handle field

FieldTypeDescription
addrStringConnection target or local socket address, usually in the format host:port.
typeStringConnection type. TCP returns tcp, UDP returns udp, and WebSocket returns ws.

Connection handle method

TypeMethodReturn valueDescription
TcpClientwrite(data) / send(data)IntWrites a TCP String, byte array, or Bytes, returning the number of bytes written.
TcpClientread()StringSynchronously read a piece of TCP data and convert it to a string according to UTF-8 lossy.
TcpClientread_bytes()BytesSynchronously read a segment of TCP raw bytes.
TcpClientclose()BoolClose the TCP connection.
UdpSocketsend(data)IntSend UDP data to the default remote address in the connect configuration and return the number of bytes sent.
UdpSocketsend(data, addr)IntSend UDP data to the specified host:port and return the number of bytes sent.
UdpSocketclose()BoolClose UDP socket.
WsSocketsend(data) / write(data)BoolSend WebSocket message; String is text frame, Bytes or byte array is binary frame.
WsSocketclose()BoolClose the WebSocket connection.
WsSocketon_message(fn(message) {}, binary)WsSocketRegister WebSocket client message callback; when the second parameter is true, message is Bytes.
WsSocketon_close(fn() {})WsSocketRegister the WebSocket client close callback.
WsSocketon_error(fn(message) {})WsSocketRegister WebSocket client error callback.

Examples

Notes

- TCP and UDP use the host, port fields; WebSocket uses the full url field.

- WebSocket does not support synchronous read(); please receive messages via on_message().

  • When you need to receive binary messages, TCP can use read_bytes(), and the listening callback can set binary: true in the net.listen configuration.