node:net module provides an asynchronous network API for creating stream-based TCP or IPC servers and clients.
Import
Class: net.Server
This class is used to create a TCP or IPC server.Creating a Server
Events
Event: ‘close’
Emitted when the server closes. If connections exist, this event is not emitted until all connections are ended.Event: ‘connection’
socketThe connection object
Event: ‘error’
error
Event: ‘listening’
Emitted when the server has been bound after callingserver.listen().
Methods
server.listen([port[, host[, backlog]]][, callback])
porthostbacklogMaximum length of the queue of pending connectionscallback- Returns:
port and host.
server.address()
- Returns:
server.close([callback])
callback- Returns:
server.getConnections(callback)
callbackTakes two arguments:errandcount
Properties
server.listening
- Type:
server.maxConnections
- Type:
Class: net.Socket
This class is an abstraction of a TCP socket or a streaming IPC endpoint.Creating a Socket
Events
Event: ‘close’
hadError
Event: ‘connect’
Emitted when a socket connection is successfully established.Event: ‘data’
data
Event: ‘drain’
Emitted when the write buffer becomes empty.Event: ‘end’
Emitted when the other end of the socket signals the end of transmission.Event: ‘error’
error
Event: ‘timeout’
Emitted if the socket times out from inactivity.Methods
socket.connect(port[, host][, connectListener])
porthostconnectListener- Returns:
socket.write(data[, encoding][, callback])
dataencodingcallback- Returns:
socket.end([data[, encoding]][, callback])
dataencodingcallback
socket.destroy([error])
error- Returns:
socket.setTimeout(timeout[, callback])
timeoutMilliseconds of inactivity before timeoutcallback
timeout milliseconds of inactivity.
socket.setKeepAlive([enable][, initialDelay])
enableDefault:falseinitialDelayDefault:0
socket.setNoDelay([noDelay])
noDelayDefault:true
Properties
socket.localAddress
- Type:
socket.localPort
- Type:
socket.remoteAddress
- Type:
socket.remotePort
- Type:
socket.bytesRead
- Type:
socket.bytesWritten
- Type:
socket.connecting
- Type:
true, socket is still connecting.
Factory Functions
net.createServer([options][, connectionListener])
optionsallowHalfOpenDefault:falsepauseOnConnectDefault:false
connectionListener- Returns:
net.createConnection(options[, connectListener])
optionsconnectListener- Returns:
net.Socket and initiates a connection.
net.connect()
Alias tonet.createConnection().
Example: Echo Server
Example: TCP Client
IPC Support
Thenode:net module supports IPC with named pipes on Windows and Unix domain sockets on other systems.