TCP Listener Socket
An IO class that listens for and accepts incoming TCP connection requests.
Constructor
Section titled “Constructor”Listener
Section titled “Listener”Creates a new TCP Listener object instance.
Listener(options)Parameters
Section titled “Parameters”options
An object of properties used to construct the class.
port(optional) - a number specifying the port to listen on, defaults to0which will select an arbitrary available port on the system.
address(optional) - A string with the IP address of the network interface to bind to, defaults to ”::” for IPv6 or “0.0.0.0” for IPv4.
onReadable(requests)(optional): A callback function that is invoked when one or more new connection requests are received by the socket, which can be retrieved using thereadmethod. Therequestsargument indicates the total number of pending connection requests.
Exceptions
Section titled “Exceptions”If the constructor requires a resource that is already in use — whether by a script or the native host — an Error exception is thrown.
Instance Properties
Section titled “Instance Properties”Includes properties of the IO Class Pattern. Specific to this class:
format
Section titled “format”Always returns "socket/tcp".
Instance Methods
Section titled “Instance Methods”Returns a TCP Socket instance. The instance is already connected to the remote endpoint without any callbacks.
read()Return value
Section titled “Return value”An instance of TCP Socket if available.
Examples
Section titled “Examples”The class can be imported from the embedded namespace:
import Listener from "embedded:io/socket/listener";Simple TCP Server
Section titled “Simple TCP Server”This example implements a simple HTTP echo server. It accepts incoming requests and sends back the complete request (including the request headers) as the response body. The Echo class reads the request and generates the response based on the TCP Socket class.
import Listener from "embedded:io/socket/listener";import TCP from "embedded:io/socket/tcp";
class Echo extends TCP { constructor(options) { super({ ...options, onReadable: this.onReadable, }); } onReadable() { const response = this.read();
this.write(ArrayBuffer.fromString("HTTP/1.1 200 OK\r\n")); this.write(ArrayBuffer.fromString("connection: close\r\n")); this.write(ArrayBuffer.fromString("content-type: text/plain\r\n")); this.write(ArrayBuffer.fromString(`content-length: ${response.byteLength}\r\n`)); this.write(ArrayBuffer.fromString("\r\n")); this.write(response);
this.close(); }}
new Listener({ port: 80, onReadable(requests) { while (requests--) { new Echo({ from: this.read() }); } }});