Maison > Questions et réponses > le corps du texte
写的代码如下,每次telnet localhost 3000后输入字符,都只会单字符显示,且格式错乱?求解,问题出在哪里?
var net = require('net')
var count=0,users={}
var server = net.createServer(function (conn) {
conn.setEncoding('utf8')
var nickname;
conn.write(
'\n>welcome to node-chat!'
+'\n >'+count+'other people are connected at this time.'
+'\n > please write your name and press enter:'
);
count++;
conn.on('data',function(data){
data=data.replace('\r\n','')
if(!nickname){
if(users[data]){
conn.write('\033[93m> nickname already in use.try again:\033[39m');
return;
}else{
nickname=data
users[nickname]=conn
for(var i in users){
users[i].write('\033[90m>'+nickname+'joined the room\033[39m\n');
}
}
}else{
for (var i in users){
if(i!=nickname){
users[i].write('\033[96m>'+nickname+':\033[39m'+data+'\n');
}
}
}
})
conn.on('close',function(){
count--;
delete users[nickname];
})
})
server.listen(3000,function(){
console.log('\033[96m server listening on *:3000\033[39m')
})
显示效果如图: