首页 > 解决方案 > 写入 NodeJs 缓冲区

问题描述

我正在处理 JS 客户端和 C# 服务器连接。

连接进展顺利。当我想将缓冲区从 JS 客户端发送到 C# 服务器时,就会出现问题。

对于要由我的服务器处理的缓冲区,缓冲区必须具有特定的结构:以 18 个字节编码的标头,然后是消息。

缓冲区包含:

  1. 8 字节的消息大小
  2. 8 字节的消息 ID
  3. 2 个字节的消息类型

在以前的版本中,我使用 C# 客户端发送此缓冲区。我这样进行:

//Header parameters
ulong ID = ulong.MaxValue;
ushort type = 0;

//Message
string message = "This is the message";
byte[] encodedMessage = Encoding.ASCII.GetBytes(message);

//Encoding the header and add header to buffer
byte[] buffer = new byte[encodedMessage.Length + 18];
Array.Copy(BitConverter.GetBytes(encodedMessage.LongLength + 18), 0, buffer, 0, 8);
Array.Copy(BitConverter.GetBytes(ID), 0, buffer, 8, 8);
Array.Copy(BitConverter.GetBytes((uint)type), 0, buffer, 16, 2);

//Adding the message to the buffer
Array.Copy(encodedMessage, 0, buffer, 18, encodedMessage.Length);

标头信息使用 C# BitConverter.GetBytes() 函数进行转换。

我想在 NodeJs 中做同样的事情

我这样做了:

var msg = "This is the message"

var size = 18 + msg.length

var buffer = new ArrayBuffer(size)
var buf = Buffer.from(buffer);

// Writting the header
buf.write(str(size-18),0,8) // Write the message size
buf.write("123456",8,8) // Write the id
buf.write("0",16,2) // Write the message type

//Adding the message to the buffer
buf.write(msg,18,msg.length)

但是这样一来,header就不会转换成有点像上面的C#函数了。

有没有办法在 nodejs 中做到这一点?

标签: javascriptnode.js

解决方案


您可以使用Buffer.alloc18 字节长度来初始化标头缓冲区。然后用类似这样的方式写入数据,最后将标头缓冲区与内容缓冲区连接起来:

const content = "This is the message";
const headerBuffer = Buffer.alloc(18);
headerBuffer.write(Buffer.from(content, 'ascii').byteLength.toString(), 0, 8);
headerBuffer.write("1234", 8, 8);
headerBuffer.write("0", 16, 2);
const contentBuffer = Buffer.from(content, 'ascii');
const result = Buffer.concat([headerBuffer, contentBuffer]);

将此缓冲区写入文件并显示hexdump结果:

$ hexdump -C tmp 
00000000  31 39 00 00 00 00 00 00  31 32 33 34 00 00 00 00  |19......1234....|
00000010  30 00 54 68 69 73 20 69  73 20 74 68 65 20 6d 65  |0.This is the me|
00000020  73 73 61 67 65                                    |ssage|
00000025

推荐阅读