Node.js v8.7.0 文档


dgram (数据报)#

查看英文版 / 查看英文md文件 / 编辑中文md文件

稳定性: 2 - 稳定的

dgram模块提供了 UDP 数据包 socket 的实现。

const dgram = require('dgram');
const server = dgram.createSocket('udp4');

server.on('error', (err) => {
  console.log(`服务器异常:\n${err.stack}`);
  server.close();
});

server.on('message', (msg, rinfo) => {
  console.log(`服务器收到:${msg} 来自 ${rinfo.address}:${rinfo.port}`);
});

server.on('listening', () => {
  const address = server.address();
  console.log(`服务器监听 ${address.address}:${address.port}`);
});

server.bind(41234);
// 服务器监听 0.0.0.0:41234

dgram.Socket 类#

查看英文版 / 查看英文md文件 / 编辑中文md文件

dgram.Socket对象是一个封装了数据包函数功能的EventEmitter

dgram.Socket实例是由dgram.createSocket()创建的。创建dgram.Socket实例不需要使用new关键字。

'close' 事件#

查看英文版 / 查看英文md文件 / 编辑中文md文件

'close'事件将在使用close()关闭一个 socket 之后触发。该事件一旦触发,这个 socket 上将不会触发新的'message'事件。

'error' 事件#

查看英文版 / 查看英文md文件 / 编辑中文md文件

当有任何错误发生时,'error'事件将被触发。事件发生时,回掉函数仅会接收到一个 Error 参数。

'listening' 事件#

查看英文版 / 查看英文md文件 / 编辑中文md文件

当一个 socket 开始监听数据包信息时,'listening'事件将被触发。该事件会在创建 UDP socket 之后被立即触发。

'message' 事件#

查看英文版 / 查看英文md文件 / 编辑中文md文件

当有新的数据包被 socket 接收时,'message'事件会被触发。msgrinfo会作为参数传递到该事件的处理函数中。

socket.addMembership(multicastAddress[, multicastInterface])#

查看英文版 / 查看英文md文件 / 编辑中文md文件

通知内核将multicastAddressmulticastInterface提供的多路传送集合通过IP_ADD_MEMBERSHIP这个 socket 选项结合起来。若multicastInterface参数未指定,操作系统将会选择一个接口并向其添加成员。要为所有可用的接口添加成员,可以在每个接口上调用一次addMembership方法。

socket.address()#

查看英文版 / 查看英文md文件 / 编辑中文md文件

返回一个包含 socket 地址信息的对象。对于 UDP socket,该对象将包含addressfamilyport属性。

socket.bind([port][, address][, callback])#

查看英文版 / 查看英文md文件 / 编辑中文md文件

对于 UDP socket,该方法会令dgram.Socket在指定的port和可选的address上监听数据包信息。若port未指定或为 0,操作系统会尝试绑定一个随机的端口。若address未指定,操作系统会尝试在所有地址上监听。绑定完成时会触发一个'listening'事件,并会调用callback方法。

注意,同时监听'listening'事件和在socket.bind()方法中传入callback参数并不会带来坏处,但也不是很有用。

一个被绑定的数据包 socket 会令 Node.js 进程保持运行以接收数据包信息。

若绑定失败,一个'error'事件会被触发。在极少数的情况下(例如尝试绑定一个已关闭的 socket),一个 Error 会被抛出。

一个监听 41234 端口的 UDP 服务器的例子:

const dgram = require('dgram');
const server = dgram.createSocket('udp4');

server.on('error', (err) => {
  console.log(`服务器异常:\n${err.stack}`);
  server.close();
});

server.on('message', (msg, rinfo) => {
  console.log(`服务器收到:${msg} 来自 ${rinfo.address}:${rinfo.port}`);
});

server.on('listening', () => {
  const address = server.address();
  console.log(`服务器监听 ${address.address}:${address.port}`);
});

server.bind(41234);
// 服务器监听 0.0.0.0:41234

socket.bind(options[, callback])#

查看英文版 / 查看英文md文件 / 编辑中文md文件

对于 UDP socket,该方法会令dgram.Socket在指定的port和可选的address上监听数据包信息。若port未指定或为 0,操作系统会尝试绑定一个随机的端口。若address未指定,操作系统会尝试在所有地址上监听。绑定完成时会触发一个'listening'事件,并会调用callback方法。

