Skip to content

Commit 7e985d8

Browse files
committedJan 4, 2016
doc: improvements to dgram.markdown copy
General improvements to dgram.markdown copy PR-URL: #4437 Reviewed-By: Minwoo Jung <[email protected]> Reviewed-By: Stephan Belanger <[email protected]>
1 parent bbb4a2a commit 7e985d8

File tree

1 file changed

+196
-129
lines changed

1 file changed

+196
-129
lines changed
 

‎doc/api/dgram.markdown

+196-129
Original file line numberDiff line numberDiff line change
@@ -4,50 +4,62 @@
44

55
<!-- name=dgram -->
66

7-
Datagram sockets are available through `require('dgram')`.
7+
The `dgram` module provides an implementation of UDP Datagram sockets.
88

9-
Important note: the behavior of [`dgram.Socket#bind()`][] has changed in v0.10
10-
and is always asynchronous now. If you have code that looks like this:
9+
const dgram = require('dgram');
10+
const server = dgram.createSocket('udp4');
1111

12-
const s = dgram.createSocket('udp4');
13-
s.bind(1234);
14-
s.addMembership('224.0.0.114');
12+
server.on('error', (err) => {
13+
console.log(`server error:\n${err.stack}`);
14+
server.close();
15+
});
1516

16-
You have to change it to this:
17+
server.on('message', (msg, rinfo) => {
18+
console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
19+
});
1720

