本机IP地址是10.8.93.80,
具体信息如上图所示
根据计算得知我的广播地址应该是10.8.93.255,不是10.8.93.254哦。
其它内容就直接上代码
server.js
const dgram = require('dgram'); const server = dgram.createSocket('udp4'); const multicastAddr = '224.100.100.100'; server.on('close', () => { console.log('socket已关闭'); }); server.on('error', (err) => { console.log(err); }); server.on('listening', () => { console.log('socket正在监听中...'); server.addMembership(multicastAddr); // 不写也行 server.setBroadcast(true); server.setMulticastTTL(128); setInterval(() => { sendMsg(); }, 1500); }); server.on('message', (msg, rinfo) => { console.log(`receive client message from ${rinfo.address}:${rinfo.port}`); }); function sendMsg() { console.log('sending'); server.send('大家好啊,我是服务端广播消息', 8061, '10.8.93.255'); server.send('大家好啊,我是服务端组播消息', 8061, multicastAddr); } server.bind('8060'); // 此处填写IP后无法组播
client.js
const dgram = require('dgram'); const client = dgram.createSocket('udp4'); const multicastAddr = '224.100.100.100'; client.on('close', () => { console.log('socket已关闭'); }); client.on('error', (err) => { console.log(err); }); client.on('listening', () => { console.log('socket正在监听中...'); client.addMembership(multicastAddr); }); client.on('message', (msg, rinfo) => { console.log(`receive server message from ${rinfo.address}:${rinfo.port}:${msg}`); }); client.bind(8061); // 此处必须绑定自己的局域网IP或者不填,填localhost是不行的
代码中我的服务器是绑定的8060端口,向广播地址的8061端口发送广播,故意改成不一样的是为了本机的客户端也能够接收试试,不然不就端口占用了。