UDP多广播节点 [英] UDP multi broadcast nodejs

查看:217
本文介绍了UDP多广播节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个基于UDP多播的聊天程序,这个想法是本地网络上的任何人都可以弹出并开始输入和发送消息。

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)

这会将消息回显给运行代码的人,但我也同时在同一台机器OS X上的linux VM上运行它,但是没有看到消息传递完毕。

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.

我不确定这是否意味着

1)我的代码是不正确

1) My code is incorrect

2)虚拟机与其主机具有相同的网络?

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

3)代码正确但我的家庭路由器阻塞多个广播包?

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

推荐答案

啊,我发现这个重复使用端口地址的巧妙技巧。

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

通过本地网络与非VM Ubuntu进行OS X通信。

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

这篇关于UDP多广播节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