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