net.listen

net.listen

net.listen

Function

Start the Web, TCP, UDP or WebSocket listening service.

Syntax

Parameters

ParameterTypeRequiredDefault valueDescription
configObjectYesNoneThe listening configuration object. The public fields are shown below. For protocol-specific fields, please see the corresponding protocol document.

Public configuration field

All listening types of net.listen(config) select the protocol through type and specify the listening address through bind. It is recommended that all listening configurations explicitly write out type and bind, so that codes, documents and AI tools can stably identify the service entrance.

FieldTypeRequiredDefault valueDescription
typeStringYesNoneThe listening protocol type. Optional values are web, tcp, udp, ws.
bindStringRequired for tcp/udp/ws; recommended for webweb defaults to 0.0.0.0:8080Listening address in host:port format, such as 127.0.0.1:9000 or 0.0.0.0:8080. When the port is 0, the operating system allocates an available port.
binaryBooltcp/udp/ws OptionalfalseWhen true, the message callback receives Bytes; the default behavior is to maintain String compatibility.

Protocol exclusive fields are placed on the corresponding page description:

typeExclusive documentDescription
webWeb service Site sites, static directory, upload temporary directory, TLS and other Web service configurations.
tcpTCP communication TCP server event callback and client reading and writing.
udpUDP communication UDP message callback and sending target address.
wsWebSocket communication WebSocket routing, connection callbacks and message callbacks.

Return Value

TypeDescription
WebServer TcpServer UdpSocket WsServerPress type to return the corresponding service handle.

Service handle public field

FieldTypeDescription
addrStringActual listening address, usually in the format host:port; bind port When writing 0, the port allocated by the system can be read from here.
typeStringService type. Web returns web, TCP returns tcp, UDP returns udp, and WebSocket returns ws.

Service handle public method

MethodReturn valueDescription
close()BoolClose the listening service or socket, return true on success.

Examples

Notes

  • The shorthand net.listen is equivalent to net().listen.
  • bind must contain the port; missing or invalid port will throw an error.
  • 127.0.0.1 only allows local access, 0.0.0.0 will listen to all network card addresses.
- TCP, UDP, WebSocket listening services use a shared Tokio runtime, and background events are delivered to the VM through bounded queues.
  • It is recommended to set binary: true for TCP, UDP, and WebSocket binary protocols to avoid early conversion of callback parameters into strings.
- Network event queue and connection resource limits are described in the net configuration description of BT.stats.