Note that specifying both a 'listening' event listener and passing a callback to the socket.bind() method is not harmful but not very useful.

在配合cluster模块使用dgram.Socket对象时,options对象可能包含一个附加的exclusive属性。当exclusive被设为false(默认值)时,集群工作单元会使用相同的 socket 句柄来共享连接处理作业。当exclusive被设为true时,该句柄将不会被共享,而尝试共享端口则会造成错误。

一个绑定的数据报 socket 会使 Node.js 进程持续运行以接受数据报消息。

如果绑定失败,一个 'error' 事件会产生。在极少数情况下(例如尝试绑定一个已经关闭的 socket), 一个 Error 可能抛出。

一个不共享端口的 socket 的例子如下文所示。

socket.bind({
  address: 'localhost',
  port: 8000,
  exclusive: true
});

socket.close([callback])#

查看英文版 / 查看英文md文件 / 编辑中文md文件

关闭该 socket 并停止监听其上的数据。如果提供了一个回调函数,它就相当于为'close'事件添加了一个监听器。

socket.dropMembership(multicastAddress[, multicastInterface])#

查看英文版 / 查看英文md文件 / 编辑中文md文件

引导内核通过IP_DROP_MEMBERSHIP这个 socket 选项删除multicastAddress指定的多路传送集合。当 socket 被关闭或进程被终止时,该方法会被内核自动调用,所以大多数的应用都不用自行调用该方法。

multicastInterface未指定,操作系统会尝试删除所有可用接口上的成员。

socket.getRecvBufferSize(size)#

查看英文版 / 查看英文md文件 / 编辑中文md文件

  • Returns <number> the SO_RCVBUF socket receive buffer size in bytes.

socket.getSendBufferSize(size)#

查看英文版 / 查看英文md文件 / 编辑中文md文件

  • Returns <number> the SO_SNDBUF socket send buffer size in bytes.

socket.ref()#

查看英文版 / 查看英文md文件 / 编辑中文md文件

By default, binding a socket will cause it to block the Node.js process from exiting as long as the socket is open. The socket.unref() method can be used to exclude the socket from the reference counting that keeps the Node.js process active. The socket.ref() method adds the socket back to the reference counting and restores the default behavior.

Calling socket.ref() multiples times will have no additional effect.

The socket.ref() method returns a reference to the socket so calls can be chained.

socket.send(msg, [offset, length,] port [, address] [, callback])#

查看英文版 / 查看英文md文件 / 编辑中文md文件

在 socket 上发送一个数据包。目标portaddress须被指定。

msg参数包含了要发送的消息。根据消息的类型可以有不同的做法。如果msg是一个BufferUint8Array,则offsetlength指定了消息在Buffer中对应的偏移量和字节数。如果msg是一个String,那么它会被自动地按照utf8编码转换为Buffer。对于包含了多字节字符的消息,offsetlength会根据对应的byte length进行计算,而不是根据字符的位置。如果msg是一个数组,那么offsetlength必须都不能被指定。

address参数是一个字符串。若address的值是一个主机名,则 DNS 会被用来解析主机的地址。若address未提供或是非真值,则'127.0.0.1'(用于 udp4 socket)或'::1'(用于 udp6 socket)会被使用。

若在之前 socket 未通过调用bind方法进行绑定,socket 将会被一个随机的端口号赋值并绑定到“所有接口”的地址上(对于udp4 socket 是'0.0.0.0',对于udp6 socket 是'::0')。

可以指定一个可选的callback方法来汇报 DNS 错误或判断可以安全地重用buf对象的时机。注意,在 Node.js 事件循环中,DNS 查询会对发送造成至少 1 tick 的延迟。

确定数据包被发送的唯一方式就是指定callback。若在callback被指定的情况下有错误发生,该错误会作为callback的第一个参数。若callback未被指定,该错误会以'error'事件的方式投射到socket对象上。

偏移量和长度是可选的,但如其中一个被指定则另一个也必须被指定。另外,他们只在第一个参数是BufferUint8Array 的情况下才能被使用。

一个发送 UDP 包到localhost上的某个随机端口的例子:

