Socket

Net. Socket

A Socket object is a JS wrapper around a low-level TCP socket.

Constructor

new Socket() → {Socket}

Creates a new Socket instance.

Source:
Fires:
  • event:connect - Emitted when a socket connection is successfully established.
  • event:data - Emitted when data is received.
  • event:end - Emitted when the other end of the socket sends a FIN packet.
  • event:error - Emitted when an error occurs.
  • event:close - Emitted once the socket is fully closed.
  • event:timeout - Emitted if the socket times out from (read) inactivity.
Returns:
Type:
Socket

Methods

address() → {SocketHost}

Returns the bound address, the address family name and port of the socket.

Source:
Returns:
Type:
SocketHost
  • Information about the local endpoint of the socket.

(async) connect(options) → {Promise.<socketInfo>}

Initiates a connection on a given remote host.

Additional signatures:

  • connect(port: number | string, host?: string)
Source:
Parameters:
Name Type Description
options Object

Configuration options for the connection.

Name Type Description
host string

The hostname or IP address of the remote server to connect to.

port string | number

The port number on the remote host to connect to.

Returns:
Type:
Promise.<socketInfo>

Information about the connected TCP socket.

(async) destroy()

Closes both sides of the TCP sockets.

Source:

(async) end(data, encodingopt) → {Promise.<void>}

Half-closes the TCP stream.

Source:
Parameters:
Name Type Attributes Default Description
data String | Uint8Array

The (last) data to be written to the socket.

encoding String <optional>
utf-8

The character encoding to use.

Returns:
Type:
Promise.<void>

read() → {Promise.<(Uint8Array|string)>}

Returns a promise which is fulfilled when the TCP stream can return a chunk.

Source:
Returns:
Type:
Promise.<(Uint8Array|string)>

The chunk read from the socket.

setEncoding(encodingopt)

Sets the encoding for the current socket.

Source:
Parameters:
Name Type Attributes Default Description
encoding String <optional>
utf-8

The character encoding to use.

setTimeout(timeout)

Sets the socket to timeout after timeout milliseconds of (read) inactivity on the socket.

Source:
Parameters:
Name Type Default Description
timeout Number 0

The duration after which the socket should timeout due to inactivity.

(async) write(data, encodingopt) → {Promise.<Number>}

Writes contents to a TCP socket stream.

Source:
Parameters:
Name Type Attributes Default Description
data String | Uint8Array

The data to be written to the socket.

encoding String <optional>
utf-8

The character encoding to use.

Returns:
Type:
Promise.<Number>

The number of bytes written.