dgram.createSocket(options[, callback])
options<Object> 可用选项有:type<string> 套接字的类型。必须是'udp4'或'udp6'。必填。reuseAddr<boolean> 当设置为true时,即使另一个进程已经在该地址上绑定了套接字,socket.bind()也会重用该地址,但只有一个套接字可以接收数据。 默认值:false。reusePort<boolean> 当设置为true时,即使另一个进程已经绑定了该端口,socket.bind()仍将重用该端口。传入的数据报将被分配到监听的套接字上。该选项仅在某些平台上可用,例如 Linux 3.9+、DragonFlyBSD 3.6+、FreeBSD 12.0+、Solaris 11.4 和 AIX 7.2.5+。在不支持的平台上,当套接字绑定时,该选项会引发错误。 默认值:false。ipv6Only<boolean> 将ipv6Only设置为true将禁用双栈支持,即绑定到地址::不会导致0.0.0.0被绑定。默认值:false。recvBufferSize<number> 设置SO_RCVBUF套接字值。sendBufferSize<number> 设置SO_SNDBUF套接字值。lookup<Function> 自定义查找函数。默认值:dns.lookup()。signal<AbortSignal> 一个可用于关闭套接字的 AbortSignal。receiveBlockList<net.BlockList>receiveBlockList可用于丢弃发送到特定 IP 地址、IP 范围或 IP 子网的入站数据报。如果服务器位于反向代理、NAT 等后面,该功能将无法正常工作,因为与阻止列表进行比对的地址是代理的地址,或者是 NAT 指定的地址。sendBlockList<net.BlockList>sendBlockList可用于禁止对特定 IP 地址、IP 范围或 IP 子网的外发访问。
callback<Function> 作为'message'事件的监听器附加。可选。- 返回: <dgram.Socket>
创建一个 dgram.Socket 对象。一旦创建了套接字,调用 socket.bind() 将指示套接字开始监听数据报消息。当 address 和 port 没有传给 socket.bind() 时,该方法会将套接字绑定到“所有接口”地址的随机端口(对于 udp4 和 udp6 套接字都能正确处理)。绑定的地址和端口可以通过 socket.address().address 和 socket.address().port 获取。
【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.】
如果启用了 signal 选项,对相应的 AbortController 调用 .abort() 类似于对套接字调用 .close():
【If the signal option is enabled, calling .abort() on the corresponding
AbortController is similar to calling .close() on the socket:】
const controller = new AbortController();
const { signal } = controller;
const server = dgram.createSocket({ type: 'udp4', signal });
server.on('message', (msg, rinfo) => {
console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
});
// Later, when you want to close the server.
controller.abort();