Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS buffer splitting, string and binary

I have 3 pieces of information that I need to send in a UDP packet, the userID (int), auth code (string) and the binary data.

How would I be able to send those items at once and be able to split them at the other end.

I've tried concat'ing three buffers with the information but can't figure a way to split them at the other end, as the UID and auth code will vary in length.

like image 537
user2117190 Avatar asked Oct 05 '22 07:10

user2117190


1 Answers

assuming that the following apply

  • userID - unsigned 32bit integer
  • auth code - somekind of string let's say 100 chars length
  • binary data - ..

packing

var BinaryData=/*Your binary data*/;
var bufToSend = new Buffer(3+100+BinaryData.length);
bufToSend.writeUInt32LE(INTEGER,0);
bufToSend.write(STRING,4,STRING.length,"ascii");
BinaryData.copy(bufToSend,105,0,BinaryData.length);

unpacking

var userID = bufFromUDP.readUInt32LE(0);
var authCode = bufFromUDP.slice(4,104);
var BinaryData = bufFromUDP.slice(105,bufFromUDP.length);

Also you can try adding a "separator" between fields. ex.

var sep = new Buffer(2);
sep.write(";",0,1,'ascii');

and when doing Buffer.concat([userID,sep,authCode,sep]); after each field add the sep byte.

like image 164
Gntem Avatar answered Oct 13 '22 10:10

Gntem