nodejs实现UDP组播示例
2019-11-01 本文已影响0人
mapoor
众所周知,UDP数据传输方式有 单播,组播,广播。
其中单播模式是最常用,这里就不再啰嗦了,网上随便都能搜到。
下面的示例主要实现简单的UDP组播方式。可以正常收发UDP数据。
Server端代码
const dgram = require('dgram');
const server = dgram.createSocket('udp4');
// const local_ip = "192.168.0.xx";
const multicast_ip = "225.0.0.100"; // 这里必须是一个组播地址(D类IP地址)
server.on('close', ()=>{
console.log('close socket');
});
server.on('listening', ()=>{
console.log('listening...');
server.setBroadcast(true);
server.setMulticastTTL(128);
server.addMembership(multicast_ip);
setInterval(()=>{
send_msg();
}, 2000);
});
server.on('message', (msg, rinfo)=>{
console.log(`receive client message from ${rinfo.address}: ${rinfo.port}: ${msg}`);
});
server.bind(); // 随机绑定本机一个端口
function send_msg(){
console.log('send msg');
server.send('hi, im server...', '8062', multicast_ip);
}
Client端代码:
const dgram = require('dgram');
var client = dgram.createSocket('udp4');
// const local_ip = '192.168.0.xx';
const multicast_ip = "225.0.0.100"; // 这里必须是一个组播地址(D类IP地址)
client.on('close', ()=>{
console.log('client closed');
});
client.on('error', (err) =>{
console.log('client error' + err);
});
client.on('listening', ()=>{
console.log('client listening...');
client.setBroadcast(true);
client.setMulticastTTL(128);
client.addMembership(multicast_ip);
});
client.on('message', (msg, rinfo) => {
console.log(`receive server message from ${rinfo.address}: ${rinfo.port}: ${msg}`);
});
client.bind('8062'); // 监听组播数据的端口