PageRenderTime 36ms CodeModel.GetById 2ms app.highlight 30ms RepoModel.GetById 1ms app.codeStats 0ms

/doc/api/net.markdown

https://github.com/osfreak/node
Markdown | 565 lines | 376 code | 189 blank | 0 comment | 0 complexity | 92cbd4b86067910a5673a50578b7248c MD5 | raw file
  1# net
  2
  3    Stability: 3 - Stable
  4
  5The `net` module provides you with an asynchronous network wrapper. It contains
  6methods for creating both servers and clients (called streams). You can include
  7this module with `require('net');`
  8
  9## net.createServer([options], [connectionListener])
 10
 11Creates a new TCP server. The `connectionListener` argument is
 12automatically set as a listener for the ['connection'][] event.
 13
 14`options` is an object with the following defaults:
 15
 16    { allowHalfOpen: false
 17    }
 18
 19If `allowHalfOpen` is `true`, then the socket won't automatically send a FIN
 20packet when the other end of the socket sends a FIN packet. The socket becomes
 21non-readable, but still writable. You should call the `end()` method explicitly.
 22See ['end'][] event for more information.
 23
 24Here is an example of an echo server which listens for connections
 25on 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
 40Test this by using `telnet`:
 41
 42    telnet localhost 8124
 43
 44To listen on the socket `/tmp/echo.sock` the third line from the last would
 45just be changed to
 46
 47    server.listen('/tmp/echo.sock', function() { //'listening' listener
 48
 49Use `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
 56Constructs a new socket object and opens the socket to the given location.
 57When the socket is established, the ['connect'][] event will be emitted.
 58
 59For TCP sockets, `options` argument should be an object which specifies:
 60
 61  - `port`: Port the client should connect to (Required).
 62
 63  - `host`: Host the client should connect to. Defaults to `'localhost'`.
 64
 65  - `localAddress`: Local interface to bind to for network connections.
 66
 67  - `localPort`: Local port to bind to for network connections.
 68
 69  - `family` : Version of IP stack. Defaults to `4`.
 70
 71For local domain sockets, `options` argument should be an object which
 72specifies:
 73
 74  - `path`: Path the client should connect to (Required).
 75
 76Common options are:
 77
 78  - `allowHalfOpen`: if `true`, the socket won't automatically send
 79    a FIN packet when the other end of the socket sends a FIN packet.
 80    Defaults to `false`.  See ['end'][] event for more information.
 81
 82The `connectListener` parameter will be added as an listener for the
 83['connect'][] event.
 84
 85Here is an example of a client of echo server as described previously:
 86
 87    var net = require('net');
 88    var client = net.connect({port: 8124},
 89        function() { //'connect' listener
 90      console.log('client connected');
 91      client.write('world!\r\n');
 92    });
 93    client.on('data', function(data) {
 94      console.log(data.toString());
 95      client.end();
 96    });
 97    client.on('end', function() {
 98      console.log('client disconnected');
 99    });
100
101To connect on the socket `/tmp/echo.sock` the second line would just be
102changed to
103
104    var client = net.connect({path: '/tmp/echo.sock'});
105
106## net.connect(port, [host], [connectListener])
107## net.createConnection(port, [host], [connectListener])
108
109Creates a TCP connection to `port` on `host`. If `host` is omitted,
110`'localhost'` will be assumed.
111The `connectListener` parameter will be added as an listener for the
112['connect'][] event.
113
114## net.connect(path, [connectListener])
115## net.createConnection(path, [connectListener])
116
117Creates unix socket connection to `path`.
118The `connectListener` parameter will be added as an listener for the
119['connect'][] event.
120
121## Class: net.Server
122
123This class is used to create a TCP or local server.
124
125### server.listen(port, [host], [backlog], [callback])
126
127Begin accepting connections on the specified `port` and `host`.  If the
128`host` is omitted, the server will accept connections directed to any
129IPv4 address (`INADDR_ANY`). A port value of zero will assign a random port.
130
131Backlog is the maximum length of the queue of pending connections.
132The actual length will be determined by your OS through sysctl settings such as
133`tcp_max_syn_backlog` and `somaxconn` on linux. The default value of this
134parameter is 511 (not 512).
135
136This function is asynchronous.  When the server has been bound,
137['listening'][] event will be emitted.  The last parameter `callback`
138will be added as an listener for the ['listening'][] event.
139
140One issue some users run into is getting `EADDRINUSE` errors. This means that
141another server is already running on the requested port. One way of handling this
142would be to wait a second and then try again. This can be done with
143
144    server.on('error', function (e) {
145      if (e.code == 'EADDRINUSE') {
146        console.log('Address in use, retrying...');
147        setTimeout(function () {
148          server.close();
149          server.listen(PORT, HOST);
150        }, 1000);
151      }
152    });
153
154(Note: All sockets in Node set `SO_REUSEADDR` already)
155
156
157### server.listen(path, [callback])
158
159* `path` {String}
160* `callback` {Function}
161
162Start a local socket server listening for connections on the given `path`.
163
164This function is asynchronous.  When the server has been bound,
165['listening'][] event will be emitted.  The last parameter `callback`
166will be added as an listener for the ['listening'][] event.
167
168On UNIX, the local domain is usually known as the UNIX domain. The path is a
169filesystem path name. It is subject to the same naming conventions and
170permissions checks as would be done on file creation, will be visible in the
171filesystem, and will *persist until unlinked*.
172
173On Windows, the local domain is implemented using a named pipe. The path *must*
174refer to an entry in `\\?\pipe\` or `\\.\pipe\`. Any characters are permitted,
175but the latter may do some processing of pipe names, such as resolving `..`
176sequences. Despite appearances, the pipe name space is flat.  Pipes will *not
177persist*, they are removed when the last reference to them is closed. Do not
178forget javascript string escaping requires paths to be specified with
179double-backslashes, such as:
180
181    net.createServer().listen(
182        path.join('\\\\?\\pipe', process.cwd(), 'myctl'))
183
184### server.listen(handle, [callback])
185
186* `handle` {Object}
187* `callback` {Function}
188
189The `handle` object can be set to either a server or socket (anything
190with an underlying `_handle` member), or a `{fd: <n>}` object.
191
192This will cause the server to accept connections on the specified
193handle, but it is presumed that the file descriptor or handle has
194already been bound to a port or domain socket.
195
196Listening on a file descriptor is not supported on Windows.
197
198This function is asynchronous.  When the server has been bound,
199['listening'][] event will be emitted.
200the last parameter `callback` will be added as an listener for the
201['listening'][] event.
202
203### server.close([callback])
204
205Stops the server from accepting new connections and keeps existing
206connections. This function is asynchronous, the server is finally
207closed when all connections are ended and the server emits a `'close'`
208event. Optionally, you can pass a callback to listen for the `'close'`
209event. If present, the callback is invoked with any potential error
210as the first and only argument.
211
212### server.address()
213
214Returns the bound address, the address family name and port of the server
215as reported by the operating system.
216Useful to find which port was assigned when giving getting an OS-assigned address.
217Returns an object with three properties, e.g.
218`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`
219
220Example:
221
222    var server = net.createServer(function (socket) {
223      socket.end("goodbye\n");
224    });
225
226    // grab a random port.
227    server.listen(function() {
228      address = server.address();
229      console.log("opened server on %j", address);
230    });
231
232Don't call `server.address()` until the `'listening'` event has been emitted.
233
234### server.unref()
235
236Calling `unref` on a server will allow the program to exit if this is the only
237active server in the event system. If the server is already `unref`d calling
238`unref` again will have no effect.
239
240### server.ref()
241
242Opposite of `unref`, calling `ref` on a previously `unref`d server will *not*
243let the program exit if it's the only server left (the default behavior). If
244the server is `ref`d calling `ref` again will have no effect.
245
246### server.maxConnections
247
248Set this property to reject connections when the server's connection count gets
249high.
250
251It is not recommended to use this option once a socket has been sent to a child
252with `child_process.fork()`.
253
254### server.connections
255
256This function is **deprecated**; please use [server.getConnections()][] instead.
257The number of concurrent connections on the server.
258
259This becomes `null` when sending a socket to a child with
260`child_process.fork()`. To poll forks and get current number of active
261connections use asynchronous `server.getConnections` instead.
262
263### server.getConnections(callback)
264
265Asynchronously get the number of concurrent connections on the server. Works
266when sockets were sent to forks.
267
268Callback should take two arguments `err` and `count`.
269
270`net.Server` is an [EventEmitter][] with the following events:
271
272### Event: 'listening'
273
274Emitted when the server has been bound after calling `server.listen`.
275
276### Event: 'connection'
277
278* {Socket object} The connection object
279
280Emitted when a new connection is made. `socket` is an instance of
281`net.Socket`.
282
283### Event: 'close'
284
285Emitted when the server closes. Note that if connections exist, this
286event is not emitted until all connections are ended.
287
288### Event: 'error'
289
290* {Error Object}
291
292Emitted when an error occurs.  The `'close'` event will be called directly
293following this event.  See example in discussion of `server.listen`.
294
295## Class: net.Socket
296
297This object is an abstraction of a TCP or local socket.  `net.Socket`
298instances implement a duplex Stream interface.  They can be created by the
299user and used as a client (with `connect()`) or they can be created by Node
300and passed to the user through the `'connection'` event of a server.
301
302### new net.Socket([options])
303
304Construct a new socket object.
305
306`options` is an object with the following defaults:
307
308    { fd: null
309      allowHalfOpen: false,
310      readable: false,
311      writable: false
312    }
313
314`fd` allows you to specify the existing file descriptor of socket.
315Set `readable` and/or `writable` to `true` to allow reads and/or writes on this
316socket (NOTE: Works only when `fd` is passed).
317About `allowHalfOpen`, refer to `createServer()` and `'end'` event.
318
319### socket.connect(port, [host], [connectListener])
320### socket.connect(path, [connectListener])
321
322Opens the connection for a given socket. If `port` and `host` are given,
323then the socket will be opened as a TCP socket, if `host` is omitted,
324`localhost` will be assumed. If a `path` is given, the socket will be
325opened as a unix socket to that path.
326
327Normally this method is not needed, as `net.createConnection` opens the
328socket. Use this only if you are implementing a custom Socket.
329
330This function is asynchronous. When the ['connect'][] event is emitted the
331socket is established. If there is a problem connecting, the `'connect'` event
332will not be emitted, the `'error'` event will be emitted with the exception.
333
334The `connectListener` parameter will be added as an listener for the
335['connect'][] event.
336
337
338### socket.bufferSize
339
340`net.Socket` has the property that `socket.write()` always works. This is to
341help users get up and running quickly. The computer cannot always keep up
342with the amount of data that is written to a socket - the network connection
343simply might be too slow. Node will internally queue up the data written to a
344socket and send it out over the wire when it is possible. (Internally it is
345polling on the socket's file descriptor for being writable).
346
347The consequence of this internal buffering is that memory may grow. This
348property shows the number of characters currently buffered to be written.
349(Number of characters is approximately equal to the number of bytes to be
350written, but the buffer may contain strings, and the strings are lazily
351encoded, so the exact number of bytes is not known.)
352
353Users who experience large or growing `bufferSize` should attempt to
354"throttle" the data flows in their program with `pause()` and `resume()`.
355
356
357### socket.setEncoding([encoding])
358
359Set the encoding for the socket as a Readable Stream. See
360[stream.setEncoding()][] for more information.
361
362### socket.write(data, [encoding], [callback])
363
364Sends data on the socket. The second parameter specifies the encoding in the
365case of a string--it defaults to UTF8 encoding.
366
367Returns `true` if the entire data was flushed successfully to the kernel
368buffer. Returns `false` if all or part of the data was queued in user memory.
369`'drain'` will be emitted when the buffer is again free.
370
371The optional `callback` parameter will be executed when the data is finally
372written out - this may not be immediately.
373
374### socket.end([data], [encoding])
375
376Half-closes the socket. i.e., it sends a FIN packet. It is possible the
377server will still send some data.
378
379If `data` is specified, it is equivalent to calling
380`socket.write(data, encoding)` followed by `socket.end()`.
381
382### socket.destroy()
383
384Ensures that no more I/O activity happens on this socket. Only necessary in
385case of errors (parse error or so).
386
387### socket.pause()
388
389Pauses the reading of data. That is, `'data'` events will not be emitted.
390Useful to throttle back an upload.
391
392### socket.resume()
393
394Resumes reading after a call to `pause()`.
395
396### socket.setTimeout(timeout, [callback])
397
398Sets the socket to timeout after `timeout` milliseconds of inactivity on
399the socket. By default `net.Socket` do not have a timeout.
400
401When an idle timeout is triggered the socket will receive a `'timeout'`
402event but the connection will not be severed. The user must manually `end()`
403or `destroy()` the socket.
404
405If `timeout` is 0, then the existing idle timeout is disabled.
406
407The optional `callback` parameter will be added as a one time listener for the
408`'timeout'` event.
409
410### socket.setNoDelay([noDelay])
411
412Disables the Nagle algorithm. By default TCP connections use the Nagle
413algorithm, they buffer data before sending it off. Setting `true` for
414`noDelay` will immediately fire off data each time `socket.write()` is called.
415`noDelay` defaults to `true`.
416
417### socket.setKeepAlive([enable], [initialDelay])
418
419Enable/disable keep-alive functionality, and optionally set the initial
420delay before the first keepalive probe is sent on an idle socket.
421`enable` defaults to `false`.
422
423Set `initialDelay` (in milliseconds) to set the delay between the last
424data packet received and the first keepalive probe. Setting 0 for
425initialDelay will leave the value unchanged from the default
426(or previous) setting. Defaults to `0`.
427
428### socket.address()
429
430Returns the bound address, the address family name and port of the
431socket as reported by the operating system. Returns an object with
432three properties, e.g.
433`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`
434
435### socket.unref()
436
437Calling `unref` on a socket will allow the program to exit if this is the only
438active socket in the event system. If the socket is already `unref`d calling
439`unref` again will have no effect.
440
441### socket.ref()
442
443Opposite of `unref`, calling `ref` on a previously `unref`d socket will *not*
444let the program exit if it's the only socket left (the default behavior). If
445the socket is `ref`d calling `ref` again will have no effect.
446
447### socket.remoteAddress
448
449The string representation of the remote IP address. For example,
450`'74.125.127.100'` or `'2001:4860:a005::68'`.
451
452### socket.remotePort
453
454The numeric representation of the remote port. For example,
455`80` or `21`.
456
457### socket.localAddress
458
459The string representation of the local IP address the remote client is
460connecting on. For example, if you are listening on `'0.0.0.0'` and the
461client connects on `'192.168.1.1'`, the value would be `'192.168.1.1'`.
462
463### socket.localPort
464
465The numeric representation of the local port. For example,
466`80` or `21`.
467
468### socket.bytesRead
469
470The amount of received bytes.
471
472### socket.bytesWritten
473
474The amount of bytes sent.
475
476
477`net.Socket` instances are [EventEmitter][] with the following events:
478
479### Event: 'lookup'
480
481Emitted after resolving the hostname but before connecting.
482Not applicable to UNIX sockets.
483
484* `err` {Error | Null} The error object.  See [dns.lookup()][].
485* `address` {String} The IP address.
486* `family` {String | Null} The address type.  See [dns.lookup()][].
487
488### Event: 'connect'
489
490Emitted when a socket connection is successfully established.
491See `connect()`.
492
493### Event: 'data'
494
495* {Buffer object}
496
497Emitted when data is received.  The argument `data` will be a `Buffer` or
498`String`.  Encoding of data is set by `socket.setEncoding()`.
499(See the [Readable Stream][] section for more information.)
500
501Note that the __data will be lost__ if there is no listener when a `Socket`
502emits a `'data'` event.
503
504### Event: 'end'
505
506Emitted when the other end of the socket sends a FIN packet.
507
508By default (`allowHalfOpen == false`) the socket will destroy its file
509descriptor  once it has written out its pending write queue.  However, by
510setting `allowHalfOpen == true` the socket will not automatically `end()`
511its side allowing the user to write arbitrary amounts of data, with the
512caveat that the user is required to `end()` their side now.
513
514
515### Event: 'timeout'
516
517Emitted if the socket times out from inactivity. This is only to notify that
518the socket has been idle. The user must manually close the connection.
519
520See also: `socket.setTimeout()`
521
522
523### Event: 'drain'
524
525Emitted when the write buffer becomes empty. Can be used to throttle uploads.
526
527See also: the return values of `socket.write()`
528
529### Event: 'error'
530
531* {Error object}
532
533Emitted when an error occurs.  The `'close'` event will be called directly
534following this event.
535
536### Event: 'close'
537
538* `had_error` {Boolean} true if the socket had a transmission error
539
540Emitted once the socket is fully closed. The argument `had_error` is a boolean
541which says if the socket was closed due to a transmission error.
542
543## net.isIP(input)
544
545Tests if input is an IP address. Returns 0 for invalid strings,
546returns 4 for IP version 4 addresses, and returns 6 for IP version 6 addresses.
547
548
549## net.isIPv4(input)
550
551Returns true if input is a version 4 IP address, otherwise returns false.
552
553
554## net.isIPv6(input)
555
556Returns true if input is a version 6 IP address, otherwise returns false.
557
558['connect']: #net_event_connect
559['connection']: #net_event_connection
560['end']: #net_event_end
561[EventEmitter]: events.html#events_class_events_eventemitter
562['listening']: #net_event_listening
563[server.getConnections()]: #net_server_getconnections_callback
564[Readable Stream]: stream.html#stream_readable_stream
565[stream.setEncoding()]: stream.html#stream_stream_setencoding_encoding