使用nodejs发送和接受tcp请求

使用nodejs发送和接受tcp请求
// 使用 promise-socket 同步执行
const {PromiseSocket} = require("promise-socket")

const client = async (path, fileName) => {
  const socket = new PromiseSocket();
  socket.setTimeout(1000)
  await socket.connect({host:ip, port:port});
  let response = await socket.read(1)
  await socket.write(Buffer.from([IP.length%16, IP.length/16]));
  await socket.end();
  return true;
}

tcp 是以字节流来发送和接受数据,通过wireshark可以看到
00 50 56 99 e8 00 3c fd fe 7c 78 01 08 00 45 00
00 34 cc 3b 40 00 36 06 77 58 3d a4 2f ce 0a 15
89 a9 1d f4 a6 67 a6 c8 9f e0 dd cc f7 fd 80 11
00 08 4a 6b 00 00 01 01 08 0a 6e ed 67 b1 05 2f
6e 7b
其中 00 表示一个字节(8位), 8位的二进制数最多可以表示255(11111111);
所以如果要算出一个字节的数具体是多少,可以通过与 256的n次方 求商或者取余得到;
12345
1 226 64
1  E2 40

从右往左:第n位数 = (12345/256的n次方)%256
n从0开始

例子: 将数字1234以 2 bytes发出
1. 1234转换为16进制:04D2
2. 
Buffer.from([1234/256, 1234%256]); //大端
Buffer.from([1234%256, 1234/256]); //小端

计算机硬件有两种储存数据的方式:大端字节序(big endian)和小端字节序(little endian)。
举例来说,数值0x2211使用两个字节储存:高位字节是0x22,低位字节是0x11。
大端字节序:高位字节在前,低位字节在后,这是人类读写数值的方法。
小端字节序:低位字节在前,高位字节在后,即以0x1122形式储存。

猜你喜欢

转载自www.cnblogs.com/stellar/p/11545036.html