|
楼主 |
发表于 2018-9-25 10:57:03
|
显示全部楼层
- var net = require('net');
- var HOST = '127.0.0.1';
- var PORT = 502;
- // transactionID Protocol DatSize Addr CMD-ReadReg CMD-Reg-Addr CMD-Reg-Count
- const cmd = Buffer.from([ 0x55, 0xAA, 0, 0, 0, 6, 0x09, 0x03, 0x13, 0x94, 0, 2 ]);
- var tcp = new net.Socket();
- tcp.connect(PORT, HOST, function() {
- console.log('CONNECTED TO: ' + HOST + ':' + PORT);
- });
- tcp.on('data', function(ack){
- var sLine = "Recv: ";
- for(var i=0;i<ack.length;i++)
- sLine += ack[i].toString(16) + ' ';
-
- console.log( sLine );
- // console.log( '\n' )
- console.log( "CMD->Transaction ID:" + (cmd[0]*256+cmd[1]) )
- console.log( "CMD->Protocol ID:" + (cmd[2]*256+cmd[3]) )
- console.log( "CMD->Data Size:" + (cmd[4]*256+cmd[5]) )
- console.log( "CMD->Device Addr:" + (cmd[6]) )
- console.log( "CMD->Operation CMD:" + (cmd[7]) )
- console.log( "CMD->Register Addr:" + (cmd[8]*256+cmd[9]) )
- console.log( "CMD->Register Count:" + (cmd[10]*256+cmd[11]) )
- // console.log( "\n" )
- console.log( "ACK->Transaction ID:" + (ack[0]*256+ack[1]) )
- console.log( "ACK->Protocol ID:" + (ack[2]*256+ack[3]) )
- console.log( "ACK->Data Size:" + (ack[4]*256+ack[5]) )
- console.log( "ACK->Device Addr:" + (ack[6]) )
- console.log( "ACK->Operation CMD:" + (ack[7]) )
- console.log( "ACK->Raw Data Size:" + (ack[8]) )
- console.log( "ACK->Register[" + (cmd[8]*256+cmd[9]+0) + "]:" + (ack[9]*256+ack[10]) )
- console.log( "ACK->Register[" + (cmd[8]*256+cmd[9]+1) + "]:" + (ack[11]*256+ack[12]) )
- });
- tcp.on('close', function() {
- console.log('Connection closed');
- });
- var nCnt = 0;
- setInterval(function(){
- console.log( ">>>>---------------------------------------->>>" )
- var Tim = new Date();
- console.log( Tim.getFullYear() + '.' + Tim.getMonth() + '.' + Tim.getDate() + '-' + Tim.getHours() + ':' + Tim.getMinutes() + ':' + Tim.getSeconds() )
- tcp.write(cmd);
- var sLine = "Send: ";
- for(var i=0;i<cmd.length;i++)
- sLine += cmd[i].toString(16) + ' ';
- console.log( sLine );
- if(nCnt>10)
- client.destroy();
- nCnt++;
- },3000);
复制代码
再贴一个js版本的,浏览器只支持websocket不支持纯Socket,可以在nodejs环境下可以Run |
|