PageRenderTime 46ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/doc/api/dgram.markdown

https://gitlab.com/GeekSir/node
Markdown | 312 lines | 217 code | 95 blank | 0 comment | 0 complexity | 4e067c0cfbe10d8b71177def646cd701 MD5 | raw file
Possible License(s): 0BSD, Apache-2.0, MPL-2.0-no-copyleft-exception, JSON, WTFPL, CC-BY-SA-3.0, Unlicense, ISC, BSD-3-Clause, MIT, AGPL-3.0
  1. # UDP / Datagram Sockets
  2. Stability: 3 - Stable
  3. <!-- name=dgram -->
  4. Datagram sockets are available through `require('dgram')`.
  5. Important note: the behavior of `dgram.Socket#bind()` has changed in v0.10
  6. and is always asynchronous now. If you have code that looks like this:
  7. var s = dgram.createSocket('udp4');
  8. s.bind(1234);
  9. s.addMembership('224.0.0.114');
  10. You have to change it to this:
  11. var s = dgram.createSocket('udp4');
  12. s.bind(1234, function() {
  13. s.addMembership('224.0.0.114');
  14. });
  15. ## dgram.createSocket(type[, callback])
  16. * `type` String. Either 'udp4' or 'udp6'
  17. * `callback` Function. Attached as a listener to `message` events.
  18. Optional
  19. * Returns: Socket object
  20. Creates a datagram Socket of the specified types. Valid types are `udp4`
  21. and `udp6`.
  22. Takes an optional callback which is added as a listener for `message` events.
  23. Call `socket.bind()` if you want to receive datagrams. `socket.bind()` will
  24. bind to the "all interfaces" address on a random port (it does the right thing
  25. for both `udp4` and `udp6` sockets). You can then retrieve the address and port
  26. with `socket.address().address` and `socket.address().port`.
  27. ## dgram.createSocket(options[, callback])
  28. * `options` Object
  29. * `callback` Function. Attached as a listener to `message` events.
  30. * Returns: Socket object
  31. The `options` object should contain a `type` field of either `udp4` or `udp6`
  32. and an optional boolean `reuseAddr` field.
  33. When `reuseAddr` is true `socket.bind()` will reuse the address, even if
  34. another process has already bound a socket on it. `reuseAddr` defaults to
  35. `false`.
  36. Takes an optional callback which is added as a listener for `message` events.
  37. Call `socket.bind()` if you want to receive datagrams. `socket.bind()` will
  38. bind to the "all interfaces" address on a random port (it does the right thing
  39. for both `udp4` and `udp6` sockets). You can then retrieve the address and port
  40. with `socket.address().address` and `socket.address().port`.
  41. ## Class: dgram.Socket
  42. The dgram Socket class encapsulates the datagram functionality. It
  43. should be created via `dgram.createSocket(...)`
  44. ### Event: 'message'
  45. * `msg` Buffer object. The message
  46. * `rinfo` Object. Remote address information
  47. Emitted when a new datagram is available on a socket. `msg` is a `Buffer` and
  48. `rinfo` is an object with the sender's address information:
  49. socket.on('message', function(msg, rinfo) {
  50. console.log('Received %d bytes from %s:%d\n',
  51. msg.length, rinfo.address, rinfo.port);
  52. });
  53. ### Event: 'listening'
  54. Emitted when a socket starts listening for datagrams. This happens as soon as UDP sockets
  55. are created.
  56. ### Event: 'close'
  57. Emitted when a socket is closed with `close()`. No new `message` events will be emitted
  58. on this socket.
  59. ### Event: 'error'
  60. * `exception` Error object
  61. Emitted when an error occurs.
  62. ### socket.send(buf, offset, length, port, address[, callback])
  63. * `buf` Buffer object or string. Message to be sent
  64. * `offset` Integer. Offset in the buffer where the message starts.
  65. * `length` Integer. Number of bytes in the message.
  66. * `port` Integer. Destination port.
  67. * `address` String. Destination hostname or IP address.
  68. * `callback` Function. Called when the message has been sent. Optional.
  69. For UDP sockets, the destination port and address must be specified. A string
  70. may be supplied for the `address` parameter, and it will be resolved with DNS.
  71. If the address is omitted or is an empty string, `'0.0.0.0'` or `'::0'` is used
  72. instead. Depending on the network configuration, those defaults may or may not
  73. work; it's best to be explicit about the destination address.
  74. If the socket has not been previously bound with a call to `bind`, it gets
  75. assigned a random port number and is bound to the "all interfaces" address
  76. (`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.)
  77. An optional callback may be specified to detect DNS errors or for determining
  78. when it's safe to reuse the `buf` object. Note that DNS lookups delay the time
  79. to send for at least one tick. The only way to know for sure that the datagram
  80. has been sent is by using a callback.
  81. With consideration for multi-byte characters, `offset` and `length` will
  82. be calculated with respect to
  83. [byte length](buffer.html#buffer_class_method_buffer_bytelength_string_encoding)
  84. and not the character position.
  85. Example of sending a UDP packet to a random port on `localhost`;
  86. var dgram = require('dgram');
  87. var message = new Buffer("Some bytes");
  88. var client = dgram.createSocket("udp4");
  89. client.send(message, 0, message.length, 41234, "localhost", function(err) {
  90. client.close();
  91. });
  92. **A Note about UDP datagram size**
  93. The maximum size of an `IPv4/v6` datagram depends on the `MTU` (_Maximum Transmission Unit_)
  94. and on the `Payload Length` field size.
  95. - The `Payload Length` field is `16 bits` wide, which means that a normal payload
  96. cannot be larger than 64K octets including internet header and data
  97. (65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header);
  98. this is generally true for loopback interfaces, but such long datagrams
  99. are impractical for most hosts and networks.
  100. - The `MTU` is the largest size a given link layer technology can support for datagrams.
  101. For any link, `IPv4` mandates a minimum `MTU` of `68` octets, while the recommended `MTU`
  102. for IPv4 is `576` (typically recommended as the `MTU` for dial-up type applications),
  103. whether they arrive whole or in fragments.
  104. For `IPv6`, the minimum `MTU` is `1280` octets, however, the mandatory minimum
  105. fragment reassembly buffer size is `1500` octets.
  106. The value of `68` octets is very small, since most current link layer technologies have
  107. a minimum `MTU` of `1500` (like Ethernet).
  108. Note that it's impossible to know in advance the MTU of each link through which
  109. a packet might travel, and that generally sending a datagram greater than
  110. the (receiver) `MTU` won't work (the packet gets silently dropped, without
  111. informing the source that the data did not reach its intended recipient).
  112. ### socket.bind(port[, address][, callback])
  113. * `port` Integer
  114. * `address` String, Optional
  115. * `callback` Function with no parameters, Optional. Callback when
  116. binding is done.
  117. For UDP sockets, listen for datagrams on a named `port` and optional
  118. `address`. If `address` is not specified, the OS will try to listen on
  119. all addresses. After binding is done, a "listening" event is emitted
  120. and the `callback`(if specified) is called. Specifying both a
  121. "listening" event listener and `callback` is not harmful but not very
  122. useful.
  123. A bound datagram socket keeps the node process running to receive
  124. datagrams.
  125. If binding fails, an "error" event is generated. In rare case (e.g.
  126. binding a closed socket), an `Error` may be thrown by this method.
  127. Example of a UDP server listening on port 41234:
  128. var dgram = require("dgram");
  129. var server = dgram.createSocket("udp4");
  130. server.on("error", function (err) {
  131. console.log("server error:\n" + err.stack);
  132. server.close();
  133. });
  134. server.on("message", function (msg, rinfo) {
  135. console.log("server got: " + msg + " from " +
  136. rinfo.address + ":" + rinfo.port);
  137. });
  138. server.on("listening", function () {
  139. var address = server.address();
  140. console.log("server listening " +
  141. address.address + ":" + address.port);
  142. });
  143. server.bind(41234);
  144. // server listening 0.0.0.0:41234
  145. ### socket.bind(options[, callback])
  146. * `options` {Object} - Required. Supports the following properties:
  147. * `port` {Number} - Required.
  148. * `address` {String} - Optional.
  149. * `exclusive` {Boolean} - Optional.
  150. * `callback` {Function} - Optional.
  151. The `port` and `address` properties of `options`, as well as the optional
  152. callback function, behave as they do on a call to
  153. [socket.bind(port, \[address\], \[callback\])
  154. ](#dgram_socket_bind_port_address_callback).
  155. If `exclusive` is `false` (default), then cluster workers will use the same
  156. underlying handle, allowing connection handling duties to be shared. When
  157. `exclusive` is `true`, the handle is not shared, and attempted port sharing
  158. results in an error. An example which listens on an exclusive port is
  159. shown below.
  160. socket.bind({
  161. address: 'localhost',
  162. port: 8000,
  163. exclusive: true
  164. });
  165. ### socket.close()
  166. Close the underlying socket and stop listening for data on it.
  167. ### socket.address()
  168. Returns an object containing the address information for a socket. For UDP sockets,
  169. this object will contain `address` , `family` and `port`.
  170. ### socket.setBroadcast(flag)
  171. * `flag` Boolean
  172. Sets or clears the `SO_BROADCAST` socket option. When this option is set, UDP packets
  173. may be sent to a local interface's broadcast address.
  174. ### socket.setTTL(ttl)
  175. * `ttl` Integer
  176. Sets the `IP_TTL` socket option. TTL stands for "Time to Live," but in this context it
  177. specifies the number of IP hops that a packet is allowed to go through. Each router or
  178. gateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a
  179. router, it will not be forwarded. Changing TTL values is typically done for network
  180. probes or when multicasting.
  181. The argument to `setTTL()` is a number of hops between 1 and 255. The default on most
  182. systems is 64.
  183. ### socket.setMulticastTTL(ttl)
  184. * `ttl` Integer
  185. Sets the `IP_MULTICAST_TTL` socket option. TTL stands for "Time to Live," but in this
  186. context it specifies the number of IP hops that a packet is allowed to go through,
  187. specifically for multicast traffic. Each router or gateway that forwards a packet
  188. decrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.
  189. The argument to `setMulticastTTL()` is a number of hops between 0 and 255. The default on most
  190. systems is 1.
  191. ### socket.setMulticastLoopback(flag)
  192. * `flag` Boolean
  193. Sets or clears the `IP_MULTICAST_LOOP` socket option. When this option is set, multicast
  194. packets will also be received on the local interface.
  195. ### socket.addMembership(multicastAddress[, multicastInterface])
  196. * `multicastAddress` String
  197. * `multicastInterface` String, Optional
  198. Tells the kernel to join a multicast group with `IP_ADD_MEMBERSHIP` socket option.
  199. If `multicastInterface` is not specified, the OS will try to add membership to all valid
  200. interfaces.
  201. ### socket.dropMembership(multicastAddress[, multicastInterface])
  202. * `multicastAddress` String
  203. * `multicastInterface` String, Optional
  204. Opposite of `addMembership` - tells the kernel to leave a multicast group with
  205. `IP_DROP_MEMBERSHIP` socket option. This is automatically called by the kernel
  206. when the socket is closed or process terminates, so most apps will never need to call
  207. this.
  208. If `multicastInterface` is not specified, the OS will try to drop membership to all valid
  209. interfaces.
  210. ### socket.unref()
  211. Calling `unref` on a socket will allow the program to exit if this is the only
  212. active socket in the event system. If the socket is already `unref`d calling
  213. `unref` again will have no effect.
  214. ### socket.ref()
  215. Opposite of `unref`, calling `ref` on a previously `unref`d socket will *not*
  216. let the program exit if it's the only socket left (the default behavior). If
  217. the socket is `ref`d calling `ref` again will have no effect.