const dgram = require('dgram');
const message = Buffer.from('Some bytes');
const client = dgram.createSocket('udp4');
client.send(message, 41234, 'localhost', (err) => {
  client.close();
});

一个发送包含多个 buffer 的 UDP 包到 127.0.0.1 上的某个随机端口的例子:

const dgram = require('dgram');
const buf1 = Buffer.from('Some ');
const buf2 = Buffer.from('bytes');
const client = dgram.createSocket('udp4');
client.send([buf1, buf2], 41234, (err) => {
  client.close();
});

发送多个 buffer 的速度取决于应用和操作系统。 It is important to run benchmarks to determine the optimal strategy on a case-by-case basis. Generally speaking, however, sending multiple buffers is faster.

关于 UDP 包大小的注意事项

IPv4/v6数据包的最大尺寸取决于MTU(Maximum Transmission Unit, 最大传输单元)与Payload Length字段大小。

  • Payload Length字段有16 位宽,指一个超过 64K 的包含 IP 头部和数据的负载 (65,507 字节 = 65,535 − 8 字节 UDP 头 − 20 字节 IP 头部);通常对于环回地址来说是这样,但这个长度的数据包对于大多数的主机和网络来说不切实际。

  • MTU指的是数据链路层为数据包提供的最大大小。对于任意链路,IPv4所托管的MTU最小为68个字节,推荐为576(典型地,作为拨号上网应用的推荐值),无论它们是完整地还是分块地抵达。

    对于IPv6MTU的最小值是1280个字节,然而,受托管的最小的碎片重组缓冲大小为1500个字节。现今大多数的数据链路层技术(如以太网),都有1500MTU最小值,因而68个字节显得非常小。

要提前知道数据包可能经过的每个链路的 MTU 是不可能的。发送大于接受者MTU大小的数据包将不会起作用,因为数据包会被静默地丢失,而不会通知发送者该包未抵达目的地。

socket.setBroadcast(flag)#

查看英文版 / 查看英文md文件 / 编辑中文md文件

设置或清除 SO_BROADCAST socket 选项。当设置为 true, UDP包可能会被发送到一个本地接口的广播地址

socket.setMulticastInterface(multicastInterface)#

查看英文版 / 查看英文md文件 / 编辑中文md文件

Note: All references to scope in this section are refering to IPv6 Zone Indices, which are defined by RFC 4007. In string form, an IP with a scope index is written as 'IP%scope' where scope is an interface name or interface number.

Sets the default outgoing multicast interface of the socket to a chosen interface or back to system interface selection. The multicastInterface must be a valid string representation of an IP from the socket's family.

For IPv4 sockets, this should be the IP configured for the desired physical interface. All packets sent to multicast on the socket will be sent on the interface determined by the most recent successful use of this call.

For IPv6 sockets, multicastInterface should include a scope to indicate the interface as in the examples that follow. In IPv6, individual send calls can also use explicit scope in addresses, so only packets sent to a multicast address without specifying an explicit scope are affected by the most recent successful use of this call.

Examples: IPv6 Outgoing Multicast Interface#

查看英文版 / 查看英文md文件 / 编辑中文md文件

On most systems, where scope format uses the interface name:

const socket = dgram.createSocket('udp6');

socket.bind(1234, () => {
  socket.setMulticastInterface('::%eth1');
});

On Windows, where scope format uses an interface number:

const socket = dgram.createSocket('udp6');

socket.bind(1234, () => {
  socket.setMulticastInterface('::%2');
});

Example: IPv4 Outgoing Multicast Interface#

查看英文版 / 查看英文md文件 / 编辑中文md文件

All systems use an IP of the host on the desired physical interface:

const socket = dgram.createSocket('udp4');

socket.bind(1234, () => {
  socket.setMulticastInterface('10.0.0.2');
});

Call Results#

查看英文版 / 查看英文md文件 / 编辑中文md文件

A call on a socket that is not ready to send or no longer open may throw a Not running Error.

If multicastInterface can not be parsed into an IP then an EINVAL System Error is thrown.

On IPv4, if multicastInterface is a valid address but does not match any interface, or if the address does not match the family then a System Error such as EADDRNOTAVAIL or EPROTONOSUP is thrown.

On IPv6, most errors with specifying or omiting scope will result in the socket continuing to use (or returning to) the system's default interface selection.

