本文实例讲述了nodejs简单实现TCP服务器端和客户端的聊天功能。分享给大家供大家参考,具体如下:
服务器端
用户输入数据,就将这些数据广播给其他所有已连接的用户
sockets.forEach(function(otherSocket){
if (otherSocket !== socket){
otherSocket.write(data);
}
});
//删除被关闭的连接
socket.on('close',function(){
console.log('connection closed');
var index = sockets.indexOf(socket);
sockets.splice(index,1);
});
});
});
server.on('error',function(err){
console.log('Server error:',err.message);
});
server.on('close',function(){
console.log('Server closed');
});
server.listen(4000);
客户端
= maxRetries) {
throw new Error('Max retries have been exceeded,I give up.');
}
retriedTimes +=1;
setTimeout(connect,retryTimeout);
}
conn = net.createConnection(port);
conn.on('connect',function() {
retriedTimes = 0;
console.log('connect to server');
});
conn.on('error',function(err) {
console.log('Error in connection:',err);
});
conn.on('close',function() {
if(! quitting) {
console.log('connection got closed,will try to reconnect');
reconnect();
}
});
//打印
conn.pipe(process.stdout,{end: false});
})();
希望本文所述对大家nodejs程序设计有所帮助。
原文链接:https://www.f2er.com/nodejs/34346.html