18-
const s = dgram.createSocket('udp4');
19-
s.bind(1234, () => {
20-
s.addMembership('224.0.0.114');
21+
server.on('listening', () => {
22+
var address = server.address();
23+
console.log(`server listening ${address.address}:${address.port}`);
2124
});
2225

26+
server.bind(41234);
27+
// server listening 0.0.0.0:41234
28+
2329
## Class: dgram.Socket
2430

25-
The dgram Socket class encapsulates the datagram functionality. It
26-
should be created via [`dgram.createSocket(...)`][]
31+
The `dgram.Socket` object is an [`EventEmitter`][] that encapsulates the
32+
datagram functionality.
33+
34+
New instances of `dgram.Socket` are created using [`dgram.createSocket()`][].
35+
The `new` keyword is not to be used to create `dgram.Socket` instances.
2736

2837
### Event: 'close'
2938

30-
Emitted after a socket is closed with [`close()`][]. No new `'message'` events will be emitted
31-
on this socket.
39+
The `'close'` event is emitted after a socket is closed with [`close()`][].
40+
Once triggered, no new `'message'` events will be emitted on this socket.
3241

3342
### Event: 'error'
3443

3544
* `exception` Error object
3645

37-
Emitted when an error occurs.
46+
The `'error'` event is emitted whenever any error occurs. The event handler
47+
function is passed a single Error object.
3848

3949
### Event: 'listening'
4050

41-
Emitted when a socket starts listening for datagrams. This happens as soon as UDP sockets
42-
are created.
51+
The `'listening'` event is emitted whenever a socket begins listening for
52+
datagram messages. This occurs as soon as UDP sockets are created.
4353

4454
### Event: 'message'
4555

4656
* `msg` Buffer object. The message
4757
* `rinfo` Object. Remote address information
4858

49-
Emitted when a new datagram is available on a socket. `msg` is a `Buffer` and
50-
`rinfo` is an object with the sender's address information:
59+
The `'message'` event is emitted when a new datagram is available on a socket.
60+
The event handler function is passed two arguments: `msg` and `rinfo`. The
61+
`msg` argument is a [`Buffer`][] and `rinfo` is an object with the sender's
62+
address information provided by the `address`, `family` and `port` properties:
5163

5264
socket.on('message', (msg, rinfo) => {
5365
console.log('Received %d bytes from %s:%d\n',
@@ -59,41 +71,44 @@ Emitted when a new datagram is available on a socket. `msg` is a `Buffer` and
5971
* `multicastAddress` String
6072
* `multicastInterface` String, Optional
6173

62-
Tells the kernel to join a multicast group with `IP_ADD_MEMBERSHIP` socket option.
63-
64-
If `multicastInterface` is not specified, the OS will try to add membership to all valid
65-
interfaces.
74+
Tells the kernel to join a multicast group at the given `multicastAddress`
75+
using the `IP_ADD_MEMBERSHIP` socket option. If the `multicastInterface`
76+
argument is not specified, the operating system will try to add membership to
77+
all valid networking interfaces.
6678

6779
### socket.address()
6880

69-
Returns an object containing the address information for a socket. For UDP sockets,
70-
this object will contain `address` , `family` and `port`.
81+
Returns an object containing the address information for a socket.
82+
For UDP sockets, this object will contain `address`, `family` and `port`
83+
properties.
7184

72-
### socket.bind([port][, address][, callback])
85+
### [socket.bind([port][, address][, callback])]
7386

7487
* `port` Integer, Optional
7588
* `address` String, Optional
76-
* `callback` Function with no parameters, Optional. Callback when
77-
binding is done.
78-
79-
For UDP sockets, listen for datagrams on a named `port` and optional
80-
`address`. If `port` is not specified, the OS will try to bind to a random
81-
port. If `address` is not specified, the OS will try to listen on
82-
all addresses. After binding is done, a `'listening'` event is emitted
83-
and the `callback`(if specified) is called. Specifying both a
84-
`'listening'` event listener and `callback` is not harmful but not very
89+
* `callback` Function with no parameters, Optional. Called when
90+
binding is complete.
91+
92+
For UDP sockets, causes the `dgram.Socket` to listen for datagram messages on a
93+
named `port` and optional `address`. If `port` is not specified, the operating
94+
system will attempt to bind to a random port. If `address` is not specified,
95+
the operating system will attempt to listen on all addresses. Once binding is
96+
complete, a `'listening'` event is emitted and the optional `callback` function
97+
is called.
98+
99+
Note that specifying both a `'listening'` event listener and passing a
100+
`callback` to the `socket.bind()` method is not harmful but not very
85101
useful.
86102

87103
A bound datagram socket keeps the Node.js process running to receive
88-
datagrams.
104+
datagram messages.
89105

90106
If binding fails, an `'error'` event is generated. In rare case (e.g.
91-
binding a closed socket), an [`Error`][] may be thrown by this method.
107+
attempting to bind with a closed socket), an [`Error`][] may be thrown.
92108

93109
Example of a UDP server listening on port 41234:
94110

95111
const dgram = require('dgram');
96-
97112
const server = dgram.createSocket('udp4');
98113

99114
server.on('error', (err) => {
@@ -121,15 +136,22 @@ Example of a UDP server listening on port 41234:
121136
* `exclusive` {Boolean} - Optional.
122137
* `callback` {Function} - Optional.
123138

124-
The `port` and `address` properties of `options`, as well as the optional
125-
callback function, behave as they do on a call to
126-
[`socket.bind(port, \[address\], \[callback\])`][].
139+
For UDP sockets, causes the `dgram.Socket` to listen for datagram messages on a
140+
named `port` and optional `address` that are passed as properties of an
141+
`options` object passed as the first argument. If `port` is not specified, the
142+
operating system will attempt to bind to a random port. If `address` is not
143+
specified, the operating system will attempt to listen on all addresses. Once
144+
binding is complete, a `'listening'` event is emitted and the optional
145+
`callback` function is called.
146+
147+
The `options` object may contain an additional `exclusive` property that is
148+
use when using `dgram.Socket` objects with the [`cluster`] module. When
149+
`exclusive` is set to `false` (the default), cluster workers will use the same
150+
underlying socket handle allowing connection handling duties to be shared.
151+
When `exclusive` is `true`, however, the handle is not shared and attempted
152+
port sharing results in an error.
127153

128-
If `exclusive` is `false` (default), then cluster workers will use the same
129-
underlying handle, allowing connection handling duties to be shared. When
130-
`exclusive` is `true`, the handle is not shared, and attempted port sharing
131-
results in an error. An example which listens on an exclusive port is
132-
shown below.
154+
An example socket listening on an exclusive port is shown below.
133155

134156
socket.bind({
135157
address: 'localhost',
@@ -147,13 +169,13 @@ provided, it is added as a listener for the [`'close'`][] event.
147169
* `multicastAddress` String
148170
* `multicastInterface` String, Optional
149171

150-
Opposite of [`addMembership()`][] - tells the kernel to leave a multicast group with
151-
`IP_DROP_MEMBERSHIP` socket option. This is automatically called by the kernel
152-
when the socket is closed or process terminates, so most apps will never need to call
153-
this.
172+
Instructs the kernel to leave a multicast group at `multicastAddress` using the
173+
`IP_DROP_MEMBERSHIP` socket option. This method is automatically called by the
174+
kernel when the socket is closed or the process terminates, so most apps will
175+
never have reason to call this.
154176

155-
If `multicastInterface` is not specified, the OS will try to drop membership to all valid
156-
interfaces.
177+
If `multicastInterface` is not specified, the operating system will attempt to
178+
drop membership on all valid interfaces.
157179

158180
### socket.send(buf, offset, length, port, address[, callback])
159181

@@ -164,26 +186,35 @@ interfaces.
164186
* `address` String. Destination hostname or IP address.
165187
* `callback` Function. Called when the message has been sent. Optional.
166188

167-
For UDP sockets, the destination port and address must be specified. A string
168-
may be supplied for the `address` parameter, and it will be resolved with DNS.
189+
Broadcasts a datagram on the socket. The destination `port` and `address` must
190+
be specified.
169191

170-
If the address is omitted or is an empty string, `'0.0.0.0'` or `'::0'` is used
171-
instead. Depending on the network configuration, those defaults may or may not
172-
work; it's best to be explicit about the destination address.
192+
The `buf` argument is a [`Buffer`] object containing the message. The `offset`
193+
and `length` specify the offset within the `Buffer` where the message begins
194+
and the number of bytes in the message, respectively. With messages that
195+
contain multi-byte characters, `offset` and `length` will be calculated with
196+
respect to [byte length][] and not the character position.
173197

174-
If the socket has not been previously bound with a call to `bind`, it gets
175-
assigned a random port number and is bound to the "all interfaces" address
198+
The `address` argument is a string. If the value of `address` is a host name,
199+
DNS will be used to resolve the address of the host. If the `address` is not
200+
specified or is an empty string, `'0.0.0.0'` or `'::0'` will be used instead.
201+
It is possible, depending on the network configuration, that these defaults
202+
may not work; accordingly, it is best to be explicit about the destination
203+
address.
204+
205+
If the socket has not been previously bound with a call to `bind`, the socket
206+
is assigned a random port number and is bound to the "all interfaces" address
176207
(`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.)
177208

178-
An optional callback may be specified to detect DNS errors or for determining
179-
when it's safe to reuse the `buf` object. Note that DNS lookups delay the time
180-
to send for at least one tick. The only way to know for sure that the datagram
181-
has been sent is by using a callback. If an error occurs and a callback is
182-
given, the error will be the first argument to the callback. If a callback is
183-
not given, the error is emitted as an `'error'` event on the `socket` object.
209+
An optional `callback` function may be specified to as a way of reporting
210+
DNS errors or for determining when it is safe to reuse the `buf` object.
211+
Note that DNS lookups delay the time to send for at least one tick of the
212+
Node.js event loop.
184213

185-
With consideration for multi-byte characters, `offset` and `length` will
186-
be calculated with respect to [byte length][] and not the character position.
214+
The only way to know for sure that the datagram has been sent is by using a
215+
`callback`. If an error occurs and a `callback` is given, the error will be
216+
passed as the first argument to the `callback`. If a `callback` is not given,
217+
the error is emitted as an `'error'` event on the `socket` object.
187218

188219
Example of sending a UDP packet to a random port on `localhost`;
189220

@@ -196,103 +227,137 @@ Example of sending a UDP packet to a random port on `localhost`;
196227

197228
**A Note about UDP datagram size**
198229

199-
The maximum size of an `IPv4/v6` datagram depends on the `MTU` (_Maximum Transmission Unit_)
200-
and on the `Payload Length` field size.
230+
The maximum size of an `IPv4/v6` datagram depends on the `MTU`
231+
(_Maximum Transmission Unit_) and on the `Payload Length` field size.
201232

202-
- The `Payload Length` field is `16 bits` wide, which means that a normal payload
203-
cannot be larger than 64K octets including internet header and data
233+
- The `Payload Length` field is `16 bits` wide, which means that a normal
234+
payload exceed 64K octets _including_ the internet header and data
204235
(65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header);
205-
this is generally true for loopback interfaces, but such long datagrams
206-
are impractical for most hosts and networks.
236+
this is generally true for loopback interfaces, but such long datagram
237+
messages are impractical for most hosts and networks.
207238

208-
- The `MTU` is the largest size a given link layer technology can support for datagrams.
209-
For any link, `IPv4` mandates a minimum `MTU` of `68` octets, while the recommended `MTU`
210-
for IPv4 is `576` (typically recommended as the `MTU` for dial-up type applications),
211-
whether they arrive whole or in fragments.
239+
- The `MTU` is the largest size a given link layer technology can support for
240+
datagram messages. For any link, `IPv4` mandates a minimum `MTU` of `68`
241+
octets, while the recommended `MTU` for IPv4 is `576` (typically recommended
242+
as the `MTU` for dial-up type applications), whether they arrive whole or in
243+
fragments.
212244

213245
For `IPv6`, the minimum `MTU` is `1280` octets, however, the mandatory minimum
214-
fragment reassembly buffer size is `1500` octets.
215-
The value of `68` octets is very small, since most current link layer technologies have
216-
a minimum `MTU` of `1500` (like Ethernet).
246+
fragment reassembly buffer size is `1500` octets. The value of `68` octets is
247+
very small, since most current link layer technologies, like Ethernet, have a
248+
minimum `MTU` of `1500`.
217249

218-
Note that it's impossible to know in advance the MTU of each link through which
219-
a packet might travel, and that generally sending a datagram greater than
220-
the (receiver) `MTU` won't work (the packet gets silently dropped, without
221-
informing the source that the data did not reach its intended recipient).
250+
It is impossible to know in advance the MTU of each link through which
251+
a packet might travel. Sending a datagram greater than the receiver `MTU` will
252+
not work because the packet will get silently dropped without informing the
253+
source that the data did not reach its intended recipient.
222254

223255
### socket.setBroadcast(flag)
224256

225257
* `flag` Boolean
226258

227-
Sets or clears the `SO_BROADCAST` socket option. When this option is set, UDP packets
228-
may be sent to a local interface's broadcast address.
259+
Sets or clears the `SO_BROADCAST` socket option. When set to `true`, UDP
260+
packets may be sent to a local interface's broadcast address.
229261

230262
### socket.setMulticastLoopback(flag)
231263

232264
* `flag` Boolean
233265

234-
Sets or clears the `IP_MULTICAST_LOOP` socket option. When this option is set, multicast
235-
packets will also be received on the local interface.
266+
Sets or clears the `IP_MULTICAST_LOOP` socket option. When set to `true`,
267+
multicast packets will also be received on the local interface.
236268

237269
### socket.setMulticastTTL(ttl)
238270

239271
* `ttl` Integer
240272

241-
Sets the `IP_MULTICAST_TTL` socket option. TTL stands for "Time to Live", but in this
242-
context it specifies the number of IP hops that a packet is allowed to go through,
243-
specifically for multicast traffic. Each router or gateway that forwards a packet
244-
decrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.
273+
Sets the `IP_MULTICAST_TTL` socket option. While TTL generally stands for
274+
"Time to Live", in this context it specifies the number of IP hops that a
275+
packet is allowed to travel through, specifically for multicast traffic. Each
276+
router or gateway that forwards a packet decrements the TTL. If the TTL is
277+
decremented to 0 by a router, it will not be forwarded.
245278

246-
The argument to `setMulticastTTL()` is a number of hops between 0 and 255. The default on most
247-
systems is 1.
279+
The argument passed to to `socket.setMulticastTTL()` is a number of hops
280+
between 0 and 255. The default on most systems is `1` but can vary.
248281

249282
### socket.setTTL(ttl)
250283

251284
* `ttl` Integer
252285

253-
Sets the `IP_TTL` socket option. TTL stands for "Time to Live", but in this context it
254-
specifies the number of IP hops that a packet is allowed to go through. Each router or
255-
gateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a
256-
router, it will not be forwarded. Changing TTL values is typically done for network
257-
probes or when multicasting.
286+
Sets the `IP_TTL` socket option. While TTL generally stands for "Time to Live",
287+
in this context it specifies the number of IP hops that a packet is allowed to
288+
travel through. Each router or gateway that forwards a packet decrements the
289+
TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.
290+
Changing TTL values is typically done for network probes or when multicasting.
258291

259-
The argument to `setTTL()` is a number of hops between 1 and 255. The default
260-
on most systems is 64.
292+
The argument to `socket.setTTL()` is a number of hops between 1 and 255.
293+
The default on most systems is 64 but can vary.
261294

262295
### socket.ref()
263296

264-
Opposite of `unref`, calling `ref` on a previously `unref`d socket will *not*
265-
let the program exit if it's the only socket left (the default behavior). If
266-
the socket is `ref`d calling `ref` again will have no effect.
297+
By default, binding a socket will cause it to block the Node.js process from
298+
exiting as long as the socket is open. The `socket.unref()` method can be used
299+
to exclude the socket from the reference counting that keeps the Node.js
300+
process active. The `socket.ref()` method adds the socket back to the reference
301+
counting and restores the default behavior.
302+
303+
Calling `socket.ref()` multiples times will have no additional effect.
267304

268-
Returns `socket`.
305+
The `socket.ref()` method returns a reference to the socket so calls can be
306+
chained.
269307

270308
### socket.unref()
271309

272-
Calling `unref` on a socket will allow the program to exit if this is the only
273-
active socket in the event system. If the socket is already `unref`d calling
274-
`unref` again will have no effect.
310+
By default, binding a socket will cause it to block the Node.js process from
311+
exiting as long as the socket is open. The `socket.unref()` method can be used
312+
to exclude the socket from the reference counting that keeps the Node.js
313+
process active, allowing the process to exit even if the socket is still
314+
listening.
315+
316+
Calling `socket.unref()` multiple times will have no addition effect.
275317

276-
Returns `socket`.
318+
The `socket.unref()` method returns a reference to the socket so calls can be
319+
chained.
277320

278-
## dgram.createSocket(options[, callback])
321+
### Change to asynchronous `socket.bind()` behavior
322+
323+
As of Node.js v0.10, [`dgram.Socket#bind()`][] changed to an asynchronous
324+
execution model. Legacy code that assumes synchronous behavior, as in the
325+
following example:
326+
327+
const s = dgram.createSocket('udp4');
328+
s.bind(1234);
329+
s.addMembership('224.0.0.114');
330+
331+
Must be changed to pass a callback function to the [`dgram.Socket#bind()`][]
332+
function:
333+
334+
const s = dgram.createSocket('udp4');
335+
s.bind(1234, () => {
336+
s.addMembership('224.0.0.114');
337+
});
338+
339+
## `dgram` module functions
340+
341+
### dgram.createSocket(options[, callback])
279342
* `options` Object
280343
* `callback` Function. Attached as a listener to `'message'` events.
281344
* Returns: Socket object
282345

283-
The `options` object should contain a `type` field of either `udp4` or `udp6`
284-
and an optional boolean `reuseAddr` field.
346+
Creates a `dgram.Socket` object. The `options` argument is an object that
347+
should contain a `type` field of either `udp4` or `udp6` and an optional
348+
boolean `reuseAddr` field.
285349

286350
When `reuseAddr` is `true` [`socket.bind()`][] will reuse the address, even if
287351
another process has already bound a socket on it. `reuseAddr` defaults to
288-
`false`.
352+
`false`. An optional `callback` function can be passed specified which is added
353+
as a listener for `'message'` events.
289354

290-
Takes an optional callback which is added as a listener for `'message'` events.
291-
292-
Call [`socket.bind()`][] if you want to receive datagrams. [`socket.bind()`][] will
293-
bind to the "all interfaces" address on a random port (it does the right thing
294-
for both `udp4` and `udp6` sockets). You can then retrieve the address and port
295-
with [`socket.address().address`][] and [`socket.address().port`][].
355+
Once the socket is created, calling [`socket.bind()`][] will instruct the
356+
socket to begin listening for datagram messages. When `address` and `port` are
357+
not passed to [`socket.bind()`][] the method will bind the socket to the "all
358+
interfaces" address on a random port (it does the right thing for both `udp4`
359+
and `udp6` sockets). The bound address and port can be retrieved using
360+
[`socket.address().address`][] and [`socket.address().port`][].
296361

297362
## dgram.createSocket(type[, callback])
298363

@@ -301,24 +366,26 @@ with [`socket.address().address`][] and [`socket.address().port`][].
301366
Optional
302367
* Returns: Socket object
303368

304-
Creates a datagram Socket of the specified types. Valid types are `udp4`
305-
and `udp6`.
306-
307-
Takes an optional callback which is added as a listener for `'message'` events.
369+
Creates a `dgram.Socket` object of the specified `type`. The `type` argument
370+
can be either `udp4` or `udp6`. An optional `callback` function can be passed
371+
which is added as a listener for `'message'` events.
308372

309-
Call [`socket.bind()`][] if you want to receive datagrams. [`socket.bind()`][] will
310-
bind to the "all interfaces" address on a random port (it does the right thing
311-
for both `udp4` and `udp6` sockets). You can then retrieve the address and port
312-
with [`socket.address().address`][] and [`socket.address().port`][].
373+
Once the socket is created, calling [`socket.bind()`][] will instruct the
374+
socket to begin listening for datagram messages. When `address` and `port` are
375+
not passed to [`socket.bind()`][] the method will bind the socket to the "all
376+
interfaces" address on a random port (it does the right thing for both `udp4`
377+
and `udp6` sockets). The bound address and port can be retrieved using
378+
[`socket.address().address`][] and [`socket.address().port`][].
313379

380+
[`EventEmitter`]: events.html
381+
[`Buffer`]: buffer.html
314382
[`'close'`]: #dgram_event_close
315383
[`addMembership()`]: #dgram_socket_addmembership_multicastaddress_multicastinterface
316384
[`close()`]: #dgram_socket_close_callback
317-
[`dgram.createSocket(...)`]: #dgram_dgram_createsocket_options_callback
385+
[`dgram.createSocket()`]: #dgram_dgram_createsocket_options_callback
318386
[`dgram.Socket#bind()`]: #dgram_socket_bind_options_callback
319387
[`Error`]: errors.html#errors_class_error
320388
[`socket.address().address`]: #dgram_socket_address
321389
[`socket.address().port`]: #dgram_socket_address
322390
[`socket.bind()`]: #dgram_socket_bind_port_address_callback
323-
[`socket.bind(port, \[address\], \[callback\])`]: #dgram_socket_bind_port_address_callback
324391
[byte length]: buffer.html#buffer_class_method_buffer_bytelength_string_encoding

0 commit comments

Comments
 (0)
Please sign in to comment.