UDP multi broadcast nodejs

2019-05-18 19:44发布

I'm trying to create a UDP multi broadcast based chat program, the idea being that anyone on the local network can just pop on and start typing and sending messages.

I figure that every client needs two sockets, one to send messages and one to receive messages.

At its simplest, this is what I have now:

"using strict";

const multicast_addr = "224.1.1.1",
      bin_addr = "0.0.0.0",
      port = 6811;

var udp = require("dgram");

var listener = udp.createSocket("udp4"),
    sender = udp.createSocket("udp4");

listener.bind(port, multicast_addr, function(){
    listener.addMembership(multicast_addr);
    listener.setBroadcast(true);
});

listener.on("message", function (b, other) {
    console.log(b.toString().trim());
});

process.stdin.on("data", function (data){
    sender.send(data, 0, data.length, port, multicast_addr);
});

(Never mind the echo, that's application logic that will be built on top)

This will echo the message back to the person running the code, but I also ran this at the same time on a linux VM on the same machine, OS X, but didn't see the messages being passed at all.

I'm not sure if that means that

1) My code is incorrect

2) VMs have the same networking as their host machine?

3) Code is correct but my home router is blocking multi broadcast packets?

1条回答
Emotional °昔
2楼-- · 2019-05-18 20:08

Ah, I found this neat trick of reusing ports for addresses.

"using strict";

const multicast_addr = "224.1.1.1",
      bin_addr = "0.0.0.0",
      port = 6811;

var udp = require("dgram");

var listener = udp.createSocket({type:"udp4", reuseAddr:true}),
    sender = udp.createSocket({type:"udp4", reuseAddr:true});

listener.bind(port, multicast_addr, function(){
    listener.addMembership(multicast_addr);
    listener.setBroadcast(true);
});

listener.on("message", function (b, other) {
    console.log(b.toString().trim());
});

process.stdin.on("data", function (data){
    sender.send(data, 0, data.length, port, multicast_addr);
});

Worked for having OS X talk to Non-VM Ubuntu over local network.

查看更多
登录 后发表回答