简体   繁体   English

使用NodeJS中的UDP将多个客户端连接到同一服务器

[英]Multiple Clients connected to the same Server using UDP in NodeJS

Is it possible to have multiple clients to the same UDP server ? 同一台UDP服务器上可以有多个客户端吗? I'd like to broadcast the same data to all connected clients. 我想向所有连接的客户端广播相同的数据。

Here would be a starting sample, if it helps somehow ... 如果可以帮助的话,这将是一个初始示例...

// Server
var news = [
  "Borussia Dortmund wins German championship",
  "Tornado warning for the Bay Area",
  "More rain for the weekend"
];

var dgram = require('dgram');
var server = dgram.createSocket("udp4");
server.bind(function() {
  server.setBroadcast(true)
  server.setMulticastTTL(128);
  setInterval(broadcastNew, 3000);
});

function broadcastNew() {
  var message = new Buffer(news[Math.floor(Math.random() * news.length)]);
  server.send(message, 0, message.length, 5007, "224.1.1.1");
  console.log("Sent " + message + " to the wire...");
}

// Client 1
var PORT = 5007;
var dgram = require('dgram');
var client = dgram.createSocket('udp4');

client.on('listening', function() {
  var address = client.address();
  console.log('UDP Client listening on ' + address.address + ":" + address.port);
  client.setBroadcast(true)
  client.setMulticastTTL(128);
  client.addMembership('224.1.1.1');
});

client.on('message', function(message, remote) {
  console.log('A: Epic Command Received. Preparing Relay.');
  console.log('B: From: ' + remote.address + ':' + remote.port + ' - ' + message);
});

client.bind(PORT);

// Client 2

// Here would go another client, it is possible ? 

Yes, it is possible. 对的,这是可能的。

I won't go on a speech about how you should use TCP before UDP and only use UDP when absolutely necessary. 我不会发表有关如何在UDP之前使用TCP的演讲,仅在绝对必要时才使用UDP。

For your problem, the fact is that UDP doesn't have any "connection". 对于您的问题,事实是UDP没有任何“连接”。 You receive messages, you send messages, but there is no "connection". 您收到消息,您发送消息,但是没有“连接”。

So what you should do is: 因此,您应该做的是:

  • When receiving a message from an incoming client, store the IP/Port used by the client 接收来自传入客户端的消息时,存储客户端使用的IP /端口
  • When wanting to send messages to clients, send to all the IP/Port combinations stored 想要向客户端发送消息时,发送到存储的所有IP /端口组合
  • Periodically remove old clients (for example who didn't send a message in the last 5 minutes) 定期删除旧客户端(例如,最近5分钟内未发送邮件的客户端)

You can detect when a message is received on a bound socket after the "message" event. 您可以检测“消息”事件之后何时在绑定套接字上接收到消息。 Your code would look something like that ( helped myself ): 您的代码看起来像这样( 对我自己有所帮助 ):

// Server
var news = [
  "Borussia Dortmund wins German championship",
  "Tornado warning for the Bay Area",
  "More rain for the weekend"
];

var clients = {};

const dgram = require('dgram');
const server = dgram.createSocket('udp4');

server.on('error', (err) => {
  console.log(`server error:\n${err.stack}`);
  server.close();
});

server.on('message', (msg, rinfo) => {
  console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);

  clients[JSON.stringify([rinfo.address, rinfo.port])] = true;
  //use delete clients[client] to remove from the list of clients
});

function broadCastNew() {
    var message = new Buffer(news[Math.floor(Math.random() * news.length)]);

    for (var client in clients) {
        client = JSON.parse(client);
        var port = client[1];
        var address = client[0];
        server.send(message, 0, message.length, port, address);
    }

    console.log("Sent " + message + " to the wire...");
}

server.on('listening', () => {
  var address = server.address();
  console.log(`server listening ${address.address}:${address.port}`);

  setInterval(broadcastNew, 3000);
});

server.bind(5007);

Now whenever your server gets an UDP message on port 5007, it will add the sender to the list of clients, and every 3 seconds it will send a message to all the clients stored. 现在,只要服务器在端口5007上收到UDP消息,它将发送方添加到客户端列表中,并且每3秒钟它将向所有存储的客户端发送一条消息。 How to make the sender receive that piece of news is another story, but you can use a tool such as WireShark to confirm yourself that it was correctly sent back. 如何使发件人接收该消息是另一回事,但是您可以使用WireShark之​​类的工具来确认自己已正确发送了该消息。

Here I didn't delete old clients but you probably should include a mechanism to store the last time they contacted you (instead of using = true you can for example store current time, then periodically remove old clients) 在这里,我没有删除旧客户端,但您可能应该包括一种存储上一次与您联系的时间的机制(例如,您可以存储当前时间,然后定期删除旧客户端,而不是使用= true

Broadcast and Multicast are probably different from what you imagine, broadcast is used for example to send a message to everyone on the local network. 广播和多播可能与您想象的不同,例如,广播用于向本地网络上的每个人发送消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用EventSourcing(NodeJS,MongoDB,JSON)跨多个偶尔连接的客户端同步数据 - Synchronize Data across multiple occasionally-connected-clients using EventSourcing (NodeJS, MongoDB, JSON) 将 Socket.io 与连接到同一服务器的多个客户端一起使用 - Using Socket.io with multiple clients connecting to same server 使用代理的NodeJS简单UDP客户端服务器应用程序 - NodeJS simple UDP client server application using broker WebRTC数据通道服务器向客户端进行UDP通信 - WebRTC Data Channel server to clients UDP communication PHP为所有连接的客户端提供相同的随机数 - PHP same random number for all the connected clients WebSockets的-的NodeJS。 是否可以向所有连接的客户端(从服务器)广播消息,而无需客户端首先发送客户端消息 - Websockets-NodeJS. Is it possible to broadcast a message to all connected clients(from the server) without having a client message the client first 如何从nodejs向所有连接的客户端发送变量? - How do I send a variable from nodejs to all the connected clients? 使用 node.js 监控连接的客户端 - monitor connected clients using node.js Node.js,客户端不总是接收服务器消息 - Nodejs, clients not always receiving server messages WebRTC数据通道服务器向客户端进行UDP通信。目前有可能吗? - WebRTC Data Channel server to clients UDP communication. Is it currently possible?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM