Javascript 在NodeJ中使用UDP连接到同一服务器的多个客户端
是否可以将多个客户端连接到同一UDP服务器? 我想向所有连接的客户端广播相同的数据 这将是一个开始的样本,如果它有帮助的话Javascript 在NodeJ中使用UDP连接到同一服务器的多个客户端,javascript,node.js,udp,Javascript,Node.js,Udp,是否可以将多个客户端连接到同一UDP服务器? 我想向所有连接的客户端广播相同的数据 这将是一个开始的样本,如果它有帮助的话 // 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 = dg
// 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 ?
是的,这是可能的
我不会继续讲在UDP之前应该如何使用TCP,并且只在绝对必要时使用UDP
对于您的问题,事实是UDP没有任何“连接”。你接收消息,你发送消息,但没有“连接”
所以你应该做的是:
- 从传入客户端接收消息时,存储客户端使用的IP/端口
- 要向客户端发送消息时,请发送到存储的所有IP/端口组合
- 定期删除旧客户端(例如,在过去5分钟内未发送消息的客户端)
=true
,例如,您可以存储当前时间,然后定期删除旧客户端)
广播和多播可能与您想象的不同,例如,广播用于向本地网络上的每个人发送消息
// 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);