doc: update parameter name in net.markdown
[platform/upstream/nodejs.git] / doc / api / net.markdown
1 # net
2
3     Stability: 2 - Stable
4
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');`.
8
9 ## net.createServer([options][, connectionListener])
10
11 Creates a new TCP server. The `connectionListener` argument is
12 automatically set as a listener for the ['connection'][] event.
13
14 `options` is an object with the following defaults:
15
16     {
17       allowHalfOpen: false,
18       pauseOnConnect: false
19     }
20
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.
25
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()`.
30
31 Here is an example of an echo server which listens for connections
32 on port 8124:
33
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');
39       });
40       c.write('hello\r\n');
41       c.pipe(c);
42     });
43     server.listen(8124, function() { //'listening' listener
44       console.log('server bound');
45     });
46
47 Test this by using `telnet`:
48
49     telnet localhost 8124
50
51 To listen on the socket `/tmp/echo.sock` the third line from the last would
52 just be changed to
53
54     server.listen('/tmp/echo.sock', function() { //'listening' listener
55
56 Use `nc` to connect to a UNIX domain socket server:
57
58     nc -U /tmp/echo.sock
59
60 ## net.connect(options[, connectListener])
61 ## net.createConnection(options[, connectListener])
62
63 A factory function, which returns a new ['net.Socket'](#net_class_net_socket)
64 and automatically connects with the supplied `options`.
65
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)
68 method.
69
70 The `connectListener` parameter will be added as a listener for the
71 ['connect'][] event once.
72
73 Here is an example of a client of the previously described echo server:
74
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');
80     });
81     client.on('data', function(data) {
82       console.log(data.toString());
83       client.end();
84     });
85     client.on('end', function() {
86       console.log('disconnected from server');
87     });
88
89 To connect on the socket `/tmp/echo.sock` the second line would just be
90 changed to
91
92     var client = net.connect({path: '/tmp/echo.sock'});
93
94 ## net.connect(port[, host][, connectListener])
95 ## net.createConnection(port[, host][, connectListener])
96
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`.
100
101 If `host` is omitted, `'localhost'` will be assumed.
102
103 The `connectListener` parameter will be added as a listener for the
104 ['connect'][] event once.
105
106 ## net.connect(path[, connectListener])
107 ## net.createConnection(path[, connectListener])
108
109 A factory function, which returns a new unix
110 ['net.Socket'](#net_class_net_socket) and automatically connects to the
111 supplied `path`.
112
113 The `connectListener` parameter will be added as a listener for the
114 ['connect'][] event once.
115
116 ## Class: net.Server
117
118 This class is used to create a TCP or local server.
119
120 ### server.listen(port[, hostname][, backlog][, callback])
121
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.
126
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).
131
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.
135
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
139
140     server.on('error', function (e) {
141       if (e.code == 'EADDRINUSE') {
142         console.log('Address in use, retrying...');
143         setTimeout(function () {
144           server.close();
145           server.listen(PORT, HOST);
146         }, 1000);
147       }
148     });
149
150 (Note: All sockets in Node.js set `SO_REUSEADDR` already)
151
152
153 ### server.listen(path[, callback])
154
155 * `path` {String}
156 * `callback` {Function}
157
158 Start a local socket server listening for connections on the given `path`.
159
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.
163
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*.
168
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:
176
177     net.createServer().listen(
178         path.join('\\\\?\\pipe', process.cwd(), 'myctl'))
179
180 ### server.listen(handle[, callback])
181
182 * `handle` {Object}
183 * `callback` {Function}
184
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.
187
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.
191
192 Listening on a file descriptor is not supported on Windows.
193
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.
198
199 ### server.listen(options[, callback])
200
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.
208
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.
214
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
219 shown below.
220
221     server.listen({
222       host: 'localhost',
223       port: 80,
224       exclusive: true
225     });
226
227 ### server.close([callback])
228
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.
235
236 ### server.address()
237
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' }`
243
244 Example:
245
246     var server = net.createServer(function (socket) {
247       socket.end("goodbye\n");
248     });
249
250     // grab a random port.
251     server.listen(function() {
252       address = server.address();
253       console.log("opened server on %j", address);
254     });
255
256 Don't call `server.address()` until the `'listening'` event has been emitted.
257
258 ### server.unref()
259
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.
263
264 Returns `server`.
265
266 ### server.ref()
267
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.
271
272 Returns `server`.
273
274 ### server.maxConnections
275
276 Set this property to reject connections when the server's connection count gets
277 high.
278
279 It is not recommended to use this option once a socket has been sent to a child
280 with `child_process.fork()`.
281
282 ### server.connections
283
284     Stability: 0 - Deprecated: Use [server.getConnections][] instead.
285
286 The number of concurrent connections on the server.
287
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.
291
292 ### server.getConnections(callback)
293
294 Asynchronously get the number of concurrent connections on the server. Works
295 when sockets were sent to forks.
296
297 Callback should take two arguments `err` and `count`.
298
299 `net.Server` is an [EventEmitter][] with the following events:
300
301 ### Event: 'listening'
302
303 Emitted when the server has been bound after calling `server.listen`.
304
305 ### Event: 'connection'
306
307 * {Socket object} The connection object
308
309 Emitted when a new connection is made. `socket` is an instance of
310 `net.Socket`.
311
312 ### Event: 'close'
313
314 Emitted when the server closes. Note that if connections exist, this
315 event is not emitted until all connections are ended.
316
317 ### Event: 'error'
318
319 * {Error Object}
320
321 Emitted when an error occurs.  The ['close'][] event will be called directly
322 following this event.  See example in discussion of `server.listen`.
323
324 ## Class: net.Socket
325
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.
330
331 ### new net.Socket([options])
332
333 Construct a new socket object.
334
335 `options` is an object with the following defaults:
336
337     { fd: null,
338       allowHalfOpen: false,
339       readable: false,
340       writable: false
341     }
342
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.
347
348 ### socket.connect(options[, connectListener])
349
350 Opens the connection for a given socket.
351
352 For TCP sockets, `options` argument should be an object which specifies:
353
354   - `port`: Port the client should connect to (Required).
355
356   - `host`: Host the client should connect to. Defaults to `'localhost'`.
357
358   - `localAddress`: Local interface to bind to for network connections.
359
360   - `localPort`: Local port to bind to for network connections.
361
362   - `family` : Version of IP stack. Defaults to `4`.
363
364   - `lookup` : Custom lookup function. Defaults to `dns.lookup`.
365
366 For local domain sockets, `options` argument should be an object which
367 specifies:
368
369   - `path`: Path the client should connect to (Required).
370
371 Normally this method is not needed, as `net.createConnection` opens the
372 socket. Use this only if you are implementing a custom Socket.
373
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.
377
378 The `connectListener` parameter will be added as a listener for the
379 ['connect'][] event.
380
381 ### socket.connect(port[, host][, connectListener])
382 ### socket.connect(path[, connectListener])
383
384 As [socket.connect(options[, connectListener])](#net_socket_connect_options_connectlistener),
385 with options either as either `{port: port, host: host}` or `{path: path}`.
386
387 ### socket.bufferSize
388
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).
395
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.)
401
402 Users who experience large or growing `bufferSize` should attempt to
403 "throttle" the data flows in their program with `pause()` and `resume()`.
404
405
406 ### socket.setEncoding([encoding])
407
408 Set the encoding for the socket as a Readable Stream. See
409 [stream.setEncoding()][] for more information.
410
411 ### socket.write(data[, encoding][, callback])
412
413 Sends data on the socket. The second parameter specifies the encoding in the
414 case of a string--it defaults to UTF8 encoding.
415
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.
419
420 The optional `callback` parameter will be executed when the data is finally
421 written out - this may not be immediately.
422
423 ### socket.end([data][, encoding])
424
425 Half-closes the socket. i.e., it sends a FIN packet. It is possible the
426 server will still send some data.
427
428 If `data` is specified, it is equivalent to calling
429 `socket.write(data, encoding)` followed by `socket.end()`.
430
431 ### socket.destroy()
432
433 Ensures that no more I/O activity happens on this socket. Only necessary in
434 case of errors (parse error or so).
435
436 ### socket.pause()
437
438 Pauses the reading of data. That is, `'data'` events will not be emitted.
439 Useful to throttle back an upload.
440
441 ### socket.resume()
442
443 Resumes reading after a call to `pause()`.
444
445 ### socket.setTimeout(timeout[, callback])
446
447 Sets the socket to timeout after `timeout` milliseconds of inactivity on
448 the socket. By default `net.Socket` do not have a timeout.
449
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.
453
454 If `timeout` is 0, then the existing idle timeout is disabled.
455
456 The optional `callback` parameter will be added as a one time listener for the
457 `'timeout'` event.
458
459 Returns `socket`.
460
461 ### socket.setNoDelay([noDelay])
462
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`.
467
468 Returns `socket`.
469
470 ### socket.setKeepAlive([enable][, initialDelay])
471
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`.
475
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`.
480
481 Returns `socket`.
482
483 ### socket.address()
484
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' }`
489
490 ### socket.unref()
491
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.
495
496 Returns `socket`.
497
498 ### socket.ref()
499
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.
503
504 Returns `socket`.
505
506 ### socket.remoteAddress
507
508 The string representation of the remote IP address. For example,
509 `'74.125.127.100'` or `'2001:4860:a005::68'`.
510
511 ### socket.remoteFamily
512
513 The string representation of the remote IP family. `'IPv4'` or `'IPv6'`.
514
515 ### socket.remotePort
516
517 The numeric representation of the remote port. For example,
518 `80` or `21`.
519
520 ### socket.localAddress
521
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'`.
525
526 ### socket.localPort
527
528 The numeric representation of the local port. For example,
529 `80` or `21`.
530
531 ### socket.bytesRead
532
533 The amount of received bytes.
534
535 ### socket.bytesWritten
536
537 The amount of bytes sent.
538
539
540 `net.Socket` instances are [EventEmitter][] with the following events:
541
542 ### Event: 'lookup'
543
544 Emitted after resolving the hostname but before connecting.
545 Not applicable to UNIX sockets.
546
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()][].
550
551 ### Event: 'connect'
552
553 Emitted when a socket connection is successfully established.
554 See `connect()`.
555
556 ### Event: 'data'
557
558 * {Buffer object}
559
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.)
563
564 Note that the __data will be lost__ if there is no listener when a `Socket`
565 emits a `'data'` event.
566
567 ### Event: 'end'
568
569 Emitted when the other end of the socket sends a FIN packet.
570
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.
576
577
578 ### Event: 'timeout'
579
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.
582
583 See also: `socket.setTimeout()`
584
585
586 ### Event: 'drain'
587
588 Emitted when the write buffer becomes empty. Can be used to throttle uploads.
589
590 See also: the return values of `socket.write()`
591
592 ### Event: 'error'
593
594 * {Error object}
595
596 Emitted when an error occurs.  The `'close'` event will be called directly
597 following this event.
598
599 ### Event: 'close'
600
601 * `had_error` {Boolean} `true` if the socket had a transmission error.
602
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.
605
606 ## net.isIP(input)
607
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.
610
611
612 ## net.isIPv4(input)
613
614 Returns true if input is a version 4 IP address, otherwise returns false.
615
616
617 ## net.isIPv6(input)
618
619 Returns true if input is a version 6 IP address, otherwise returns false.
620
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