nodejs socket實現的服務端和客戶端簡單通訊
阿新 • • 發佈:2018-11-21
本文例項講述了通過node.js的net模組實現nodejs socket服務端和客戶端簡單通訊功能,可以用作客戶端對服務端的埠監聽以及事件回執。
server端程式碼
var net = require('net');//模組引入var listenPort = 8080;//監聽埠var server = net.createServer(function (socket){ // 建立socket服務端 console.log('connect: ' + socket.remoteAddress + ':' + socket.remotePort); socket.setEncoding('binary'); //接收到資料 socket.on('data',function(data){ console.log('client send:' + data); });socket.write('Hello client!\r\n' ); // socket.pipe(socket); //資料錯誤事件 socket.on('error',function(exception){ console.log('socket error:' + exception); socket.end(); }); //客戶端關閉事件 socket.on('close',function(data){ console.log('client closed!'); // socket.remoteAddress + ' ' + socket.remotePort); });}).listen(listenPort);//伺服器監聽事件server.on('listening',function(){ console.log("server listening:" + server.address().port);});//伺服器錯誤事件server.on("error",function(exception){ console.log("server error:" + exception);});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
client端程式碼
var net = require('net');var port = 8080;var host = '127.0.0.1';var client= new net.Socket();//建立socket客戶端client.setEncoding('binary');//連線到服務端client.connect(port,host,function(){ client.write('hello server'); //向埠寫入資料到達服務端});client.on('data',function(data){ console.log('from server:'+ data); //得到服務端返回來的資料});client.on('error',function(error){//錯誤出現之後關閉連線 console.log('error:'+error); client.destory();});client.on('close',function(){//正常關閉連線 console.log('Connection closed');});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
執行結果如下
再分享一下我老師大神的人工智慧教程吧。零基礎!通俗易懂!風趣幽默!希望你也加入到我們人工智慧的隊伍中來!http://www.captainbed.net