本文實(shí)例講述了nodejs簡單實(shí)現(xiàn)TCP服務(wù)器端和客戶端的聊天功能。分享給大家供大家參考,具體如下:
服務(wù)器端
var net = require('net');var server = net.createServer();//聚合所有客戶端var sockets = [];//接受新的客戶端連接server.on('connection', function(socket){ console.log('got a new connection'); sockets.push(socket); //從連接中讀取數(shù)據(jù) socket.on('data', function(data){ console.log('got data:', data); //廣播數(shù)據(jù) //每當(dāng)一個(gè)已連接的用戶輸入數(shù)據(jù),就將這些數(shù)據(jù)廣播給其他所有已連接的用戶 sockets.forEach(function(otherSocket){ if (otherSocket !== socket){ otherSocket.write(data); } }); //刪除被關(guān)閉的連接 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; //記錄重新連接的次數(shù)var maxRetries = 10; //最多重新連接十次process.stdin.resume(); //process.stdin流來接受用戶的鍵盤輸入,這個(gè)可讀流初始化時(shí)處于暫停狀態(tài),調(diào)用流上的resume()方法來恢復(fù)流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); }});//連接時(shí)設(shè)置最多連接十次,并且開啟定時(shí)器三秒后再連接(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});})();希望本文所述對(duì)大家nodejs程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注