socket.addMembership(multicastAddress[, multicastInterface])


告诉内核使用 IP_ADD_MEMBERSHIP 套接字选项在给定的 multicastAddressmulticastInterface 加入多播组。如果未指定 multicastInterface 参数,操作系统将选择一个接口并加入该接口的组。要在每个可用接口上加入组,请多次调用 addMembership,每个接口调用一次。

【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.】

当在多个 cluster 工作进程之间共享 UDP 套接字时,必须只调用一次 socket.addMembership() 函数,否则会发生 EADDRINUSE 错误:

【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');
  });
}