2015-11-18 09:38:01
Service side
varNET = require (' net ');varServer = Net.createserver (function(socket) {Socket.on (' Data ',function(data) {Console.log (data); //data = json.parse (data);Console.log (' The type of this need is: ' +Data.transtype); if(Data.order = = ' Order1 ' && data.transtype = = ' Time ') { varTime =NewDate (); Data.time= Time.getminutes (). ToString () + ': ' + time.getseconds (). ToString () + '. ' +time.getmilliseconds (). toString (); Data.transtype= ' Time '; //console.log (' data: ');console.log (data); Console.log (' Send back time ' +data.time); Data=json.stringify (data); //Console.log (typeof data); //console.log (' data: ');console.log (data); Socket.write (data); } Else if(Data.transtype = = ' Result ') { varnum = 0; for(vari = 0; I < 10; i++) {num= num +i; } num= num + parseint (math.random () * 10); Data.result=num; Console.log (' Send back results ' +Data.result); Data=json.stringify (data); Socket.write (data); }}) Socket.on (' End ',function() {Console.log (' Client disconnects \ n '); }) Socket.on (' Error ',function(data) {Console.log (data); Console.log (' Client error '); }); Server.listen (8124,function() {Console.log (' Server-side open ');})
Client
varNET = require (' net ');varClient = Net.connect ({port:8124},function() {Console.log (' Client Connection '); //setinterval (function () { varTime =NewDate (); varA = {}; A.order= ' Order1 '; A.transtype= ' Time '; varA =Json.stringify (a); //a.setencoding (' utf-8 ');Console.log (a); Client.write (a); //}, +);}); Client.on (' Data ',function(data) {//console.log (' data: '); //console.log (data);data = data.tostring ("Utf-8"); Data=json.parse (data); //console.log (data); if(Data.transtype = = ' Time ') {Console.log (' Meter reading takes time: ' +data.time); Data.transtype= ' Result '; Data=json.stringify (data); Client.write (data); //Console.log (' need result ');}Else if(Data.transtype = = ' Result ') {Console.log (' Meter reading Result: ' + data.result + ' \ n '); //client.end (); //console.log (' data: '); //console.log (data);}}); Client.on (' End ',function() {Console.log (' Disconnect ');}) Client.on (' Error ',function(data) {Console.log (data); Console.log (Error);})
node. JS analog Meter-reading TCP server and client