我有以下代码:
var packet = "\xFF\xFF\xFF\xFF";
packet += "\x6D";
packet += "127.0.0.1:" + this.port;
packet += "\x00";
packet += this.name;
packet += "\x00";
packet += this.map;
packet += "\x00";
packet += "game1";
packet += "\x00";
packet += "x-z";
packet += "\x00";
packet += String.fromCharCode(this.players.length);
packet += String.fromCharCode(this.maxplayers);
packet += String.fromCharCode(this.protocol);
packet += "\x64";
packet += "\x6C";
packet += "\x00";
packet += "\x01";
packet += "\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x01\x00\x01\x00";
return new Buffer(packet, "binary");
我现在正在从字符串创建缓冲区,但我认为这不是好的做法,并且字符串连接效率不高。如何用 Buffer 函数替换它并直接写入缓冲区?我无法理解 Buffer 是如何工作的,例如,如何\xFF
在开头写入 4 个字节。
谢谢你。