【问题标题】:Nodejs socket.io is emitting message to client as number of clients connectedNodejs socket.io 正在向客户端发送消息作为连接的客户端数量
【发布时间】:2013-06-29 14:24:49
【问题描述】:

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

【问题讨论】:

  • 正在复制哪条消息。
  • 这个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); });
  • 您正在尝试使用像 socket.io 这样的 http 服务器。您为每个 POST 请求执行server.emit('sendingData', body);。并且您按照每个连接用户的时间处理它,每次发送数据接收到服务器。尝试将server.on('sendingData', function(data) 移出socket.on('connection', function (client)

标签: node.js socket.io


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2019-08-04
    • 1970-01-01
    • 1970-01-01
    • 2014-08-17
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-24
    • 2015-08-06
    相关资源
    最近更新 更多