socket.addMembership(multicastAddress[, multicastInterface])
使用 IP_ADD_MEMBERSHIP
套接字选项告诉内核在给定的 multicastAddress
和 multicastInterface
上加入多播组。
如果未指定 multicastInterface
参数,则操作系统将选择一个接口并为其添加成员资格。
要为每个可用接口添加成员资格,则多次调用 addMembership
,每个接口一次。
当在未绑定的套接字上调用时,则此方法将隐式地绑定到随机端口,监听所有接口。
当在多个 cluster
工作进程共享 UDP 套接字时,则必须只调用一次 socket.addMembership()
函数,否则会发生 EADDRINUSE
错误:
import cluster from 'node:cluster';
import dgram from 'node:dgram';
if (cluster.isPrimary) {
cluster.fork(); // 工作正常。
cluster.fork(); // EADDRINUSE 失败。
} else {
const s = dgram.createSocket('udp4');
s.bind(1234, () => {
s.addMembership('224.0.0.114');
});
}
const cluster = require('node:cluster');
const dgram = require('node:dgram');
if (cluster.isPrimary) {
cluster.fork(); // 工作正常。
cluster.fork(); // EADDRINUSE 失败。
} else {
const s = dgram.createSocket('udp4');
s.bind(1234, () => {
s.addMembership('224.0.0.114');
});
}
Tells the kernel to join a multicast group at the given multicastAddress
and
multicastInterface
using the IP_ADD_MEMBERSHIP
socket option. If the
multicastInterface
argument is not specified, the operating system will choose
one interface and will add membership to it. To add membership to every
available interface, call addMembership
multiple times, once per interface.
When called on an unbound socket, this method will implicitly bind to a random port, listening on all interfaces.
When sharing a UDP socket across multiple cluster
workers, the
socket.addMembership()
function must be called only once or an
EADDRINUSE
error will occur:
import cluster from 'node:cluster';
import dgram from 'node:dgram';
if (cluster.isPrimary) {
cluster.fork(); // Works ok.
cluster.fork(); // Fails with EADDRINUSE.
} else {
const s = dgram.createSocket('udp4');
s.bind(1234, () => {
s.addMembership('224.0.0.114');
});
}
const cluster = require('node:cluster');
const dgram = require('node:dgram');
if (cluster.isPrimary) {
cluster.fork(); // Works ok.
cluster.fork(); // Fails with EADDRINUSE.
} else {
const s = dgram.createSocket('udp4');
s.bind(1234, () => {
s.addMembership('224.0.0.114');
});
}