const dgram = require('dgram'); const client = dgram.createSocket('udp4'); client.on('close',()=>{ console.log('socket已关闭'); }); client.on('error',(err)=>{ console.log(err); }); client.on('listening',()=>{ console.log('socket正在监听中...'); }); client.on('message',(msg,rinfo)=>{ console.log(`receive message from ${rinfo.address}:${rinfo.port}:${msg}`); }); client.bind(8061,'1.1.1.69');
3、UDP组播实现
组播地址是实现UDP组播的关键,因此了解组播地址是重点。什么是组播地址?IANA将D类地址(224.0.0.0-239.255.255.255)分配给IP组播,用来标识一个IP组播组,由IGMP(组管理协议)协议维护组成员关系,其中:
224.0.0.0~224.0.0.255为永久组地址,地址224.0.0.0保留不做分配,其它地址供路由协议使用;
224.0.1.0~224.0.1.255是公用组播地址,可以用于Internet;
224.0.2.0~238.255.255.255为用户可用的组播地址(临时组地址),全网范围内有效;
239.0.0.0~239.255.255.255为本地管理组播地址,仅在特定的本地范围内有效。
向组播地址发送数据报,只有该组成员才会接收此数据报。
dgram模块的addMembership()方法将socket加入组播组中,dropMembership()方法退出组播组。下面以组播地址224.100.100.100来实现UDP组播,如下所示:
服务端:
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.setMulticastTTL(128); setInterval(()=>{ sendMsg(); },1500); }); server.on('message',(msg,rinfo)=>{ console.log(`receive message from ${rinfo.address}:${rinfo.port}`); }); function sendMsg(){ server.send('大家好啊,我是服务端.',8061,multicastAddr); } server.bind('8060','1.1.1.69');
客户端:
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 message from ${rinfo.address}:${rinfo.port}:${msg}`); }); client.bind(8061,'1.1.1.69');