5 The `net` module provides you with an asynchronous network wrapper. It contains
6 methods 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:
16 { allowHalfOpen: false
19 If `allowHalfOpen` is `true`, then the socket won't automatically send a FIN
20 packet when the other end of the socket sends a FIN packet. The socket becomes
21 non-readable, but still writable. You should call the `end()` method explicitly.
22 See ['end'][] event for more information.
24 Here is an example of an echo server which listens for connections
27 var net = require('net');
28 var server = net.createServer(function(c) { //'connection' listener
29 console.log('server connected');
30 c.on('end', function() {
31 console.log('server disconnected');
36 server.listen(8124, function() { //'listening' listener
37 console.log('server bound');
40 Test this by using `telnet`:
44 To listen on the socket `/tmp/echo.sock` the third line from the last would
47 server.listen('/tmp/echo.sock', function() { //'listening' listener
49 Use `nc` to connect to a UNIX domain socket server:
53 ## net.connect(options[, connectionListener])
54 ## net.createConnection(options[, connectionListener])
56 A factory method, which returns a new ['net.Socket'](#net_class_net_socket)
57 and connects to the supplied address and port.
59 When the socket is established, the ['connect'][] event will be emitted.
61 Has the same events as ['net.Socket'](#net_class_net_socket).
63 For TCP sockets, `options` argument should be an object which specifies:
65 - `port`: Port the client should connect to (Required).
67 - `host`: Host the client should connect to. Defaults to `'localhost'`.
69 - `localAddress`: Local interface to bind to for network connections.
71 - `localPort`: Local port to bind to for network connections.
73 - `family` : Version of IP stack. Defaults to `4`.
75 For local domain sockets, `options` argument should be an object which
78 - `path`: Path the client should connect to (Required).
82 - `allowHalfOpen`: if `true`, the socket won't automatically send
83 a FIN packet when the other end of the socket sends a FIN packet.
84 Defaults to `false`. See ['end'][] event for more information.
86 The `connectListener` parameter will be added as an listener for the
89 Here is an example of a client of echo server as described previously:
91 var net = require('net');
92 var client = net.connect({port: 8124},
93 function() { //'connect' listener
94 console.log('client connected');
95 client.write('world!\r\n');
97 client.on('data', function(data) {
98 console.log(data.toString());
101 client.on('end', function() {
102 console.log('client disconnected');
105 To connect on the socket `/tmp/echo.sock` the second line would just be
108 var client = net.connect({path: '/tmp/echo.sock'});
110 ## net.connect(port[, host]\[, connectListener])
111 ## net.createConnection(port[, host]\[, connectListener])
113 Creates a TCP connection to `port` on `host`. If `host` is omitted,
114 `'localhost'` will be assumed.
115 The `connectListener` parameter will be added as an listener for the
118 Is a factory method which returns a new ['net.Socket'](#net_class_net_socket).
120 ## net.connect(path[, connectListener])
121 ## net.createConnection(path[, connectListener])
123 Creates unix socket connection to `path`.
124 The `connectListener` parameter will be added as an listener for the
127 A factory method which returns a new ['net.Socket'](#net_class_net_socket).
131 This class is used to create a TCP or local server.
133 ### server.listen(port[, host]\[, backlog]\[, callback])
135 Begin accepting connections on the specified `port` and `host`. If the
136 `host` is omitted, the server will accept connections directed to any
137 IPv4 address (`INADDR_ANY`). A port value of zero will assign a random port.
139 Backlog is the maximum length of the queue of pending connections.
140 The actual length will be determined by your OS through sysctl settings such as
141 `tcp_max_syn_backlog` and `somaxconn` on linux. The default value of this
142 parameter is 511 (not 512).
144 This function is asynchronous. When the server has been bound,
145 ['listening'][] event will be emitted. The last parameter `callback`
146 will be added as an listener for the ['listening'][] event.
148 One issue some users run into is getting `EADDRINUSE` errors. This means that
149 another server is already running on the requested port. One way of handling this
150 would be to wait a second and then try again. This can be done with
152 server.on('error', function (e) {
153 if (e.code == 'EADDRINUSE') {
154 console.log('Address in use, retrying...');
155 setTimeout(function () {
157 server.listen(PORT, HOST);
162 (Note: All sockets in Node set `SO_REUSEADDR` already)
165 ### server.listen(path[, callback])
168 * `callback` {Function}
170 Start a local socket server listening for connections on the given `path`.
172 This function is asynchronous. When the server has been bound,
173 ['listening'][] event will be emitted. The last parameter `callback`
174 will be added as an listener for the ['listening'][] event.
176 On UNIX, the local domain is usually known as the UNIX domain. The path is a
177 filesystem path name. It is subject to the same naming conventions and
178 permissions checks as would be done on file creation, will be visible in the
179 filesystem, and will *persist until unlinked*.
181 On Windows, the local domain is implemented using a named pipe. The path *must*
182 refer to an entry in `\\?\pipe\` or `\\.\pipe\`. Any characters are permitted,
183 but the latter may do some processing of pipe names, such as resolving `..`
184 sequences. Despite appearances, the pipe name space is flat. Pipes will *not
185 persist*, they are removed when the last reference to them is closed. Do not
186 forget javascript string escaping requires paths to be specified with
187 double-backslashes, such as:
189 net.createServer().listen(
190 path.join('\\\\?\\pipe', process.cwd(), 'myctl'))
192 ### server.listen(handle[, callback])
195 * `callback` {Function}
197 The `handle` object can be set to either a server or socket (anything
198 with an underlying `_handle` member), or a `{fd: <n>}` object.
200 This will cause the server to accept connections on the specified
201 handle, but it is presumed that the file descriptor or handle has
202 already been bound to a port or domain socket.
204 Listening on a file descriptor is not supported on Windows.
206 This function is asynchronous. When the server has been bound,
207 ['listening'][] event will be emitted.
208 the last parameter `callback` will be added as an listener for the
209 ['listening'][] event.
211 ### server.listen(options[, callback])
213 * `options` {Object} - Required. Supports the following properties:
214 * `port` {Number} - Optional.
215 * `host` {String} - Optional.
216 * `backlog` {Number} - Optional.
217 * `path` {String} - Optional.
218 * `exclusive` {Boolean} - Optional.
219 * `callback` {Function} - Optional.
221 The `port`, `host`, and `backlog` properties of `options`, as well as the
222 optional callback function, behave as they do on a call to
223 [server.listen(port, \[host\], \[backlog\], \[callback\])
224 ](#net_server_listen_port_host_backlog_callback). Alternatively, the `path`
225 option can be used to specify a UNIX socket.
227 If `exclusive` is `false` (default), then cluster workers will use the same
228 underlying handle, allowing connection handling duties to be shared. When
229 `exclusive` is `true`, the handle is not shared, and attempted port sharing
230 results in an error. An example which listens on an exclusive port is
239 ### server.close([callback])
241 Stops the server from accepting new connections and keeps existing
242 connections. This function is asynchronous, the server is finally
243 closed when all connections are ended and the server emits a `'close'`
244 event. Optionally, you can pass a callback to listen for the `'close'`
245 event. If present, the callback is invoked with any potential error
246 as the first and only argument.
250 Returns the bound address, the address family name and port of the server
251 as reported by the operating system.
252 Useful to find which port was assigned when giving getting an OS-assigned address.
253 Returns an object with three properties, e.g.
254 `{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`
258 var server = net.createServer(function (socket) {
259 socket.end("goodbye\n");
262 // grab a random port.
263 server.listen(function() {
264 address = server.address();
265 console.log("opened server on %j", address);
268 Don't call `server.address()` until the `'listening'` event has been emitted.
272 Calling `unref` on a server will allow the program to exit if this is the only
273 active server in the event system. If the server is already `unref`d calling
274 `unref` again will have no effect.
278 Opposite of `unref`, calling `ref` on a previously `unref`d server will *not*
279 let the program exit if it's the only server left (the default behavior). If
280 the server is `ref`d calling `ref` again will have no effect.
282 ### server.maxConnections
284 Set this property to reject connections when the server's connection count gets
287 It is not recommended to use this option once a socket has been sent to a child
288 with `child_process.fork()`.
290 ### server.connections
292 This function is **deprecated**; please use [server.getConnections()][] instead.
293 The number of concurrent connections on the server.
295 This becomes `null` when sending a socket to a child with
296 `child_process.fork()`. To poll forks and get current number of active
297 connections use asynchronous `server.getConnections` instead.
299 ### server.getConnections(callback)
301 Asynchronously get the number of concurrent connections on the server. Works
302 when sockets were sent to forks.
304 Callback should take two arguments `err` and `count`.
306 `net.Server` is an [EventEmitter][] with the following events:
308 ### Event: 'listening'
310 Emitted when the server has been bound after calling `server.listen`.
312 ### Event: 'connection'
314 * {Socket object} The connection object
316 Emitted when a new connection is made. `socket` is an instance of
321 Emitted when the server closes. Note that if connections exist, this
322 event is not emitted until all connections are ended.
328 Emitted when an error occurs. The `'close'` event will be called directly
329 following this event. See example in discussion of `server.listen`.
333 This object is an abstraction of a TCP or local socket. `net.Socket`
334 instances implement a duplex Stream interface. They can be created by the
335 user and used as a client (with `connect()`) or they can be created by Node
336 and passed to the user through the `'connection'` event of a server.
338 ### new net.Socket([options])
340 Construct a new socket object.
342 `options` is an object with the following defaults:
345 allowHalfOpen: false,
350 `fd` allows you to specify the existing file descriptor of socket.
351 Set `readable` and/or `writable` to `true` to allow reads and/or writes on this
352 socket (NOTE: Works only when `fd` is passed).
353 About `allowHalfOpen`, refer to `createServer()` and `'end'` event.
355 ### socket.connect(port[, host]\[, connectListener])
356 ### socket.connect(path[, connectListener])
358 Opens the connection for a given socket. If `port` and `host` are given,
359 then the socket will be opened as a TCP socket, if `host` is omitted,
360 `localhost` will be assumed. If a `path` is given, the socket will be
361 opened as a unix socket to that path.
363 Normally this method is not needed, as `net.createConnection` opens the
364 socket. Use this only if you are implementing a custom Socket.
366 This function is asynchronous. When the ['connect'][] event is emitted the
367 socket is established. If there is a problem connecting, the `'connect'` event
368 will not be emitted, the `'error'` event will be emitted with the exception.
370 The `connectListener` parameter will be added as an listener for the
374 ### socket.bufferSize
376 `net.Socket` has the property that `socket.write()` always works. This is to
377 help users get up and running quickly. The computer cannot always keep up
378 with the amount of data that is written to a socket - the network connection
379 simply might be too slow. Node will internally queue up the data written to a
380 socket and send it out over the wire when it is possible. (Internally it is
381 polling on the socket's file descriptor for being writable).
383 The consequence of this internal buffering is that memory may grow. This
384 property shows the number of characters currently buffered to be written.
385 (Number of characters is approximately equal to the number of bytes to be
386 written, but the buffer may contain strings, and the strings are lazily
387 encoded, so the exact number of bytes is not known.)
389 Users who experience large or growing `bufferSize` should attempt to
390 "throttle" the data flows in their program with `pause()` and `resume()`.
393 ### socket.setEncoding([encoding])
395 Set the encoding for the socket as a Readable Stream. See
396 [stream.setEncoding()][] for more information.
398 ### socket.write(data[, encoding]\[, callback])
400 Sends data on the socket. The second parameter specifies the encoding in the
401 case of a string--it defaults to UTF8 encoding.
403 Returns `true` if the entire data was flushed successfully to the kernel
404 buffer. Returns `false` if all or part of the data was queued in user memory.
405 `'drain'` will be emitted when the buffer is again free.
407 The optional `callback` parameter will be executed when the data is finally
408 written out - this may not be immediately.
410 ### socket.end([data]\[, encoding])
412 Half-closes the socket. i.e., it sends a FIN packet. It is possible the
413 server will still send some data.
415 If `data` is specified, it is equivalent to calling
416 `socket.write(data, encoding)` followed by `socket.end()`.
420 Ensures that no more I/O activity happens on this socket. Only necessary in
421 case of errors (parse error or so).
425 Pauses the reading of data. That is, `'data'` events will not be emitted.
426 Useful to throttle back an upload.
430 Resumes reading after a call to `pause()`.
432 ### socket.setTimeout(timeout[, callback])
434 Sets the socket to timeout after `timeout` milliseconds of inactivity on
435 the socket. By default `net.Socket` do not have a timeout.
437 When an idle timeout is triggered the socket will receive a `'timeout'`
438 event but the connection will not be severed. The user must manually `end()`
439 or `destroy()` the socket.
441 If `timeout` is 0, then the existing idle timeout is disabled.
443 The optional `callback` parameter will be added as a one time listener for the
446 ### socket.setNoDelay([noDelay])
448 Disables the Nagle algorithm. By default TCP connections use the Nagle
449 algorithm, they buffer data before sending it off. Setting `true` for
450 `noDelay` will immediately fire off data each time `socket.write()` is called.
451 `noDelay` defaults to `true`.
453 ### socket.setKeepAlive([enable]\[, initialDelay])
455 Enable/disable keep-alive functionality, and optionally set the initial
456 delay before the first keepalive probe is sent on an idle socket.
457 `enable` defaults to `false`.
459 Set `initialDelay` (in milliseconds) to set the delay between the last
460 data packet received and the first keepalive probe. Setting 0 for
461 initialDelay will leave the value unchanged from the default
462 (or previous) setting. Defaults to `0`.
466 Returns the bound address, the address family name and port of the
467 socket as reported by the operating system. Returns an object with
468 three properties, e.g.
469 `{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`
473 Calling `unref` on a socket will allow the program to exit if this is the only
474 active socket in the event system. If the socket is already `unref`d calling
475 `unref` again will have no effect.
479 Opposite of `unref`, calling `ref` on a previously `unref`d socket will *not*
480 let the program exit if it's the only socket left (the default behavior). If
481 the socket is `ref`d calling `ref` again will have no effect.
483 ### socket.remoteAddress
485 The string representation of the remote IP address. For example,
486 `'74.125.127.100'` or `'2001:4860:a005::68'`.
488 ### socket.remoteFamily
490 The string representation of the remote IP family. `'IPv4'` or `'IPv6'`.
492 ### socket.remotePort
494 The numeric representation of the remote port. For example,
497 ### socket.localAddress
499 The string representation of the local IP address the remote client is
500 connecting on. For example, if you are listening on `'0.0.0.0'` and the
501 client connects on `'192.168.1.1'`, the value would be `'192.168.1.1'`.
505 The numeric representation of the local port. For example,
510 The amount of received bytes.
512 ### socket.bytesWritten
514 The amount of bytes sent.
517 `net.Socket` instances are [EventEmitter][] with the following events:
521 Emitted after resolving the hostname but before connecting.
522 Not applicable to UNIX sockets.
524 * `err` {Error | Null} The error object. See [dns.lookup()][].
525 * `address` {String} The IP address.
526 * `family` {String | Null} The address type. See [dns.lookup()][].
530 Emitted when a socket connection is successfully established.
537 Emitted when data is received. The argument `data` will be a `Buffer` or
538 `String`. Encoding of data is set by `socket.setEncoding()`.
539 (See the [Readable Stream][] section for more information.)
541 Note that the __data will be lost__ if there is no listener when a `Socket`
542 emits a `'data'` event.
546 Emitted when the other end of the socket sends a FIN packet.
548 By default (`allowHalfOpen == false`) the socket will destroy its file
549 descriptor once it has written out its pending write queue. However, by
550 setting `allowHalfOpen == true` the socket will not automatically `end()`
551 its side allowing the user to write arbitrary amounts of data, with the
552 caveat that the user is required to `end()` their side now.
557 Emitted if the socket times out from inactivity. This is only to notify that
558 the socket has been idle. The user must manually close the connection.
560 See also: `socket.setTimeout()`
565 Emitted when the write buffer becomes empty. Can be used to throttle uploads.
567 See also: the return values of `socket.write()`
573 Emitted when an error occurs. The `'close'` event will be called directly
574 following this event.
578 * `had_error` {Boolean} true if the socket had a transmission error
580 Emitted once the socket is fully closed. The argument `had_error` is a boolean
581 which says if the socket was closed due to a transmission error.
585 Tests if input is an IP address. Returns 0 for invalid strings,
586 returns 4 for IP version 4 addresses, and returns 6 for IP version 6 addresses.
591 Returns true if input is a version 4 IP address, otherwise returns false.
596 Returns true if input is a version 6 IP address, otherwise returns false.
598 ['connect']: #net_event_connect
599 ['connection']: #net_event_connection
600 ['end']: #net_event_end
601 [EventEmitter]: events.html#events_class_events_eventemitter
602 ['listening']: #net_event_listening
603 [server.getConnections()]: #net_server_getconnections_callback
604 [Readable Stream]: stream.html#stream_readable_stream
605 [stream.setEncoding()]: stream.html#stream_stream_setencoding_encoding