我尝试使用node.js构建聊天服务器,但是它会在其他客户端上打印输入'控制台逐字逐句,有没有办法将它们放在一起
var net = require('net')
var chatServer= net.createServer()
clientList = []
chatServer.on('connection', function(client){
client.name = client.remoteAddress + ":" + client.remotePort
client.write('Hi' + client.name + "!\n");
clientList.push(client)
client.on('data', function(data){
broadcast(data, client)
})
})
function broadcast(message, client){
for(var i=0; i<clientList.length;i+=1){
if(client !== clientList[i]){
clientList[i].write(client.name + " says" + message +"\n")
}
}
}
chatServer.listen(9000, "127.0.0.1")
感谢。
答案 0 :(得分:2)
如果您的邮件是换行符分隔的,那么您可以执行以下操作:
chatServer.on('connection', function(client) {
client.name = client.remoteAddress + ":" + client.remotePort;
client.write('Hi' + client.name + "!\n");
clientList.push(client)
var buf = '';
client.setEncoding('utf8');
client.on('data', function(data) {
buf += data;
var i;
while ((i = buf.indexOf('\n')) > -1) {
broadcast(buf.substring(0, i), client);
buf = buf.substring(i + 1);
}
});
});