Node.js Websocket聊天应用程序:客户端接收重复消息

时间:2016-01-19 00:39:36

标签: javascript node.js websocket

我是Node.js的新手。我正在尝试使用Node.js,websocket实现聊天应用程序。我在服务器端使用的代码:

var config        = require('someconfigure'),
socketServer  = require('somewebsocketapi').server;


var clients = [ ];


socketServer( 'example', function ( connection, server ) {
var index;

  connection.on('open', function ( id ) {
index = clients.push(connection) - 1;
console.log('[open]');
  });



  connection.on('message', function ( msg ) {

    console.log(msg);
    var content = JSON.parse(msg.utf8Data);
    var author = content.action.data[0].author;
    var channel = content.action.data[0].channel;
    var text = content.action.data[0].text;
    var time = (new Date()).getTime();
    console.log(author+text+channel);

    // send messsage to all clients

    var obj = JSON.stringify(
        { 
            command:"messages",
            data: [
                {
                    timestamp: time,
                    text: text,
                    author: author,
                    channel: channel
                }
            ] 
        }
        );
    console.log("Number of clients "+clients.length);
    for (var i=0; i < clients.length; i++) {
        if(clients[i]!= connection)
            clients[i].send(obj);
        }
  });

  connection.on('error', function ( err ) {
console.log(err);
  });

  connection.on('close', function(){
   console.log((new Date()) + " Peer "
            + index + " disconnected.");
        // remove user from the list of connected clients
        clients.splice(index, 1);
  });


}).config( config );

我面临的问题是,客户正在获得重复的杂物。例如,如果连接了5个客户端,则所有客户端将获得相同的消息5次。

我知道我错过了什么,但我怎么能解决这个问题呢?提前感谢您的帮助。

0 个答案:

没有答案