本文實例講述了nodejs簡單實現TCP服務器端和客戶端的聊天功能。分享給大家供大家參考,具體如下:
服務器端
var net = require('net'); var server = net.createServer(); //聚合所有客戶端 var sockets = []; //接受新的客戶端連接 server.on('connection', function(socket){ console.log('got a new connection'); sockets.push(socket); //從連接中讀取數據 socket.on('data', function(data){ console.log('got data:', data); //廣播數據 //每當一個已連接的用戶輸入數據,就將這些數據廣播給其他所有已連接的用戶 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);
客戶端
var net = require('net'); var port = 4000; var quitting = false; var conn; var retryTimeout = 3000; //三秒,定義三秒后重新連接 var retriedTimes = 0; //記錄重新連接的次數 var maxRetries = 10; //最多重新連接十次 process.stdin.resume(); //process.stdin流來接受用戶的鍵盤輸入,這個可讀流初始化時處于暫停狀態,調用流上的resume()方法來恢復流 process.stdin.on('data', function(data){ if (data.toString().trim().toLowerCase() === 'quit'){ quitting = true; console.log('quitting'); conn.end(); process.stdin.pause(); } else { conn.write(data); } }); //連接時設置最多連接十次,并且開啟定時器三秒后再連接 (function connect() { function reconnect() { if (retriedTimes >= 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程序設計有所幫助。
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com