首页 > 其他分享 >note_2023年1月9日22点46分

note_2023年1月9日22点46分

时间:2023-01-09 22:56:05浏览次数:50  
标签:00 const 22 46 buf chunk note Buffer data

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;
  });
});

标签:00,const,22,46,buf,chunk,note,Buffer,data
From: https://www.cnblogs.com/zhuoss/p/17038764.html

相关文章

  • leetcode-225-easy
    ImplementStackusingQueuesImplementalast-in-first-out(LIFO)stackusingonlytwoqueues.Theimplementedstackshouldsupportallthefunctionsofanorm......
  • 深圳市友浩达科技有限公司CTO 张善友 入选 2022 中国开源先锋 33 人|积聚开源力量,持续
    2023年1月3日,2022年「中国技术先锋」年度评选推出「2022中国开源先锋33人之心尖上的开源人物榜单」,深圳市友浩达科技有限公司CTO张善友评选成为“心”尖上的开源......
  • IDEA2022设置项目默认Maven仓库路径
    介绍我们在使用idea创建新项目时,如果没有提前做配置,那么每次创建maven项目都是使用默认的maven配置,每次还需要进行修改maven配置,十分不方便,那么如何在每次创建maven项目时,......
  • P2261 [CQOI2007]余数求和
    (昨天发病写题解,结果一看早就截止了)前置知识:数列分块我们先看一个式子\[\sum_{k=1}^{n}\lfloor\sqrtk\rfloor\]化简我们稍微枚举一下,就会发现这样一个性质这......
  • 老黑2022秋季上课内容
    老黑2022秋季上课内容链式前向星关键代码\(N\)表示点数+10;\(M\)表示边数+10。有向边初始数组structEdge{ intnext,to,v; /* *next记录上一条边同......
  • 2023/1/9 20221321杨渝学习打卡
    Python入门学习学习链接:https://www.bilibili.com/video/BV14r4y1k7F9/?spm_id_from=333.999.0.0&vd_source=a989a1afa6cb8b6527dd9bf059d71439输入,输出,计算1.输入:在c语......
  • client intended to send too large body: 2274148 bytes
    clientintendedtosendtoolargebody:2274148bytes 问题现象前端上传图片失败,nginx错误日志文件(/var/log/nginx/error.log)中的报错信息为:“clientintendedto......
  • 223. 最长上升子序列问题(挑战程序设计竞赛)
    地址https://www.papamelon.com/problem/223有一个长为n的序列a_0,a_1,...,a_n。求出这个序列的最长上升子序列的长度。上升子序列指的是对于任意的i<j都满足......
  • 波澜起伏的2022(身边的风景很美,可以停下来看看)
     前言  昨天晚上和女朋友聊天,突然就问起我2023年的计划拟定好了吗。是啊,恍惚之间,又是一年末尾。不禁想起2022年初的时候,总觉得是昨日的光景,还没走远。  细算......
  • 回首2022年,人间不清醒
        说一下目前的经历情况,本人java开发暖男一枚,年初开始在成都找工作,这段时间是最煎熬的,这期间收到过很多叫你面试的,每天都奔波在地铁上,不是在面试就是在面试的路......