2

我制作了一个 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 接收数据

4

1 回答 1

2

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

于 2013-07-02T17:49:26.857 回答