A socket's address family's ANY address (IPv4 '0.0.0.0' or IPv6 '::') can be used to return control of the sockets default outgoing interface to the system for future multicast packets.

socket.setMulticastLoopback(flag)#

查看英文版 / 查看英文md文件 / 编辑中文md文件

设置或清除 IP_MULTICAST_LOOP socket 选项。当设置为 true, 多播数据包也将在本地接口接收。

socket.setMulticastTTL(ttl)#

查看英文版 / 查看英文md文件 / 编辑中文md文件

Sets the IP_MULTICAST_TTL socket option. While TTL generally stands for "Time to Live", in this context it specifies the number of IP hops that a packet is allowed to travel through, specifically for multicast traffic. Each router or gateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.

The argument passed to to socket.setMulticastTTL() is a number of hops between 0 and 255. The default on most systems is 1 but can vary.

socket.setRecvBufferSize(size)#

查看英文版 / 查看英文md文件 / 编辑中文md文件

Sets the SO_RCVBUF socket option. Sets the maximum socket receive buffer in bytes.

socket.setSendBufferSize(size)#

查看英文版 / 查看英文md文件 / 编辑中文md文件

Sets the SO_SNDBUF socket option. Sets the maximum socket send buffer in bytes.

socket.setTTL(ttl)#

查看英文版 / 查看英文md文件 / 编辑中文md文件

Sets the IP_TTL socket option. While TTL generally stands for "Time to Live", in this context it specifies the number of IP hops that a packet is allowed to travel through. Each router or gateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. Changing TTL values is typically done for network probes or when multicasting.

The argument to socket.setTTL() is a number of hops between 1 and 255. The default on most systems is 64 but can vary.

socket.unref()#

查看英文版 / 查看英文md文件 / 编辑中文md文件

By default, binding a socket will cause it to block the Node.js process from exiting as long as the socket is open. The socket.unref() method can be used to exclude the socket from the reference counting that keeps the Node.js process active, allowing the process to exit even if the socket is still listening.

Calling socket.unref() multiple times will have no addition effect.

The socket.unref() method returns a reference to the socket so calls can be chained.

Change to asynchronous socket.bind() behavior#

查看英文版 / 查看英文md文件 / 编辑中文md文件

As of Node.js v0.10, dgram.Socket#bind() changed to an asynchronous execution model. Legacy code that assumes synchronous behavior, as in the following example:

const s = dgram.createSocket('udp4');
s.bind(1234);
s.addMembership('224.0.0.114');

Must be changed to pass a callback function to the dgram.Socket#bind() function:

const s = dgram.createSocket('udp4');
s.bind(1234, () => {
  s.addMembership('224.0.0.114');
});

dgram module functions#

dgram.createSocket(options[, callback])#

查看英文版 / 查看英文md文件 / 编辑中文md文件

  • options <Object> Available options are:
    • type <string> The family of socket. Must be either 'udp4' or 'udp6'. Required.
    • reuseAddr <boolean> When true socket.bind() will reuse the address, even if another process has already bound a socket on it. Defaults to false.
    • recvBufferSize <number> - Sets the SO_RCVBUF socket value.
    • sendBufferSize <number> - Sets the SO_SNDBUF socket value.
    • lookup <Function> Custom lookup function. Defaults to dns.lookup().
  • callback <Function> Attached as a listener for 'message' events. Optional.
  • Returns: <dgram.Socket>

Creates a dgram.Socket object. Once the socket is created, calling socket.bind() will instruct the socket to begin listening for datagram messages. When address and port are not passed to socket.bind() the method will bind the socket to the "all interfaces" address on a random port (it does the right thing for both udp4 and udp6 sockets). The bound address and port can be retrieved using socket.address().address and socket.address().port.

dgram.createSocket(type[, callback])#

查看英文版 / 查看英文md文件 / 编辑中文md文件

Creates a dgram.Socket object of the specified type. The type argument can be either udp4 or udp6. An optional callback function can be passed which is added as a listener for 'message' events.

Once the socket is created, calling socket.bind() will instruct the socket to begin listening for datagram messages. When address and port are not passed to socket.bind() the method will bind the socket to the "all interfaces" address on a random port (it does the right thing for both udp4 and udp6 sockets). The bound address and port can be retrieved using socket.address().address and socket.address().port.