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


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

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

address 参数是字符串。 如果 address 的值是主机名,则会使用 DNS 解析主机地址。 如果未提供 address 或其他错误,则默认情况下将使用 '127.0.0.1'(用于 udp4 套接字)或 '::1'(用于 udp6 套接字)。

如果套接字之前没有绑定过对 bind 的调用,则该套接字会被分配随机端口号并绑定到“所有接口”地址('0.0.0.0' 用于 udp4 套接字,'::0' 用于 udp6 套接字。)

可以指定可选的 callback 函数作为报告 DNS 错误或确定何时可以安全地重用 buf 对象的一种方式。 DNS 查找延迟了 Node.js 事件循环的至少一滴答的发送时间。

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

偏移量和长度是可选的,但如果使用任何一个,则必须都设置。 仅当第一个参数是 BufferTypedArrayDataView 时才支持它们。

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

发送 UDP 包到 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 上的端口的示例;

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();
});

发送多个缓冲区可能更快或更慢,这取决于应用程序和操作系统。 运行基准测试以根据具体情况确定最佳策略。 但是,一般来说,发送多个缓冲区会更快。

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

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();
  });
});

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.

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.

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 falsy, '127.0.0.1' (for udp4 sockets) or '::1' (for udp6 sockets) will be used by default.

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.)

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.

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.

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.

This method throws ERR_SOCKET_BAD_PORT if called on an unbound socket.

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();
});

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.

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();
  });
});