D:\code_gitee\python_socket\agvServer.ts
import { createServer } from "net";
const server = createServer();
server.listen(19204, "localhost");
server.on("connection", (socket) => {
socket.on("data", (chunk) => {
console.log(chunk);
socket.write(Buffer.from(chunk));
});
});
D:\code_gitee\python_socket\agvsocket.js
var net = require("net");
var client = new net.Socket();
client.setEncoding("utf8");
var serverIp = "192.168.1.3";
var serverPort = 19204;
// var data = "A";
// var dataBuf = Buffer.from(data, "ASCII"); //字符串构建buffer
// var dataLen = data.length;
// console.log(dataBuf);
// var headBuf = Buffer.alloc(2); // 协议头32字节
// headBuf.writeUInt32LE(0x1002, 0); //协议头命令字
// ----------------------------
// const buf = Buffer.allocUnsafe(2);
// buf.writeUInt32BE(0xfeedface, 0);
//------------------------
// const buf = Buffer.from("a", "ascii");
// console.log(buf.toString("hex"));
// --------------------------------
// const buf = Buffer.alloc(10);
// console.log(buf.toString("hex"));
// --------------------
function hex2buf(msgLenHexStr, size) {
if (msgLenHexStr.length % 2 !== 0) {
msgLenHexStr = "0" + msgLenHexStr;
}
const msgLenHexArr = msgLenHexStr.match(/[\da-f]{2}/gi).map(function (h) {
return Buffer.alloc(1).fill(parseInt(h, 16));
});
const msgLenHexArrLen = msgLenHexArr.length;
for (let i = 0; i < size - msgLenHexArrLen; i++) {
msgLenHexArr.unshift(Buffer.alloc(1).fill(0));
}
return msgLenHexArr;
}
function packMsg(reqId, msgType, msg = {}) {
const headBuf = Buffer.from([0x5a, 0x01]);
const reqIdBuf = Buffer.alloc(2);
reqIdBuf.fill(reqId, 1);
let msgLen = 0;
const msgJson = JSON.stringify(msg);
if (msgJson !== "{}") {
msgLen = msgJson.length;
}
const msgLenBuf = hex2buf(msgLen.toString(16), 4);
const msgTypeBuf = hex2buf(msgType.toString(16), 2);
const innerUseBuf = Buffer.alloc(6);
const msgBuf = Buffer.from(msgJson, "ascii");
console.log(msgBuf.toString("ascii"));
const buf = Buffer.concat([
headBuf,
reqIdBuf,
...msgLenBuf,
...msgTypeBuf,
innerUseBuf,
msgBuf,
]);
return buf;
}
//5A 01 00 01 00 00 00 1C 07 D2 00 00 00 00 00 00 7B 22 78 22 3A 31 30 2E 30 2C 22 79 22 3A 33 2E 30 2C 22 61 6E 67 6C 65 22 3A 30 7D
const buf = packMsg(1, 2002, { x: 10.0, y: 3.0, angle: 0 });
// const buf = packMsg(1, 1110);
console.log(buf.toString("hex"));
// headBuf.writeUInt32LE(dataLen, 28); // 协议头中的数据长度
// var sendBuf = Buffer.concat([headBuf, dataBuf]); // 协议头与数据拼接
client.connect(serverPort, serverIp, function () {
console.log("已连接到服务器");
client.write(buf);
client.destroy();
});
// //监听数据
// client.on("data", (data) => {
// varjrecvBuf = Buffer.from(data, "utf8");
// var command = recvBuf.readUInt32LE(4, 4); //命令字
// var xml = data.substring(32);
// console.log("服务器返回的数据:", xml);
// });
D:\code_gitee\python_socket\agvsocket.py
import socket
import json
import time
import struct
PACK_FMT_STR = '!BBHLH6s'
IP = '192.168.1.3'
Port = 19204
def packMasg(reqId, msgType, msg={}):
msgLen = 0
jsonStr = json.dumps(msg)
if (msg != {}):
msgLen = len(jsonStr)
print(msgLen)
rawMsg = struct.pack(PACK_FMT_STR, 0x5A, 0x01, reqId,
msgLen, msgType, b'\x00\x00\x00\x00\x00\x00')
print("{:02X} {:02X} {:04X} {:08X} {:04X}"
.format(0x5A, 0x01, reqId, msgLen, msgType))
if (msg != {}):
rawMsg += bytearray(jsonStr, 'ascii')
print(msg)
return rawMsg
so = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
so.connect((IP, Port))
so.settimeout(5)
test_msg = packMasg(1, 1110, {"id": ["123"]})
so.send(test_msg)
dataall = b''
# while True:
print('\n\n\n')
try:
data = so.recv(16)
print(data)
except socket.timeout:
print('timeout')
so.close
jsonDataLen = 0
backReqNum = 0
if (len(data) < 16):
print('pack head error')
print(data)
so.close()
else:
header = struct.unpack(PACK_FMT_STR, data)
print("{:02X} {:02X} {:04X} {:08X} {:04X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} length: {}"
.format(header[0], header[1], header[2], header[3], header[4],
header[5][0], header[5][1], header[5][2], header[5][3], header[5][4], header[5][5],
header[3]))
jsonDataLen = header[3]
backReqNum = header[4]
dataall += data
data = b''
readSize = 1024
try:
while (jsonDataLen > 0):
recv = so.recv(readSize)
data += recv
jsonDataLen -= len(recv)
if jsonDataLen < readSize:
readSize = jsonDataLen
print(json.dumps(json.loads(data), indent=1))
dataall += data
print(' '.join('{:02X}'.format(x) for x in dataall))
except socket.timeout:
print('timeout')
so.close()
D:\code_gitee\python_socket\agvsocketHex.js
function getBuffer(num, byteSize) {
const buffer = new ArrayBuffer(byteSize);
const view = new DataView(buffer);
switch (byteSize) {
case 1:
view.setInt8(0, num);
break;
case 2:
view.setUint16(0, num);
break;
case 4:
view.setUint32(0, num);
break;
default:
break;
}
return Buffer.from(view.buffer);
}
function packMsg(reqId, msgType, msg = {}) {
// 报文同步头和协议版本
const headBuf = Buffer.from([0x5a, 0x01]);
// 数据区长度
let msgLen = 0;
const msgJson = JSON.stringify(msg);
if (msgJson !== "{}") {
msgLen = msgJson.length;
}
// 数据区
const msgBuf = Buffer.from(msgJson, "ascii");
// API报文结构
const buf = Buffer.concat([
headBuf, // 报文同步头和协议版本
getBuffer(reqId, 2), // 请求序号
getBuffer(msgLen, 4), // 数据区长度
getBuffer(msgType, 2), // 报文类型
Buffer.alloc(6), // 内部使用区域, 0x 00 00 00 00 00 00 00,六个字节
msgBuf, // 数据区,json序列化的数据内容
]);
return buf;
}
const net = require("net");
const client = new net.Socket();
client.setEncoding("utf8");
const HOST = "192.168.1.3";
const PORT = 19204;
const buf = packMsg(1, 2002, { x: 10.0, y: 3.0, angle: 0 });
client.connect(PORT, HOST, function () {
client.write(buf);
});
client.addListener("data", (data) => {
console.log(data);
});
// //监听数据
// client.on("data", (data) => k
// const recvBuf = Buffer.from(data, "ascii");
// console.log(recvBuf);
// const command = recvBuf.readUInt32LE(4, 4); //命令字
// const xml = data.substring(32);
// console.log("服务器返回的数据:", xml);
// });
// client.destroy();
D:\code_gitee\python_socket\agvSocketPackage.js
function getBuffer(num, byteSize) {
const buffer = new ArrayBuffer(byteSize);
const view = new DataView(buffer);
switch (byteSize) {
case 1:
view.setInt8(0, num);
break;
case 2:
view.setUint16(0, num);
break;
case 4:
view.setUint32(0, num);
break;
default:
break;
}
return Buffer.from(view.buffer);
}
function packMsg(reqId, msgType, msg = {}) {
// 报文同步头和协议版本
const headBuf = Buffer.from([0x5a, 0x01]);
// 数据区长度
let msgLen = 0;
const msgJson = JSON.stringify(msg);
if (msgJson !== "{}") {
msgLen = msgJson.length;
}
// 数据区
const msgBuf = Buffer.from(msgJson, "ascii");
// API报文结构
const buf = Buffer.concat([
headBuf, // 报文同步头和协议版本
getBuffer(reqId, 2), // 请求序号
getBuffer(msgLen, 4), // 数据区长度
getBuffer(msgType, 2), // 报文类型
Buffer.alloc(6), // 内部使用区域, 0x 00 00 00 00 00 00 00,六个字节
msgBuf, // 数据区,json序列化的数据内容
]);
return buf;
}
const buf = packMsg(1, 2002, { x: 10.0, y: 3.0, angle: 0 });
console.log(buf);
D:\code_gitee\python_socket\agvsocketpackage.ts
import { Socket } from "net";
class MyPackage {
constructor() {}
encode(reqId: number, msgType: number, msg: any = {}) {
const msgJson = JSON.stringify(msg);
let msgLen = 0;
if (msgJson !== "{}") msgLen = msgJson.length;
const headerBuf = Buffer.alloc(1);
headerBuf.writeUInt8(0x5a);
const versionBuf = Buffer.alloc(1);
versionBuf.writeUInt8(0x01);
const reqidBuf = Buffer.alloc(2);
reqidBuf.writeUInt16BE(reqId);
const msgLenBuf = Buffer.alloc(4);
msgLenBuf.writeUInt32BE(msgLen);
const msgTypeBuf = Buffer.alloc(2);
msgTypeBuf.writeUint16BE(msgType);
const innerBuf = Buffer.alloc(6);
innerBuf.writeUIntBE(0, 0, 6);
const msgBuf = Buffer.from(msgJson, "ascii");
return Buffer.concat([
headerBuf,
versionBuf,
reqidBuf,
msgLenBuf,
msgTypeBuf,
innerBuf,
msgBuf,
]);
}
getPackageLen(chunk: Buffer) {
if (chunk.length < 16) {
return 0;
} else {
return 16 + chunk.readUInt16BE(16);
}
}
}
const agv = new MyPackage();
const res = agv.encode(1, 2002, { x: 10.0, y: 3.0, angle: 0 });
const client = new Socket();
const HOST = "localhost";
const PORT = 1234;
client.connect(PORT, HOST, function () {
client.write(res);
client.write(res);
client.write(res);
client.write(res);
});
let overageBuffer: any = null;
client.on("data", (chunk) => {
if (overageBuffer) {
chunk = Buffer.concat([overageBuffer, chunk]);
}
let packageLen = 0;
while ((packageLen = agv.getPackageLen(chunk))) {
const data = chunk.slice(0, packageLen);
chunk = chunk.slice(packageLen);
console.log(data.slice(16).toString("ascii"));
}
overageBuffer = chunk;
});
D:\code_gitee\python_socket\server.ts
import { createServer } from "net";
const server = createServer();
const PORT = 1234;
const HOST = "localhost";
class MyPackage {
constructor() {}
encode(reqId: number, msgType: number, msg: any = {}) {
const msgJson = JSON.stringify(msg);
let msgLen = 0;
if (msgJson !== "{}") msgLen = msgJson.length;
const headerBuf = Buffer.alloc(1);
headerBuf.writeUInt8(0x5a);
const versionBuf = Buffer.alloc(1);
versionBuf.writeUInt8(0x01);
const reqidBuf = Buffer.alloc(2);
reqidBuf.writeUInt16BE(reqId);
const msgLenBuf = Buffer.alloc(4);
msgLenBuf.writeUInt32BE(msgLen);
const msgTypeBuf = Buffer.alloc(2);
msgTypeBuf.writeUint16BE(msgType);
const innerBuf = Buffer.alloc(6);
innerBuf.writeUIntBE(0, 0, 6);
const msgBuf = Buffer.from(msgJson, "ascii");
return Buffer.concat([
headerBuf,
versionBuf,
reqidBuf,
msgLenBuf,
msgTypeBuf,
innerBuf,
msgBuf,
]);
}
getPackageLen(chunk: Buffer) {
if (chunk.length < 16) {
return 0;
} else {
return 16 + chunk.readUInt16BE(16);
}
}
}
const agv = new MyPackage();
server.listen(PORT, HOST);
let overageBuffer: any = null;
server.on("connection", (socket) => {
socket.on("data", (chunk) => {
if (overageBuffer) {
chunk = Buffer.concat([overageBuffer, chunk]);
}
let packageLen = 0;
while ((packageLen = agv.getPackageLen(chunk))) {
const data = chunk.slice(0, packageLen);
chunk = chunk.slice(packageLen);
console.log(data.slice(16).toString("ascii"));
console.log("------------------");
socket.write(
Buffer.from([
0x5a, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x3c, 0x2a, 0xfc, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x7b, 0x22, 0x72, 0x65, 0x74, 0x5f,
0x63, 0x6f, 0x64, 0x65, 0x22, 0x3a, 0x30, 0x2c, 0x22, 0x78, 0x22,
0x3a, 0x36, 0x2e, 0x30, 0x2c, 0x22, 0x79, 0x22, 0x3a, 0x32, 0x2e,
0x30, 0x2c, 0x22, 0x61, 0x6e, 0x67, 0x6c, 0x65, 0x22, 0x3a, 0x31,
0x2e, 0x35, 0x37, 0x2c, 0x22, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x64,
0x65, 0x6e, 0x63, 0x65, 0x22, 0x3a, 0x30, 0x2e, 0x39, 0x7d,
])
);
}
overageBuffer = chunk;
});
});