2016-08-25 7 views
0

私はnode.jsで私の最初の措置をしています。私は基本を得るための簡単なチャットルームを実装しようとしていますが、各放送の後に2番目の(空の)メッセージが自動的に送信される理由を理解できません。この現象はほとんどの場合発生しますが、必ずしもそうではありません。私はWindowsでNetbeansを使用しています。クライアント接続をシミュレートするためにPuttyを使用しています。Node.jsブロードキャスト

コンソール出力:

Server running  
::1:60616 joined  
::1:60617 joined 
----------- 
Broadcasting: 
hello 
----------- 
Broadcasting: 


----------- 
Broadcasting: 
goodbye 
----------- 
Broadcasting: 


----------- 

クライアント1:

Hi ::1:60616! 
    hello 
goodbye 

クライアント2:

Hi ::1:60617! 
::1:60616 says hello::1:60616 says 
::1:60616 says goodbye::1:60616 says 

コード

var net = require('net'); 

var chatServer = net.createServer(); 
var clientList = []; 

console.log('Server running'); 

chatServer.on('connection', function (client) { 

    client.name = client.remoteAddress + ':' + client.remotePort; 
    client.write('Hi ' + client.name + '!\n'); 

    console.log(client.name + ' joined'); 

    clientList.push(client); 

    client.on('data', function (data) { 

     console.log('Broadcasting: '); 
     console.log(data.toString()); 
     console.log('-----------'); 

     broadcast(data, client); 
    }); 

    client.on('end', function() { 
     console.log(client.name + ' quit'); 
     clientList.splice(clientList.indexOf(client), 1); 
    }); 

    client.on('error', function (e) { 
     console.log(e); 
    }); 
}); 

function broadcast(message, sender) { 

    var text = sender.name + " says " + message; 

    var cleanup = []; 

    clientList.forEach(function (client) { 

     if (client !== sender) { 

      if (client.writable) {     
       client.write(text); 
      } else { 
       cleanup.push(client); 
       client.destroy(); 
      } 
     } 
    }); 

    cleanup.forEach(function (client) { 
     clientList.splice(clientList.indexOf(client), 1); 
    }); 
} 

chatServer.listen(9000); 

答えて

2

生のdataイベントに依存することはできません "多面的な"塊のデータを提示します。それは断片的に来るかもしれません、そして、あなたは必ずしもそれらの断片の大きさを制御することはできません、または、それらが特定の境界で分割されることはありません。

const split = require('split'); 
... 
client.pipe(split()).on('data', function (data) { 
    // `data` is now a separate line 
    console.log('Broadcasting: '); 
    console.log(data.toString()); 
    console.log('-----------'); 

    broadcast(data, client); 
}); 
+0

おかげで、ロバート:

はしかし、あなたを助けることができるモジュールが別々の(フル)ラインにデータを分割するであろう、例えばsplitのために、そこにあります。あなたの答えはそれを修正しました。それに加えて、私は 'os'モジュールをインクルードし、 '\ n'を 'os.EOL'に置き換えて、クライアント出力のメッセージを適切にフォーマットしなければなりませんでした。 –

+0

@ R.Costaああ、 'data'は(デフォルトでは)行末を含んでいません。 – robertklep

関連する問題