So, I wrote a tcp server application with nodejs, here is the code:
Server side
var host = "127.0.0.1";
var port = 15010;
function listen() {
console.log('Server Started [' + host + ':' + port + ']');
var server = net.createServer(function(socket) {
socket.write('Success');
socket.pipe(socket);
console.log('Client was Connected [' +
socket.remoteAddress + ':' + socket.remotePort + ']');
socket.on('data', function(resp) {
console.log('We received following data: ' + resp);
});
socket.on('end', function() {
console.log('Connected Ended ');
socket.destroy();
});
socket.on('close', function() {
console.log('Client was Closed ');
socket.destroy();
});
socket.on('error', function(ex) {
if (ex.code == 'ECONNRESET') {
console.log('Ending current session of Client');
}
});
}).listen(port, host);
It works well when processing incoming string data.
However, I was wondering how to parse the binary data received by the server from the client.
I use the following code in my game to send data to the server:
Client side
using (MemoryStream ms = new MemoryStream())
{
BinaryWriter writer = new BinaryWriter(ms);
writer.Write((short)id);
writer.Write((int)status);
writer.Write((long)score);
writer.Write((float)freq);
writer.Write(Encoding.UTF8.GetBytes(username));
Console.WriteLine(ms.Position.ToString());
socket.Send(ms.GetBuffer());
}
In C #, I could easily handle this code (the code is also similar to sending data):
byte[] resp;
socket.Receive(out resp);
using (MemoryStream ms = new MemoryStream(resp))
{
BinaryReader reader = new BinaryReader(ms);
short id = reader.ReadInt16();
int status = reader.ReadInt32();
long score = reader.ReadInt64();
float freq = reader.ReadSingle();
string username = Encoding.UTF8.GetString(reader.ReadBytes(2));
Console.WriteLine(ms.Position.ToString());
}
but how can I parse it in NodeJS?
can someone tell me which classes in NodeJS should i use to achieve this? (providing an example like I did in C # is much more appreciated)
any ideas?
sorry for my bad english, thanks in advance
, , Buffer ( @dandavis)
:
socket.on('data', function(resp) {
var id = resp.readInt16LE(0);
var status = resp.readInt32LE(2);
var score =
var freq = resp.readFloat(14);
var username = resp.toString('utf8', 18, 2);
});
:
- , ( ) int64
- API doc, , LE BE ( , Endian Big Endian, ).
, , , int64 LE BE?
!