本文實(shí)例講述了通過node.js的net模塊實(shí)現(xiàn)nodejs socket服務(wù)端和客戶端簡單通信功能,可以用作客戶端對(duì)服務(wù)端的端口監(jiān)聽以及事件回執(zhí)。
server端代碼
var net = require('net'); //模塊引入 var listenPort = 8080;//監(jiān)聽端口 var server = net.createServer(function(socket){ // 創(chuàng)建socket服務(wù)端 console.log('connect: ' + socket.remoteAddress + ':' + socket.remotePort); socket.setEncoding('binary'); //接收到數(shù)據(jù) socket.on('data',function(data){ console.log('client send:' + data); }); socket.write('Hello client!\r\n'); // socket.pipe(socket); //數(shù)據(jù)錯(cuò)誤事件 socket.on('error',function(exception){ console.log('socket error:' + exception); socket.end(); }); //客戶端關(guān)閉事件 socket.on('close',function(data){ console.log('client closed!'); // socket.remoteAddress + ' ' + socket.remotePort); }); }).listen(listenPort); //服務(wù)器監(jiān)聽事件 server.on('listening',function(){ console.log("server listening:" + server.address().port); }); //服務(wù)器錯(cuò)誤事件 server.on("error",function(exception){ console.log("server error:" + exception); });
client端代碼
var net = require('net'); var port = 8080; var host = '127.0.0.1'; var client= new net.Socket(); //創(chuàng)建socket客戶端 client.setEncoding('binary'); //連接到服務(wù)端 client.connect(port,host,function(){ client.write('hello server'); //向端口寫入數(shù)據(jù)到達(dá)服務(wù)端 }); client.on('data',function(data){ console.log('from server:'+ data); //得到服務(wù)端返回來的數(shù)據(jù) }); client.on('error',function(error){ //錯(cuò)誤出現(xiàn)之后關(guān)閉連接 console.log('error:'+error); client.destory(); }); client.on('close',function(){ //正常關(guān)閉連接 console.log('Connection closed'); });
運(yùn)行結(jié)果如下
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com