在NodeJ中编写和解析二进制数据

时间:2015-05-28 17:40:26

标签: javascript c# node.js io

所以我用nodejs写了服务器tcp应用程序,这里是代码:

服务器端

var host = "127.0.0.1";
var port = 15010;

// Instruct server to start Listening for incoming connection
function listen() {
  // Start Server
  console.log('Server Started [' + host + ':' + port + ']');

  var server = net.createServer(function(socket) {

    // Send Connection Success
    socket.write('Success');
    socket.pipe(socket);

    // Server Received a new Connection from Client
    console.log('Client was Connected [' +
      socket.remoteAddress + ':' + socket.remotePort + ']');


    // When Server Received data from Client.
    socket.on('data', function(resp) {
      console.log('We received following data: ' + resp);

      // probably going to tell server whether my Game is about to exit
      // so the server will close the current socket.
      // and also won't caught ECONNRESET exception lol.
    });

    // When Client Connection is Ended.
    socket.on('end', function() {
      console.log('Connected Ended ');

      // Destroy closed socket
      socket.destroy();
    });

    // When Client Connection is Closed.
    socket.on('close', function() {
      console.log('Client was Closed ');

      // Destroy closed socket
      socket.destroy();
    });

    // When Server caught an exception
    socket.on('error', function(ex) {
      // Server will caught an exception if client was disconnected from client side
      // It's appear the server was not expected when client is disconnected.
      // Currently, i will salvage it as much as i can until i find better solution (or this is the best solution(?) lol) but it's doesn't matter for now..
      if (ex.code == 'ECONNRESET') {
        console.log('Ending current session of Client');
      }
    });

  }).listen(port, host);

处理传入的字符串数据时效果很好 但是我想知道如何解析服务器从客户端收到的二进制数据。

我在游戏中使用以下代码将数据发送到服务器:

客户端

        // Use memory stream
        using (MemoryStream ms = new MemoryStream())
        {
            // Use binary writer also
            BinaryWriter writer = new BinaryWriter(ms);

            // Write int16 (2 bytes)
            writer.Write((short)id);

            // Write int32 (4 bytes)
            writer.Write((int)status);

            // Write int64 (8 bytes)
            writer.Write((long)score);

            // Write float (4 bytes)
            writer.Write((float)freq);

            // I can even write string on it easily (assuming username string is 2 chars)
            writer.Write(Encoding.UTF8.GetBytes(username));

            // The stream position should be
            // 2 + 4 + 8 + 4 + 2 = 20
            Console.WriteLine(ms.Position.ToString());

            // Send data to server
            socket.Send(ms.GetBuffer());
        }

在C#中,我可以使用以下代码轻松处理它(代码也类似于发送数据):

        // Receiving data from the Server
        byte[] resp;
        socket.Receive(out resp);

        // Could be handled with Memory Stream too
        using (MemoryStream ms = new MemoryStream(resp))
        {
            // This time i will use BinaryReader
            BinaryReader reader = new BinaryReader(ms);

            // Read int16 (2 bytes)
            short id = reader.ReadInt16();

            // Read int32 (4 bytes)
            int status = reader.ReadInt32();

            // Read int64 (8 bytes)
            long score = reader.ReadInt64();

            // Read float (4 bytes)
            float freq = reader.ReadSingle();

            // Read String (assuming data is 2 bytes)
            string username = Encoding.UTF8.GetString(reader.ReadBytes(2));

            // Same like before
            // The stream position should be
            // 2 + 4 + 8 + 4 + 2 = 20
            Console.WriteLine(ms.Position.ToString());
        }

但我如何在NodeJS中解析它?
有人可以告诉我NodeJS中应该使用哪些类来实现这一目标吗? (提供一个像我在C#中做的例子更受欢迎)

任何想法?
抱歉我的英语不好,提前谢谢

修改
所以我想了一下,看来收到的数据是默认的Buffer对象(感谢@dandavis) 在这里我的尝试和工作:

    // When Server Received data from Client.
    socket.on('data', function(resp) {
      // It's kinda hard (not effective(?))
      // since i need to specify offset each time im trying to read something

      // probably i will write simple class, or does anyone know class
      // that could handle like BinaryReader in C#?

      // Read int16 (2 bytes)
      var id = resp.readInt16LE(0);

      // Read int32 (4 bytes)
      var status = resp.readInt32LE(2);

      // I don't know how to read int64
      var score = // there is no readInt64LE ??

      // Read float (4 bytes)
      var freq = resp.readFloat(14);

      // Read string, assuming encoded with utf8 with 2 characters
      var username = resp.toString('utf8', 18, 2);
    });

但问题很少:

  • 我不知道如何阅读(和写)int64
  • 在API文档中,它没有描述LE和BE之间的区别(我只能推测它是Little Endian和Big Endian,但我不知道它们)

你们能告诉我如何阅读int64并简要介绍LE和BE吗?

谢谢!

0 个答案:

没有答案