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


在套接字上广播数据报。对于无连接套接字,必须指定目标 portaddress。另一方面,已连接的套接字将使用其关联的远程端点,因此 portaddress 参数不得设置。

【Broadcasts a datagram on the socket. For connectionless sockets, the destination port and address must be specified. Connected sockets, on the other hand, will use their associated remote endpoint, so the port and address arguments must not be set.】

msg 参数包含要发送的消息。
根据其类型,可能会有不同的行为。如果 msg 是一个 Buffer、任何 TypedArrayDataView,则 offsetlength 分别指定消息在 Buffer 中的起始偏移量以及消息的字节数。
如果 msg 是一个 String,则会自动转换为 'utf8' 编码的 Buffer。对于包含多字节字符的消息,offsetlength 将根据字节进行计算,而不是字符位置。
如果 msg 是一个数组,则不能指定 offsetlength

【The msg argument contains the message to be sent. Depending on its type, different behavior can apply. If msg is a Buffer, any TypedArray or a DataView, the offset and length specify the offset within the Buffer where the message begins and the number of bytes in the message, respectively. If msg is a String, then it is automatically converted to a Buffer with 'utf8' encoding. With messages that contain multi-byte characters, offset and length will be calculated with respect to byte length and not the character position. If msg is an array, offset and length must not be specified.】

address 参数是一个字符串。如果 address 的值是主机名,将使用 DNS 来解析主机的地址。如果未提供 address 或其值为 nullish,将默认使用 '127.0.0.1'(对于 udp4 套接字)或 '::1'(对于 udp6 套接字)。

【The address argument is a string. If the value of address is a host name, DNS will be used to resolve the address of the host. If address is not provided or otherwise nullish, '127.0.0.1' (for udp4 sockets) or '::1' (for udp6 sockets) will be used by default.】

如果套接字之前没有通过调用 bind 绑定,套接字将被分配一个随机端口号,并绑定到“所有接口”地址(udp4 套接字为 '0.0.0.0'udp6 套接字为 '::0')。

【If the socket has not been previously bound with a call to bind, the socket is assigned a random port number and is bound to the "all interfaces" address ('0.0.0.0' for udp4 sockets, '::0' for udp6 sockets.)】

可以指定一个可选的 callback 函数,用于报告 DNS 错误或确定何时可以安全地重用 buf 对象。DNS 查询会至少延迟一个 Node.js 事件循环的时间才发送。

【An optional callback function may be specified to as a way of reporting DNS errors or for determining when it is safe to reuse the buf object. DNS lookups delay the time to send for at least one tick of the Node.js event loop.】

确保数据报已发送的唯一方法是使用 callback。如果发生错误并且提供了 callback,错误将作为第一个参数传递给 callback。如果未提供 callback,则该错误将作为 'error' 事件在 socket 对象上触发。

【The only way to know for sure that the datagram has been sent is by using a callback. If an error occurs and a callback is given, the error will be passed as the first argument to the callback. If a callback is not given, the error is emitted as an 'error' event on the socket object.】

偏移量和长度是可选的,但如果使用其中任意一个,两个都必须设置。它们仅在第一个参数是 BufferTypedArrayDataView 时受支持。

【Offset and length are optional but both must be set if either are used. They are supported only when the first argument is a Buffer, a TypedArray, or a DataView.】

如果在未绑定的套接字上调用此方法,会抛出 ERR_SOCKET_BAD_PORT

【This method throws ERR_SOCKET_BAD_PORT if called on an unbound socket.】

localhost 上的端口发送 UDP 数据包的示例;

【Example of sending a UDP packet to a port on localhost;】

import dgram from 'node:dgram';
import { Buffer } from 'node:buffer';

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

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

将由多个缓冲区组成的 UDP 数据包发送到 127.0.0.1 上某个端口的示例;

【Example of sending a UDP packet composed of multiple buffers to a port on 127.0.0.1;】

import dgram from 'node:dgram';
import { Buffer } from 'node:buffer';

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

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

根据应用和操作系统的不同,发送多个缓冲区可能更快也可能更慢。请运行基准测试,以便在具体情况下确定最佳策略。然而,一般来说,发送多个缓冲区的速度更快。

【Sending multiple buffers might be faster or slower depending on the application and operating system. Run benchmarks to determine the optimal strategy on a case-by-case basis. Generally speaking, however, sending multiple buffers is faster.】

使用连接到 localhost 上端口的套接字发送 UDP 数据包的示例:

【Example of sending a UDP packet using a socket connected to a port on localhost:】

import dgram from 'node:dgram';
import { Buffer } from 'node:buffer';

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

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