1.使用net模塊實現基于TCP的數據通訊
提供了一個net模塊,專用于實現TCP服務器與TCP客戶端之間的通信
1.1創建TCP服務器
在Node.js利用net模塊創建TCP服務器
var server = net.createServer([options],[connectionListener])//options:false當TCP服務器接收到客戶端發送的一個FIN包時將會回發一個FIN包 true當TCP服務器接收到客戶端發送的一個FIN包時將不會回發FIN包,這使得TCP服務器可以繼續向客戶端發送數據,但不會繼續接收客戶端發送的數據。來發者必須調用end方法來關閉socket連接。默認為falseconnectionListener:指定當客戶端與服務器端簡歷連接時所要調用的回調函數function(socket){ //回調函數代碼}
參數值為TCP服務器監聽的socket端口對象createServer方法返回被創建的TCP服務器
當客戶端與服務器建立連接時,觸發connection事件,可以利用下面方式執行回調函數
server.on('connection',function(socket){//回調函數代碼})
在創建TCP服務器后,使用listen方法通知服務器開始監聽客戶端連接
server.listen(port,[host],[backlog],[callback])//port指定需要監聽的端口號,host:指定需要監聽的IP地址或主機名,如果省略,服務器將監聽來自于任何IPv4地址的客戶端連接backlog:指定位于等待隊列中的客戶端連接的最大數量callback:無參回調函數server.listen(path,[callback])//server:代表一個使用unix端口的服務器path:指定需要監聽的路徑,會觸發listening事件,然后執行回調函數callbackserver.listenting(handle,[callback])//server 代表一個TCP服務器handle:指定需要監聽的socket句柄(該句柄可以為一個TCP服務器對象,socket端口對象,文件描述符)
現舉例創建一個TCP服務器:
var net = require('net')var server = net.createServer(function(socket){ console.log('客戶端與服務器連接已建立')})server.listen(8431,'localhost',function(){ console.log('服務器端開始監聽')})
運行后可得如下結果:
利用telnet訪問對應的服務器:
telnet localhost 8431
會出現的結果如下:
socket端口對象舉例:
var net = require('net')var file = require('fs').createWriteStream('./message.txt');var server = net.createServer(function(socket){console.log('客戶端與服務器連接已建立')server.getConnections(function(err,count){ console.log('當前存在%d個客戶端連接。',count); server.maxConnections = 4; console.log('TCP服務器的最大連接數為%d',server.maxConnections); })// server.close(function(){ // console.log('TCP服務器被關閉。');// })})server.listen(8431,'localhost',function(){console.log('服務器端開始監聽')})server.on('connection',function(socket){address = socket.address();console.log('被監視的地址信息為%j',address);socket.pipe(file);socket.setEncoding('utf8');socket.on('data',function(data){ console.log(data.toString()); console.log('已接受到%d字節數據。',socket.bytesRead);});socket.on('end',function(){ file.end('再見') console.log('客戶端連接被關閉。')})socket.pause();setTimeout(function(){ console.log('*************') socket.resume(); socket.pipe(file,{end:false});},30*1000);// socket.pipe(file,{end:false});// setTimeout(function(){ // file.end('再見。'); // socket.unpipe(file);// },5000);socket.setTimeout(10*1000);socket.on('timeout',function(){ console.log('客戶端連接超時'); socket.setTimeout(0);})})
1.2 創建TCP客戶端
建立TCP客戶端舉例:
var net = require("net");var client = new net.Socket();client.setEncoding('utf8');client.connect(8431,'localhost',function(){console.log('已連接到服務器');client.write('你好');console.log('當前已發送%d字節',client.bytesWritten);client.end('再見')console.log('當前已發送%d字節',client.bytesWritten);// setTimeout(function(){ // client.end('再見'); // },10*1000)});client.on('data',function(data){//console.log('已接收服務器端發送的數據: '+data);console.log('已接收服務器端發送的數據');})client.on('error',function(err){console.log('與服務器連接或通信的過程中發生了一個錯誤,錯誤編碼為%s',err.code);client.destroy();})
同時需要建立對應的服務器:
var net = require('net');var fs = require('fs');var server = net.createServer();server.on('connection',function(socket){console.log('客戶端與服務器端連接已建立');socket.setEncoding('utf8');var readStream = fs.createReadStream('./server.js');readStream.on('data',function(data){ var flag = socket.write(data); console.log('write方法的返回值為:'+flag); console.log('緩存隊列中當前緩存了%d字符。',socket.bufferSize);})socket.on('data',function(data){ console.log('已連接客戶端發送的數據:'+data); socket.write('確認數據:'+data);})socket.on('error',function(err){ console.log('客戶端通信的過程中發生了一個錯誤,錯誤編碼為%s',err.code); socket.destroy();})socket.on('end',function(){ console.log('客戶端連接被關閉。'); server.unref();})socket.on('close',function(had_error){ if(had_error){ console.log('由于一個錯誤導致socket端口被關閉。'); server.unref(); }else{ console.log('socket端口被正常關閉。'); }})server.getConnections(function(err,count){ if(count==2) server.close();});});server.listen(8431,'localhost');server.on('close',function(){console.log('TCP服務器被關閉。');})
在Node.js中利用下面方法可以向客戶端或服務器不斷發送探測包,以確定連接狀態;
socket.setKeepAlive([enable],[initialDelay])//enable:true:啟用Keep-alive機制,不斷向對方發送一個探測包,如果沒有回應表示連接關閉initialDelay:間隔時間(毫秒)
以上這篇Node.js學習之TCP/IP數據通訊(實例講解)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。
新聞熱點
疑難解答