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

时间:2013-07-02 09:21:48

标签: node.js socket.io

我创建了一个nodejs服务器,它使用socket.io与web客户端建立通信,服务器正在向特定客户端发送套接字,问题是如果我有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接收数据

1 个答案:

答案 0 :(得分:2)

您应该将server.on('sendingData', function(data){...});放在socket.on('connection', function (client){...});之外。这是因为sendingData事件是针对http服务器而不是针对socket.io服务器的。

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

相关问题