36864f2699208ee1bbe97023705f6a78677f4e7a
[platform/upstream/nodejs.git] / doc / api / net.markdown
1 # net
2
3     Stability: 3 - Stable
4
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');`
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     { allowHalfOpen: false
17     }
18
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.
23
24 Here is an example of an echo server which listens for connections
25 on port 8124:
26
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');
32       });
33       c.write('hello\r\n');
34       c.pipe(c);
35     });
36     server.listen(8124, function() { //'listening' listener
37       console.log('server bound');
38     });
39
40 Test this by using `telnet`:
41
42     telnet localhost 8124
43
44 To listen on the socket `/tmp/echo.sock` the third line from the last would
45 just be changed to
46
47     server.listen('/tmp/echo.sock', function() { //'listening' listener
48
49 Use `nc` to connect to a UNIX domain socket server:
50
51     nc -U /tmp/echo.sock
52
53 ## net.connect(options[, connectionListener])
54 ## net.createConnection(options[, connectionListener])
55
56 A factory method, which returns a new ['net.Socket'](#net_class_net_socket)
57 and connects to the supplied address and port.
58
59 When the socket is established, the ['connect'][] event will be emitted.
60
61 Has the same events as ['net.Socket'](#net_class_net_socket).
62
63 For TCP sockets, `options` argument should be an object which specifies:
64
65   - `port`: Port the client should connect to (Required).
66
67   - `host`: Host the client should connect to. Defaults to `'localhost'`.
68
69   - `localAddress`: Local interface to bind to for network connections.
70
71   - `localPort`: Local port to bind to for network connections.
72
73   - `family` : Version of IP stack. Defaults to `4`.
74
75 For local domain sockets, `options` argument should be an object which
76 specifies:
77
78   - `path`: Path the client should connect to (Required).
79
80 Common options are:
81
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.
85
86 The `connectListener` parameter will be added as an listener for the
87 ['connect'][] event.
88
89 Here is an example of a client of echo server as described previously:
90
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');
96     });
97     client.on('data', function(data) {
98       console.log(data.toString());
99       client.end();
100     });
101     client.on('end', function() {
102       console.log('client disconnected');
103     });
104
105 To connect on the socket `/tmp/echo.sock` the second line would just be
106 changed to
107
108     var client = net.connect({path: '/tmp/echo.sock'});
109
110 ## net.connect(port[, host]\[, connectListener])
111 ## net.createConnection(port[, host]\[, connectListener])
112
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
116 ['connect'][] event.
117
118 Is a factory method which returns a new ['net.Socket'](#net_class_net_socket).
119
120 ## net.connect(path[, connectListener])
121 ## net.createConnection(path[, connectListener])
122
123 Creates unix socket connection to `path`.
124 The `connectListener` parameter will be added as an listener for the
125 ['connect'][] event.
126
127 A factory method which returns a new ['net.Socket'](#net_class_net_socket).
128
129 ## Class: net.Server
130
131 This class is used to create a TCP or local server.
132
133 ### server.listen(port[, host]\[, backlog]\[, callback])
134
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.
138
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).
143
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.
147
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
151
152     server.on('error', function (e) {
153       if (e.code == 'EADDRINUSE') {
154         console.log('Address in use, retrying...');
155         setTimeout(function () {
156           server.close();
157           server.listen(PORT, HOST);
158         }, 1000);
159       }
160     });
161
162 (Note: All sockets in Node set `SO_REUSEADDR` already)
163
164
165 ### server.listen(path[, callback])
166
167 * `path` {String}
168 * `callback` {Function}
169
170 Start a local socket server listening for connections on the given `path`.
171
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.
175
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*.
180
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:
188
189     net.createServer().listen(
190         path.join('\\\\?\\pipe', process.cwd(), 'myctl'))
191
192 ### server.listen(handle[, callback])
193
194 * `handle` {Object}
195 * `callback` {Function}
196
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.
199
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.
203
204 Listening on a file descriptor is not supported on Windows.
205
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.
210
211 ### server.listen(options[, callback])
212
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.
220
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.
226
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
231 shown below.
232
233     server.listen({
234       host: 'localhost',
235       port: 80,
236       exclusive: true
237     });
238
239 ### server.close([callback])
240
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.
247
248 ### server.address()
249
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' }`
255
256 Example:
257
258     var server = net.createServer(function (socket) {
259       socket.end("goodbye\n");
260     });
261
262     // grab a random port.
263     server.listen(function() {
264       address = server.address();
265       console.log("opened server on %j", address);
266     });
267
268 Don't call `server.address()` until the `'listening'` event has been emitted.
269
270 ### server.unref()
271
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.
275
276 ### server.ref()
277
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.
281
282 ### server.maxConnections
283
284 Set this property to reject connections when the server's connection count gets
285 high.
286
287 It is not recommended to use this option once a socket has been sent to a child
288 with `child_process.fork()`.
289
290 ### server.connections
291
292 This function is **deprecated**; please use [server.getConnections()][] instead.
293 The number of concurrent connections on the server.
294
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.
298
299 ### server.getConnections(callback)
300
301 Asynchronously get the number of concurrent connections on the server. Works
302 when sockets were sent to forks.
303
304 Callback should take two arguments `err` and `count`.
305
306 `net.Server` is an [EventEmitter][] with the following events:
307
308 ### Event: 'listening'
309
310 Emitted when the server has been bound after calling `server.listen`.
311
312 ### Event: 'connection'
313
314 * {Socket object} The connection object
315
316 Emitted when a new connection is made. `socket` is an instance of
317 `net.Socket`.
318
319 ### Event: 'close'
320
321 Emitted when the server closes. Note that if connections exist, this
322 event is not emitted until all connections are ended.
323
324 ### Event: 'error'
325
326 * {Error Object}
327
328 Emitted when an error occurs.  The `'close'` event will be called directly
329 following this event.  See example in discussion of `server.listen`.
330
331 ## Class: net.Socket
332
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.
337
338 ### new net.Socket([options])
339
340 Construct a new socket object.
341
342 `options` is an object with the following defaults:
343
344     { fd: null
345       allowHalfOpen: false,
346       readable: false,
347       writable: false
348     }
349
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.
354
355 ### socket.connect(port[, host]\[, connectListener])
356 ### socket.connect(path[, connectListener])
357
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.
362
363 Normally this method is not needed, as `net.createConnection` opens the
364 socket. Use this only if you are implementing a custom Socket.
365
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.
369
370 The `connectListener` parameter will be added as an listener for the
371 ['connect'][] event.
372
373
374 ### socket.bufferSize
375
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).
382
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.)
388
389 Users who experience large or growing `bufferSize` should attempt to
390 "throttle" the data flows in their program with `pause()` and `resume()`.
391
392
393 ### socket.setEncoding([encoding])
394
395 Set the encoding for the socket as a Readable Stream. See
396 [stream.setEncoding()][] for more information.
397
398 ### socket.write(data[, encoding]\[, callback])
399
400 Sends data on the socket. The second parameter specifies the encoding in the
401 case of a string--it defaults to UTF8 encoding.
402
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.
406
407 The optional `callback` parameter will be executed when the data is finally
408 written out - this may not be immediately.
409
410 ### socket.end([data]\[, encoding])
411
412 Half-closes the socket. i.e., it sends a FIN packet. It is possible the
413 server will still send some data.
414
415 If `data` is specified, it is equivalent to calling
416 `socket.write(data, encoding)` followed by `socket.end()`.
417
418 ### socket.destroy()
419
420 Ensures that no more I/O activity happens on this socket. Only necessary in
421 case of errors (parse error or so).
422
423 ### socket.pause()
424
425 Pauses the reading of data. That is, `'data'` events will not be emitted.
426 Useful to throttle back an upload.
427
428 ### socket.resume()
429
430 Resumes reading after a call to `pause()`.
431
432 ### socket.setTimeout(timeout[, callback])
433
434 Sets the socket to timeout after `timeout` milliseconds of inactivity on
435 the socket. By default `net.Socket` do not have a timeout.
436
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.
440
441 If `timeout` is 0, then the existing idle timeout is disabled.
442
443 The optional `callback` parameter will be added as a one time listener for the
444 `'timeout'` event.
445
446 ### socket.setNoDelay([noDelay])
447
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`.
452
453 ### socket.setKeepAlive([enable]\[, initialDelay])
454
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`.
458
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`.
463
464 ### socket.address()
465
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' }`
470
471 ### socket.unref()
472
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.
476
477 ### socket.ref()
478
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.
482
483 ### socket.remoteAddress
484
485 The string representation of the remote IP address. For example,
486 `'74.125.127.100'` or `'2001:4860:a005::68'`.
487
488 ### socket.remoteFamily
489
490 The string representation of the remote IP family. `'IPv4'` or `'IPv6'`.
491
492 ### socket.remotePort
493
494 The numeric representation of the remote port. For example,
495 `80` or `21`.
496
497 ### socket.localAddress
498
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'`.
502
503 ### socket.localPort
504
505 The numeric representation of the local port. For example,
506 `80` or `21`.
507
508 ### socket.bytesRead
509
510 The amount of received bytes.
511
512 ### socket.bytesWritten
513
514 The amount of bytes sent.
515
516
517 `net.Socket` instances are [EventEmitter][] with the following events:
518
519 ### Event: 'lookup'
520
521 Emitted after resolving the hostname but before connecting.
522 Not applicable to UNIX sockets.
523
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()][].
527
528 ### Event: 'connect'
529
530 Emitted when a socket connection is successfully established.
531 See `connect()`.
532
533 ### Event: 'data'
534
535 * {Buffer object}
536
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.)
540
541 Note that the __data will be lost__ if there is no listener when a `Socket`
542 emits a `'data'` event.
543
544 ### Event: 'end'
545
546 Emitted when the other end of the socket sends a FIN packet.
547
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.
553
554
555 ### Event: 'timeout'
556
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.
559
560 See also: `socket.setTimeout()`
561
562
563 ### Event: 'drain'
564
565 Emitted when the write buffer becomes empty. Can be used to throttle uploads.
566
567 See also: the return values of `socket.write()`
568
569 ### Event: 'error'
570
571 * {Error object}
572
573 Emitted when an error occurs.  The `'close'` event will be called directly
574 following this event.
575
576 ### Event: 'close'
577
578 * `had_error` {Boolean} true if the socket had a transmission error
579
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.
582
583 ## net.isIP(input)
584
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.
587
588
589 ## net.isIPv4(input)
590
591 Returns true if input is a version 4 IP address, otherwise returns false.
592
593
594 ## net.isIPv6(input)
595
596 Returns true if input is a version 6 IP address, otherwise returns false.
597
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