{ "source": "doc/api/net.markdown", "modules": [ { "textRaw": "net", "name": "net", "stability": 3, "stabilityText": "Stable", "desc": "

The net module provides you with an asynchronous network wrapper. It contains\nmethods for creating both servers and clients (called streams). You can include\nthis module with require('net');\n\n

\n", "methods": [ { "textRaw": "net.createServer([options], [connectionListener])", "type": "method", "name": "createServer", "desc": "

Creates a new TCP server. The connectionListener argument is\nautomatically set as a listener for the ['connection'][] event.\n\n

\n

options is an object with the following defaults:\n\n

\n
{ allowHalfOpen: false\n}
\n

If allowHalfOpen is true, then the socket won't automatically send a FIN\npacket when the other end of the socket sends a FIN packet. The socket becomes\nnon-readable, but still writable. You should call the end() method explicitly.\nSee ['end'][] event for more information.\n\n

\n

Here is an example of an echo server which listens for connections\non port 8124:\n\n

\n
var net = require('net');\nvar server = net.createServer(function(c) { //'connection' listener\n  console.log('server connected');\n  c.on('end', function() {\n    console.log('server disconnected');\n  });\n  c.write('hello\\r\\n');\n  c.pipe(c);\n});\nserver.listen(8124, function() { //'listening' listener\n  console.log('server bound');\n});
\n

Test this by using telnet:\n\n

\n
telnet localhost 8124
\n

To listen on the socket /tmp/echo.sock the third line from the last would\njust be changed to\n\n

\n
server.listen('/tmp/echo.sock', function() { //'listening' listener
\n

Use nc to connect to a UNIX domain socket server:\n\n

\n
nc -U /tmp/echo.sock
\n", "signatures": [ { "params": [ { "name": "options", "optional": true }, { "name": "connectionListener", "optional": true } ] } ] }, { "textRaw": "net.connect(options, [connectionListener])", "type": "method", "name": "connect", "desc": "

Constructs a new socket object and opens the socket to the given location.\nWhen the socket is established, the ['connect'][] event will be emitted.\n\n

\n

For TCP sockets, options argument should be an object which specifies:\n\n

\n\n

For UNIX domain sockets, options argument should be an object which specifies:\n\n

\n\n

Common options are:\n\n

\n\n

The connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

\n

Here is an example of a client of echo server as described previously:\n\n

\n
var net = require('net');\nvar client = net.connect({port: 8124},\n    function() { //'connect' listener\n  console.log('client connected');\n  client.write('world!\\r\\n');\n});\nclient.on('data', function(data) {\n  console.log(data.toString());\n  client.end();\n});\nclient.on('end', function() {\n  console.log('client disconnected');\n});
\n

To connect on the socket /tmp/echo.sock the second line would just be\nchanged to\n\n

\n
var client = net.connect({path: '/tmp/echo.sock'},
\n", "signatures": [ { "params": [ { "name": "options" }, { "name": "connectionListener", "optional": true } ] }, { "params": [ { "name": "options" }, { "name": "connectionListener", "optional": true } ] } ] }, { "textRaw": "net.createConnection(options, [connectionListener])", "type": "method", "name": "createConnection", "desc": "

Constructs a new socket object and opens the socket to the given location.\nWhen the socket is established, the ['connect'][] event will be emitted.\n\n

\n

For TCP sockets, options argument should be an object which specifies:\n\n

\n\n

For UNIX domain sockets, options argument should be an object which specifies:\n\n

\n\n

Common options are:\n\n

\n\n

The connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

\n

Here is an example of a client of echo server as described previously:\n\n

\n
var net = require('net');\nvar client = net.connect({port: 8124},\n    function() { //'connect' listener\n  console.log('client connected');\n  client.write('world!\\r\\n');\n});\nclient.on('data', function(data) {\n  console.log(data.toString());\n  client.end();\n});\nclient.on('end', function() {\n  console.log('client disconnected');\n});
\n

To connect on the socket /tmp/echo.sock the second line would just be\nchanged to\n\n

\n
var client = net.connect({path: '/tmp/echo.sock'},
\n", "signatures": [ { "params": [ { "name": "options" }, { "name": "connectionListener", "optional": true } ] } ] }, { "textRaw": "net.connect(port, [host], [connectListener])", "type": "method", "name": "connect", "desc": "

Creates a TCP connection to port on host. If host is omitted,\n'localhost' will be assumed.\nThe connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

\n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "connectListener", "optional": true } ] }, { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "net.createConnection(port, [host], [connectListener])", "type": "method", "name": "createConnection", "desc": "

Creates a TCP connection to port on host. If host is omitted,\n'localhost' will be assumed.\nThe connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

\n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "net.connect(path, [connectListener])", "type": "method", "name": "connect", "desc": "

Creates unix socket connection to path.\nThe connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "connectListener", "optional": true } ] }, { "params": [ { "name": "path" }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "net.createConnection(path, [connectListener])", "type": "method", "name": "createConnection", "desc": "

Creates unix socket connection to path.\nThe connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "net.isIP(input)", "type": "method", "name": "isIP", "desc": "

Tests if input is an IP address. Returns 0 for invalid strings,\nreturns 4 for IP version 4 addresses, and returns 6 for IP version 6 addresses.\n\n\n

\n", "signatures": [ { "params": [ { "name": "input" } ] } ] }, { "textRaw": "net.isIPv4(input)", "type": "method", "name": "isIPv4", "desc": "

Returns true if input is a version 4 IP address, otherwise returns false.\n\n\n

\n", "signatures": [ { "params": [ { "name": "input" } ] } ] }, { "textRaw": "net.isIPv6(input)", "type": "method", "name": "isIPv6", "desc": "

Returns true if input is a version 6 IP address, otherwise returns false.\n\n

\n", "signatures": [ { "params": [ { "name": "input" } ] } ] } ], "classes": [ { "textRaw": "Class: net.Server", "type": "class", "name": "net.Server", "desc": "

This class is used to create a TCP or UNIX server.\nA server is a net.Socket that can listen for new incoming connections.\n\n

\n", "methods": [ { "textRaw": "server.listen(port, [host], [backlog], [callback])", "type": "method", "name": "listen", "desc": "

Begin accepting connections on the specified port and host. If the\nhost is omitted, the server will accept connections directed to any\nIPv4 address (INADDR_ANY). A port value of zero will assign a random port.\n\n

\n

Backlog is the maximum length of the queue of pending connections.\nThe actual length will be determined by your OS through sysctl settings such as\ntcp_max_syn_backlog and somaxconn on linux. The default value of this\nparameter is 511 (not 512).\n\n

\n

This function is asynchronous. When the server has been bound,\n['listening'][] event will be emitted. The last parameter callback\nwill be added as an listener for the ['listening'][] event.\n\n

\n

One issue some users run into is getting EADDRINUSE errors. This means that\nanother server is already running on the requested port. One way of handling this\nwould be to wait a second and then try again. This can be done with\n\n

\n
server.on('error', function (e) {\n  if (e.code == 'EADDRINUSE') {\n    console.log('Address in use, retrying...');\n    setTimeout(function () {\n      server.close();\n      server.listen(PORT, HOST);\n    }, 1000);\n  }\n});
\n

(Note: All sockets in Node set SO_REUSEADDR already)\n\n\n

\n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "backlog", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.listen(path, [callback])", "type": "method", "name": "listen", "desc": "

Start a UNIX socket server listening for connections on the given path.\n\n

\n

This function is asynchronous. When the server has been bound,\n['listening'][] event will be emitted. The last parameter callback\nwill be added as an listener for the ['listening'][] event.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.listen(handle, [callback])", "type": "method", "name": "listen", "signatures": [ { "params": [ { "textRaw": "`handle` {Object} ", "name": "handle", "type": "Object" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "handle" }, { "name": "callback", "optional": true } ] } ], "desc": "

The handle object can be set to either a server or socket (anything\nwith an underlying _handle member), or a {fd: <n>} object.\n\n

\n

This will cause the server to accept connections on the specified\nhandle, but it is presumed that the file descriptor or handle has\nalready been bound to a port or domain socket.\n\n

\n

Listening on a file descriptor is not supported on Windows.\n\n

\n

This function is asynchronous. When the server has been bound,\n'listening' event will be emitted.\nthe last parameter callback will be added as an listener for the\n'listening' event.\n\n

\n" }, { "textRaw": "server.close([callback])", "type": "method", "name": "close", "desc": "

Stops the server from accepting new connections and keeps existing\nconnections. This function is asynchronous, the server is finally\nclosed when all connections are ended and the server emits a 'close'\nevent. Optionally, you can pass a callback to listen for the 'close'\nevent.\n\n

\n", "signatures": [ { "params": [ { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.address()", "type": "method", "name": "address", "desc": "

Returns the bound address, the address family name and port of the server\nas reported by the operating system.\nUseful to find which port was assigned when giving getting an OS-assigned address.\nReturns an object with three properties, e.g.\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }\n\n

\n

Example:\n\n

\n
var server = net.createServer(function (socket) {\n  socket.end("goodbye\\n");\n});\n\n// grab a random port.\nserver.listen(function() {\n  address = server.address();\n  console.log("opened server on %j", address);\n});
\n

Don't call server.address() until the 'listening' event has been emitted.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "server.unref()", "type": "method", "name": "unref", "desc": "

Calling unref on a server will allow the program to exit if this is the only\nactive server in the event system. If the server is already unrefd calling\nunref again will have no effect.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "server.ref()", "type": "method", "name": "ref", "desc": "

Opposite of unref, calling ref on a previously unrefd server will not\nlet the program exit if it's the only server left (the default behavior). If\nthe server is refd calling ref again will have no effect.\n\n

\n", "signatures": [ { "params": [] } ] } ], "properties": [ { "textRaw": "server.maxConnections", "name": "maxConnections", "desc": "

Set this property to reject connections when the server's connection count gets\nhigh.\n\n

\n

It is not recommended to use this option once a socket has been sent to a child\nwith child_process.fork().\n\n

\n" }, { "textRaw": "server.connections", "name": "connections", "desc": "

The number of concurrent connections on the server.\n\n

\n

This becomes null when sending a socket to a child with child_process.fork().\n\n

\n

net.Server is an [EventEmitter][] with the following events:\n\n

\n" } ], "events": [ { "textRaw": "Event: 'listening'", "type": "event", "name": "listening", "desc": "

Emitted when the server has been bound after calling server.listen.\n\n

\n", "params": [] }, { "textRaw": "Event: 'connection'", "type": "event", "name": "connection", "params": [], "desc": "

Emitted when a new connection is made. socket is an instance of\nnet.Socket.\n\n

\n" }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

Emitted when the server closes. Note that if connections exist, this\nevent is not emitted until all connections are ended.\n\n

\n", "params": [] }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "params": [], "desc": "

Emitted when an error occurs. The 'close' event will be called directly\nfollowing this event. See example in discussion of server.listen.\n\n

\n" } ] }, { "textRaw": "Class: net.Socket", "type": "class", "name": "net.Socket", "desc": "

This object is an abstraction of a TCP or UNIX socket. net.Socket\ninstances implement a duplex Stream interface. They can be created by the\nuser and used as a client (with connect()) or they can be created by Node\nand passed to the user through the 'connection' event of a server.\n\n

\n", "methods": [ { "textRaw": "new net.Socket([options])", "type": "method", "name": "Socket", "desc": "

Construct a new socket object.\n\n

\n

options is an object with the following defaults:\n\n

\n
{ fd: null\n  type: null\n  allowHalfOpen: false\n}
\n

fd allows you to specify the existing file descriptor of socket. type\nspecified underlying protocol. It can be 'tcp4', 'tcp6', or 'unix'.\nAbout allowHalfOpen, refer to createServer() and 'end' event.\n\n

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "socket.connect(port, [host], [connectListener])", "type": "method", "name": "connect", "desc": "

Opens the connection for a given socket. If port and host are given,\nthen the socket will be opened as a TCP socket, if host is omitted,\nlocalhost will be assumed. If a path is given, the socket will be\nopened as a unix socket to that path.\n\n

\n

Normally this method is not needed, as net.createConnection opens the\nsocket. Use this only if you are implementing a custom Socket or if a\nSocket is closed and you want to reuse it to connect to another server.\n\n

\n

This function is asynchronous. When the ['connect'][] event is emitted the\nsocket is established. If there is a problem connecting, the 'connect' event\nwill not be emitted, the 'error' event will be emitted with the exception.\n\n

\n

The connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "connectListener", "optional": true } ] }, { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "socket.connect(path, [connectListener])", "type": "method", "name": "connect", "desc": "

Opens the connection for a given socket. If port and host are given,\nthen the socket will be opened as a TCP socket, if host is omitted,\nlocalhost will be assumed. If a path is given, the socket will be\nopened as a unix socket to that path.\n\n

\n

Normally this method is not needed, as net.createConnection opens the\nsocket. Use this only if you are implementing a custom Socket or if a\nSocket is closed and you want to reuse it to connect to another server.\n\n

\n

This function is asynchronous. When the ['connect'][] event is emitted the\nsocket is established. If there is a problem connecting, the 'connect' event\nwill not be emitted, the 'error' event will be emitted with the exception.\n\n

\n

The connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "socket.setEncoding([encoding])", "type": "method", "name": "setEncoding", "desc": "

Set the encoding for the socket as a Readable Stream. See\n[stream.setEncoding()][] for more information.\n\n

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "socket.write(data, [encoding], [callback])", "type": "method", "name": "write", "desc": "

Sends data on the socket. The second parameter specifies the encoding in the\ncase of a string--it defaults to UTF8 encoding.\n\n

\n

Returns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in user memory.\n'drain' will be emitted when the buffer is again free.\n\n

\n

The optional callback parameter will be executed when the data is finally\nwritten out - this may not be immediately.\n\n

\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "socket.end([data], [encoding])", "type": "method", "name": "end", "desc": "

Half-closes the socket. i.e., it sends a FIN packet. It is possible the\nserver will still send some data.\n\n

\n

If data is specified, it is equivalent to calling\nsocket.write(data, encoding) followed by socket.end().\n\n

\n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "socket.destroy()", "type": "method", "name": "destroy", "desc": "

Ensures that no more I/O activity happens on this socket. Only necessary in\ncase of errors (parse error or so).\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.pause()", "type": "method", "name": "pause", "desc": "

Pauses the reading of data. That is, 'data' events will not be emitted.\nUseful to throttle back an upload.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.resume()", "type": "method", "name": "resume", "desc": "

Resumes reading after a call to pause().\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.setTimeout(timeout, [callback])", "type": "method", "name": "setTimeout", "desc": "

Sets the socket to timeout after timeout milliseconds of inactivity on\nthe socket. By default net.Socket do not have a timeout.\n\n

\n

When an idle timeout is triggered the socket will receive a 'timeout'\nevent but the connection will not be severed. The user must manually end()\nor destroy() the socket.\n\n

\n

If timeout is 0, then the existing idle timeout is disabled.\n\n

\n

The optional callback parameter will be added as a one time listener for the\n'timeout' event.\n\n

\n", "signatures": [ { "params": [ { "name": "timeout" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "socket.setNoDelay([noDelay])", "type": "method", "name": "setNoDelay", "desc": "

Disables the Nagle algorithm. By default TCP connections use the Nagle\nalgorithm, they buffer data before sending it off. Setting true for\nnoDelay will immediately fire off data each time socket.write() is called.\nnoDelay defaults to true.\n\n

\n", "signatures": [ { "params": [ { "name": "noDelay", "optional": true } ] } ] }, { "textRaw": "socket.setKeepAlive([enable], [initialDelay])", "type": "method", "name": "setKeepAlive", "desc": "

Enable/disable keep-alive functionality, and optionally set the initial\ndelay before the first keepalive probe is sent on an idle socket.\nenable defaults to false.\n\n

\n

Set initialDelay (in milliseconds) to set the delay between the last\ndata packet received and the first keepalive probe. Setting 0 for\ninitialDelay will leave the value unchanged from the default\n(or previous) setting. Defaults to 0.\n\n

\n", "signatures": [ { "params": [ { "name": "enable", "optional": true }, { "name": "initialDelay", "optional": true } ] } ] }, { "textRaw": "socket.address()", "type": "method", "name": "address", "desc": "

Returns the bound address, the address family name and port of the\nsocket as reported by the operating system. Returns an object with\nthree properties, e.g.\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.unref()", "type": "method", "name": "unref", "desc": "

Calling unref on a socket will allow the program to exit if this is the only\nactive socket in the event system. If the socket is already unrefd calling\nunref again will have no effect.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.ref()", "type": "method", "name": "ref", "desc": "

Opposite of unref, calling ref on a previously unrefd socket will not\nlet the program exit if it's the only socket left (the default behavior). If\nthe socket is refd calling ref again will have no effect.\n\n

\n", "signatures": [ { "params": [] } ] } ], "properties": [ { "textRaw": "socket.bufferSize", "name": "bufferSize", "desc": "

net.Socket has the property that socket.write() always works. This is to\nhelp users get up and running quickly. The computer cannot always keep up\nwith the amount of data that is written to a socket - the network connection\nsimply might be too slow. Node will internally queue up the data written to a\nsocket and send it out over the wire when it is possible. (Internally it is\npolling on the socket's file descriptor for being writable).\n\n

\n

The consequence of this internal buffering is that memory may grow. This\nproperty shows the number of characters currently buffered to be written.\n(Number of characters is approximately equal to the number of bytes to be\nwritten, but the buffer may contain strings, and the strings are lazily\nencoded, so the exact number of bytes is not known.)\n\n

\n

Users who experience large or growing bufferSize should attempt to\n"throttle" the data flows in their program with pause() and resume().\n\n\n

\n" }, { "textRaw": "socket.remoteAddress", "name": "remoteAddress", "desc": "

The string representation of the remote IP address. For example,\n'74.125.127.100' or '2001:4860:a005::68'.\n\n

\n" }, { "textRaw": "socket.remotePort", "name": "remotePort", "desc": "

The numeric representation of the remote port. For example,\n80 or 21.\n\n

\n" }, { "textRaw": "socket.localAddress", "name": "localAddress", "desc": "

The string representation of the local IP address the remote client is\nconnecting on. For example, if you are listening on '0.0.0.0' and the\nclient connects on '192.168.1.1', the value would be '192.168.1.1'.\n\n

\n" }, { "textRaw": "socket.localPort", "name": "localPort", "desc": "

The numeric representation of the local port. For example,\n80 or 21.\n\n

\n" }, { "textRaw": "socket.bytesRead", "name": "bytesRead", "desc": "

The amount of received bytes.\n\n

\n" }, { "textRaw": "socket.bytesWritten", "name": "bytesWritten", "desc": "

The amount of bytes sent.\n\n\n

\n

net.Socket instances are [EventEmitter][] with the following events:\n\n

\n" } ], "events": [ { "textRaw": "Event: 'connect'", "type": "event", "name": "connect", "desc": "

Emitted when a socket connection is successfully established.\nSee connect().\n\n

\n", "params": [] }, { "textRaw": "Event: 'data'", "type": "event", "name": "data", "params": [], "desc": "

Emitted when data is received. The argument data will be a Buffer or\nString. Encoding of data is set by socket.setEncoding().\n(See the [Readable Stream][] section for more information.)\n\n

\n

Note that the data will be lost if there is no listener when a Socket\nemits a 'data' event.\n\n

\n" }, { "textRaw": "Event: 'end'", "type": "event", "name": "end", "desc": "

Emitted when the other end of the socket sends a FIN packet.\n\n

\n

By default (allowHalfOpen == false) the socket will destroy its file\ndescriptor once it has written out its pending write queue. However, by\nsetting allowHalfOpen == true the socket will not automatically end()\nits side allowing the user to write arbitrary amounts of data, with the\ncaveat that the user is required to end() their side now.\n\n\n

\n", "params": [] }, { "textRaw": "Event: 'timeout'", "type": "event", "name": "timeout", "desc": "

Emitted if the socket times out from inactivity. This is only to notify that\nthe socket has been idle. The user must manually close the connection.\n\n

\n

See also: socket.setTimeout()\n\n\n

\n", "params": [] }, { "textRaw": "Event: 'drain'", "type": "event", "name": "drain", "desc": "

Emitted when the write buffer becomes empty. Can be used to throttle uploads.\n\n

\n

See also: the return values of socket.write()\n\n

\n", "params": [] }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "params": [], "desc": "

Emitted when an error occurs. The 'close' event will be called directly\nfollowing this event.\n\n

\n" }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "params": [], "desc": "

Emitted once the socket is fully closed. The argument had_error is a boolean\nwhich says if the socket was closed due to a transmission error.\n\n

\n" } ] } ], "type": "module", "displayName": "net" } ] }