Nodejs socket.io以连接的客户端数量向客户端发送消息

我做了一个使用socket.io的nodejs服务器与web客户端build立通信,服务器正在向特定的客户端发送套接字,问题是如果我有5个客户端连接到服务器,客户端将收到5次发送的消息!

这里是我的代码:

var fs = require('fs'), http = require('http'), io = require('socket.io'), qs = require('querystring'); sys = require ('util'), url = require('url'); var message, AndroidID; //Traitement Serveur nodejs var server = http.createServer(function(req, res) { if(req.method=='POST') { var body = ''; req.on('data', function (data) { body += data; }); req.on('end',function(){ server.emit('sendingData', body); console.log("Body : " + body); }); res.write("success"); res.end(); } else { res.writeHead(200, { 'Content-type': 'text/html'}); res.end(fs.readFileSync(__dirname + '/index.html')); } }).listen(8080, function() { console.log('Listening at: http://localhost:8080'); }); var socket = io.listen(server); var clients = {}; var compteur = 0; // Traitement socket.io socket.on('connection', function (client) { clients[compteur] = client; client.emit('firstConnection', client.id, compteur); console.log('clients : ', clients); compteur += 1; client.on('message', function (msg) { console.log('Message Received: ', msg); client.broadcast.emit('message', msg); }); server.on('sendingData', function(data){ message = data.substring(8, data.lastIndexOf('&')); androidID = data.substr(-1); console.log('[+] Sending Data : ', message ,' TO : ', parseInt(androidID)); clients[parseInt(androidID)].emit('androidmsg', message); }); }); 

nodejs服务器正在接收来自php HTTPClient的数据

你应该把server.on('sendingData', function(data){...}); socket.on('connection', function (client){...}); 。 这是因为sendingData事件是为http服务器而不是socket.io服务器。

将它放在socket.io连接处理程序中,可以使每个连接的客户端重复执行到socket.io服务器