- 作为TCP客户端与服务端通信
- 通信协议带二进制协议头,二进制头中带命令字与数据长度,协议头之后为实际数据。
var net = require('net');
var client = new net.Socket();
client.setEncoding('utf8');
var serverIp = "127.0.0.1";
var serverPort = 9000;
var data = '<request version="1">\
<name>admin</name>\
<pwd>666666</pwd>\
<User-Agent>Client, Version 20210112</User-Agent>\
</request>'
var dataBuf = Buffer.from(data, 'utf8'); //字符串构建buffer
var dataLen = data.length;
console.log(dataBuf);
var headBuf = Buffer.alloc(32); // 协议头32字节
headBuf.writeUInt32LE(0x1002, 4); //协议头命令字
headBuf.writeUInt32LE(dataLen, 28); // 协议头中的数据长度
var sendBuf = Buffer.concat([headBuf, dataBuf]); // 协议头与数据拼接
client.connect(serverPort, serverIp, function(){
console.log("已连接到服务器");
client.write(sendBuf);
});
//监听数据
client.on('data', data=>{
var recvBuf = Buffer.from(data, 'utf8');
var command = recvBuf.readUInt32LE(4, 4);//命令字
var xml = data.substring(32);
console.log('服务器返回的数据:', xml);
})