I made a nodejs server wich uses socket.io to establish communication with web client, the server is sending sockets to specific client, the issue is if I have 5 clients connected to the server, the client will receive the sent message 5 times!
here is my code :
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);
});
});
The nodejs server is receiving data from a php HTTPClient
You should put server.on('sendingData', function(data){...}); outside socket.on('connection', function (client){...});. This is because the sendingData event is for http server and not socket.io server.
Putting it inside socket.io connection handler makes it repeatedly execute for each connected client to socket.io server