5 The `net` module provides you with an asynchronous network wrapper. It contains
6 functions for creating both servers and clients (called streams). You can include
7 this module with `require('net');`.
9 ## net.createServer([options][, connectionListener])
11 Creates a new TCP server. The `connectionListener` argument is
12 automatically set as a listener for the ['connection'][] event.
14 `options` is an object with the following defaults:
21 If `allowHalfOpen` is `true`, then the socket won't automatically send a FIN
22 packet when the other end of the socket sends a FIN packet. The socket becomes
23 non-readable, but still writable. You should call the `end()` method explicitly.
24 See ['end'][] event for more information.
26 If `pauseOnConnect` is `true`, then the socket associated with each incoming
27 connection will be paused, and no data will be read from its handle. This allows
28 connections to be passed between processes without any data being read by the
29 original process. To begin reading data from a paused socket, call `resume()`.
31 Here is an example of an echo server which listens for connections
34 var net = require('net');
35 var server = net.createServer(function(c) { //'connection' listener
36 console.log('client connected');
37 c.on('end', function() {
38 console.log('client disconnected');
43 server.listen(8124, function() { //'listening' listener
44 console.log('server bound');
47 Test this by using `telnet`:
51 To listen on the socket `/tmp/echo.sock` the third line from the last would
54 server.listen('/tmp/echo.sock', function() { //'listening' listener
56 Use `nc` to connect to a UNIX domain socket server:
60 ## net.connect(options[, connectionListener])
61 ## net.createConnection(options[, connectionListener])
63 A factory function, which returns a new ['net.Socket'](#net_class_net_socket)
64 and automatically connects with the supplied `options`.
66 The options are passed to both the ['net.Socket'](#net_class_net_socket)
67 constructor and the ['socket.connect'](#net_socket_connect_options_connectlistener)
70 The `connectListener` parameter will be added as a listener for the
71 ['connect'][] event once.
73 Here is an example of a client of the previously described echo server:
75 var net = require('net');
76 var client = net.connect({port: 8124},
77 function() { //'connect' listener
78 console.log('connected to server!');
79 client.write('world!\r\n');
81 client.on('data', function(data) {
82 console.log(data.toString());
85 client.on('end', function() {
86 console.log('disconnected from server');
89 To connect on the socket `/tmp/echo.sock` the second line would just be
92 var client = net.connect({path: '/tmp/echo.sock'});
94 ## net.connect(port[, host][, connectListener])
95 ## net.createConnection(port[, host][, connectListener])
97 A factory function, which returns a new
98 ['net.Socket'](#net_class_net_socket) and automatically connects to the
99 supplied `port` and `host`.
101 If `host` is omitted, `'localhost'` will be assumed.
103 The `connectListener` parameter will be added as a listener for the
104 ['connect'][] event once.
106 ## net.connect(path[, connectListener])
107 ## net.createConnection(path[, connectListener])
109 A factory function, which returns a new unix
110 ['net.Socket'](#net_class_net_socket) and automatically connects to the
113 The `connectListener` parameter will be added as a listener for the
114 ['connect'][] event once.
118 This class is used to create a TCP or local server.
120 ### server.listen(port[, hostname][, backlog][, callback])
122 Begin accepting connections on the specified `port` and `hostname`. If the
123 `hostname` is omitted, the server will accept connections on any IPv6 address
124 (`::`) when IPv6 is available, or any IPv4 address (`0.0.0.0`) otherwise. A
125 port value of zero will assign a random port.
127 Backlog is the maximum length of the queue of pending connections.
128 The actual length will be determined by your OS through sysctl settings such as
129 `tcp_max_syn_backlog` and `somaxconn` on linux. The default value of this
130 parameter is 511 (not 512).
132 This function is asynchronous. When the server has been bound,
133 ['listening'][] event will be emitted. The last parameter `callback`
134 will be added as a listener for the ['listening'][] event.
136 One issue some users run into is getting `EADDRINUSE` errors. This means that
137 another server is already running on the requested port. One way of handling this
138 would be to wait a second and then try again. This can be done with
140 server.on('error', function (e) {
141 if (e.code == 'EADDRINUSE') {
142 console.log('Address in use, retrying...');
143 setTimeout(function () {
145 server.listen(PORT, HOST);
150 (Note: All sockets in Node.js set `SO_REUSEADDR` already)
153 ### server.listen(path[, callback])
156 * `callback` {Function}
158 Start a local socket server listening for connections on the given `path`.
160 This function is asynchronous. When the server has been bound,
161 ['listening'][] event will be emitted. The last parameter `callback`
162 will be added as a listener for the ['listening'][] event.
164 On UNIX, the local domain is usually known as the UNIX domain. The path is a
165 filesystem path name. It is subject to the same naming conventions and
166 permissions checks as would be done on file creation, will be visible in the
167 filesystem, and will *persist until unlinked*.
169 On Windows, the local domain is implemented using a named pipe. The path *must*
170 refer to an entry in `\\?\pipe\` or `\\.\pipe\`. Any characters are permitted,
171 but the latter may do some processing of pipe names, such as resolving `..`
172 sequences. Despite appearances, the pipe name space is flat. Pipes will *not
173 persist*, they are removed when the last reference to them is closed. Do not
174 forget javascript string escaping requires paths to be specified with
175 double-backslashes, such as:
177 net.createServer().listen(
178 path.join('\\\\?\\pipe', process.cwd(), 'myctl'))
180 ### server.listen(handle[, callback])
183 * `callback` {Function}
185 The `handle` object can be set to either a server or socket (anything
186 with an underlying `_handle` member), or a `{fd: <n>}` object.
188 This will cause the server to accept connections on the specified
189 handle, but it is presumed that the file descriptor or handle has
190 already been bound to a port or domain socket.
192 Listening on a file descriptor is not supported on Windows.
194 This function is asynchronous. When the server has been bound,
195 ['listening'][] event will be emitted.
196 The last parameter `callback` will be added as a listener for the
197 ['listening'][] event.
199 ### server.listen(options[, callback])
201 * `options` {Object} - Required. Supports the following properties:
202 * `port` {Number} - Optional.
203 * `host` {String} - Optional.
204 * `backlog` {Number} - Optional.
205 * `path` {String} - Optional.
206 * `exclusive` {Boolean} - Optional.
207 * `callback` {Function} - Optional.
209 The `port`, `host`, and `backlog` properties of `options`, as well as the
210 optional callback function, behave as they do on a call to
211 [server.listen(port, \[host\], \[backlog\], \[callback\])
212 ](#net_server_listen_port_hostname_backlog_callback). Alternatively, the `path`
213 option can be used to specify a UNIX socket.
215 If `exclusive` is `false` (default), then cluster workers will use the same
216 underlying handle, allowing connection handling duties to be shared. When
217 `exclusive` is `true`, the handle is not shared, and attempted port sharing
218 results in an error. An example which listens on an exclusive port is
227 ### server.close([callback])
229 Stops the server from accepting new connections and keeps existing
230 connections. This function is asynchronous, the server is finally
231 closed when all connections are ended and the server emits a ['close'][] event.
232 The optional `callback` will be called once the `'close'` event occurs. Unlike
233 that event, it will be called with an Error as its only argument if the server
234 was not open when it was closed.
238 Returns the bound address, the address family name and port of the server
239 as reported by the operating system.
240 Useful to find which port was assigned when giving getting an OS-assigned address.
241 Returns an object with three properties, e.g.
242 `{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`
246 var server = net.createServer(function (socket) {
247 socket.end("goodbye\n");
250 // grab a random port.
251 server.listen(function() {
252 address = server.address();
253 console.log("opened server on %j", address);
256 Don't call `server.address()` until the `'listening'` event has been emitted.
260 Calling `unref` on a server will allow the program to exit if this is the only
261 active server in the event system. If the server is already `unref`d calling
262 `unref` again will have no effect.
268 Opposite of `unref`, calling `ref` on a previously `unref`d server will *not*
269 let the program exit if it's the only server left (the default behavior). If
270 the server is `ref`d calling `ref` again will have no effect.
274 ### server.maxConnections
276 Set this property to reject connections when the server's connection count gets
279 It is not recommended to use this option once a socket has been sent to a child
280 with `child_process.fork()`.
282 ### server.connections
284 Stability: 0 - Deprecated: Use [server.getConnections][] instead.
286 The number of concurrent connections on the server.
288 This becomes `null` when sending a socket to a child with
289 `child_process.fork()`. To poll forks and get current number of active
290 connections use asynchronous `server.getConnections` instead.
292 ### server.getConnections(callback)
294 Asynchronously get the number of concurrent connections on the server. Works
295 when sockets were sent to forks.
297 Callback should take two arguments `err` and `count`.
299 `net.Server` is an [EventEmitter][] with the following events:
301 ### Event: 'listening'
303 Emitted when the server has been bound after calling `server.listen`.
305 ### Event: 'connection'
307 * {Socket object} The connection object
309 Emitted when a new connection is made. `socket` is an instance of
314 Emitted when the server closes. Note that if connections exist, this
315 event is not emitted until all connections are ended.
321 Emitted when an error occurs. The ['close'][] event will be called directly
322 following this event. See example in discussion of `server.listen`.
326 This object is an abstraction of a TCP or local socket. `net.Socket`
327 instances implement a duplex Stream interface. They can be created by the
328 user and used as a client (with `connect()`) or they can be created by Node.js
329 and passed to the user through the `'connection'` event of a server.
331 ### new net.Socket([options])
333 Construct a new socket object.
335 `options` is an object with the following defaults:
338 allowHalfOpen: false,
343 `fd` allows you to specify the existing file descriptor of socket.
344 Set `readable` and/or `writable` to `true` to allow reads and/or writes on this
345 socket (NOTE: Works only when `fd` is passed).
346 About `allowHalfOpen`, refer to `createServer()` and `'end'` event.
348 ### socket.connect(options[, connectListener])
350 Opens the connection for a given socket.
352 For TCP sockets, `options` argument should be an object which specifies:
354 - `port`: Port the client should connect to (Required).
356 - `host`: Host the client should connect to. Defaults to `'localhost'`.
358 - `localAddress`: Local interface to bind to for network connections.
360 - `localPort`: Local port to bind to for network connections.
362 - `family` : Version of IP stack. Defaults to `4`.
364 - `lookup` : Custom lookup function. Defaults to `dns.lookup`.
366 For local domain sockets, `options` argument should be an object which
369 - `path`: Path the client should connect to (Required).
371 Normally this method is not needed, as `net.createConnection` opens the
372 socket. Use this only if you are implementing a custom Socket.
374 This function is asynchronous. When the ['connect'][] event is emitted the
375 socket is established. If there is a problem connecting, the `'connect'` event
376 will not be emitted, the `'error'` event will be emitted with the exception.
378 The `connectListener` parameter will be added as a listener for the
381 ### socket.connect(port[, host][, connectListener])
382 ### socket.connect(path[, connectListener])
384 As [socket.connect(options[, connectListener])](#net_socket_connect_options_connectlistener),
385 with options either as either `{port: port, host: host}` or `{path: path}`.
387 ### socket.bufferSize
389 `net.Socket` has the property that `socket.write()` always works. This is to
390 help users get up and running quickly. The computer cannot always keep up
391 with the amount of data that is written to a socket - the network connection
392 simply might be too slow. Node.js will internally queue up the data written to a
393 socket and send it out over the wire when it is possible. (Internally it is
394 polling on the socket's file descriptor for being writable).
396 The consequence of this internal buffering is that memory may grow. This
397 property shows the number of characters currently buffered to be written.
398 (Number of characters is approximately equal to the number of bytes to be
399 written, but the buffer may contain strings, and the strings are lazily
400 encoded, so the exact number of bytes is not known.)
402 Users who experience large or growing `bufferSize` should attempt to
403 "throttle" the data flows in their program with `pause()` and `resume()`.
406 ### socket.setEncoding([encoding])
408 Set the encoding for the socket as a Readable Stream. See
409 [stream.setEncoding()][] for more information.
411 ### socket.write(data[, encoding][, callback])
413 Sends data on the socket. The second parameter specifies the encoding in the
414 case of a string--it defaults to UTF8 encoding.
416 Returns `true` if the entire data was flushed successfully to the kernel
417 buffer. Returns `false` if all or part of the data was queued in user memory.
418 `'drain'` will be emitted when the buffer is again free.
420 The optional `callback` parameter will be executed when the data is finally
421 written out - this may not be immediately.
423 ### socket.end([data][, encoding])
425 Half-closes the socket. i.e., it sends a FIN packet. It is possible the
426 server will still send some data.
428 If `data` is specified, it is equivalent to calling
429 `socket.write(data, encoding)` followed by `socket.end()`.
433 Ensures that no more I/O activity happens on this socket. Only necessary in
434 case of errors (parse error or so).
438 Pauses the reading of data. That is, `'data'` events will not be emitted.
439 Useful to throttle back an upload.
443 Resumes reading after a call to `pause()`.
445 ### socket.setTimeout(timeout[, callback])
447 Sets the socket to timeout after `timeout` milliseconds of inactivity on
448 the socket. By default `net.Socket` do not have a timeout.
450 When an idle timeout is triggered the socket will receive a `'timeout'`
451 event but the connection will not be severed. The user must manually `end()`
452 or `destroy()` the socket.
454 If `timeout` is 0, then the existing idle timeout is disabled.
456 The optional `callback` parameter will be added as a one time listener for the
461 ### socket.setNoDelay([noDelay])
463 Disables the Nagle algorithm. By default TCP connections use the Nagle
464 algorithm, they buffer data before sending it off. Setting `true` for
465 `noDelay` will immediately fire off data each time `socket.write()` is called.
466 `noDelay` defaults to `true`.
470 ### socket.setKeepAlive([enable][, initialDelay])
472 Enable/disable keep-alive functionality, and optionally set the initial
473 delay before the first keepalive probe is sent on an idle socket.
474 `enable` defaults to `false`.
476 Set `initialDelay` (in milliseconds) to set the delay between the last
477 data packet received and the first keepalive probe. Setting 0 for
478 initialDelay will leave the value unchanged from the default
479 (or previous) setting. Defaults to `0`.
485 Returns the bound address, the address family name and port of the
486 socket as reported by the operating system. Returns an object with
487 three properties, e.g.
488 `{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`
492 Calling `unref` on a socket will allow the program to exit if this is the only
493 active socket in the event system. If the socket is already `unref`d calling
494 `unref` again will have no effect.
500 Opposite of `unref`, calling `ref` on a previously `unref`d socket will *not*
501 let the program exit if it's the only socket left (the default behavior). If
502 the socket is `ref`d calling `ref` again will have no effect.
506 ### socket.remoteAddress
508 The string representation of the remote IP address. For example,
509 `'74.125.127.100'` or `'2001:4860:a005::68'`.
511 ### socket.remoteFamily
513 The string representation of the remote IP family. `'IPv4'` or `'IPv6'`.
515 ### socket.remotePort
517 The numeric representation of the remote port. For example,
520 ### socket.localAddress
522 The string representation of the local IP address the remote client is
523 connecting on. For example, if you are listening on `'0.0.0.0'` and the
524 client connects on `'192.168.1.1'`, the value would be `'192.168.1.1'`.
528 The numeric representation of the local port. For example,
533 The amount of received bytes.
535 ### socket.bytesWritten
537 The amount of bytes sent.
540 `net.Socket` instances are [EventEmitter][] with the following events:
544 Emitted after resolving the hostname but before connecting.
545 Not applicable to UNIX sockets.
547 * `err` {Error | Null} The error object. See [dns.lookup()][].
548 * `address` {String} The IP address.
549 * `family` {String | Null} The address type. See [dns.lookup()][].
553 Emitted when a socket connection is successfully established.
560 Emitted when data is received. The argument `data` will be a `Buffer` or
561 `String`. Encoding of data is set by `socket.setEncoding()`.
562 (See the [Readable Stream][] section for more information.)
564 Note that the __data will be lost__ if there is no listener when a `Socket`
565 emits a `'data'` event.
569 Emitted when the other end of the socket sends a FIN packet.
571 By default (`allowHalfOpen == false`) the socket will destroy its file
572 descriptor once it has written out its pending write queue. However, by
573 setting `allowHalfOpen == true` the socket will not automatically `end()`
574 its side allowing the user to write arbitrary amounts of data, with the
575 caveat that the user is required to `end()` their side now.
580 Emitted if the socket times out from inactivity. This is only to notify that
581 the socket has been idle. The user must manually close the connection.
583 See also: `socket.setTimeout()`
588 Emitted when the write buffer becomes empty. Can be used to throttle uploads.
590 See also: the return values of `socket.write()`
596 Emitted when an error occurs. The `'close'` event will be called directly
597 following this event.
601 * `had_error` {Boolean} `true` if the socket had a transmission error.
603 Emitted once the socket is fully closed. The argument `had_error` is a boolean
604 which says if the socket was closed due to a transmission error.
608 Tests if input is an IP address. Returns 0 for invalid strings,
609 returns 4 for IP version 4 addresses, and returns 6 for IP version 6 addresses.
614 Returns true if input is a version 4 IP address, otherwise returns false.
619 Returns true if input is a version 6 IP address, otherwise returns false.
621 ['close']: #net_event_close
622 ['connect']: #net_event_connect
623 ['connection']: #net_event_connection
624 ['end']: #net_event_end
625 [EventEmitter]: events.html#events_class_events_eventemitter
626 ['listening']: #net_event_listening
627 [server.getConnections]: #net_server_getconnections_callback
628 [Readable Stream]: stream.html#stream_class_stream_readable
629 [stream.setEncoding()]: stream.html#stream_readable_setencoding_encoding
630 [dns.lookup()]: dns.html#dns_dns_lookup_hostname_options_callback