开发者

How to create a custom object using node.js

I have a java-based server that allows client applications to connect via other programming languages (java, unity, obj-c). I would like to know how to add javascript to this list using node.js and socket.io. The server listens on a set port and accepts simple json data plus an int for length in bytes, it response in the same format. The format of the "packet" is like so:

first four bytes are the length
00 00 00 1c

remaining bytes are the data
7b 22 69 64 22 3a 31 2c 22 6e 61 6d 65 22 3a 22 73 6f 6d 65 77 69 64 67 65 74 22 7d

The data is sent over TCP and is encoded in little endian. The object in originating from Java is modeled like so:

public class Widget {
    private int id;
    private String name;
    public int getId() { return id; }
    public String getName() { return name; }
}
开发者_如何学运维

The JSON would be:

{"id":1,"name":"somewidget"}


You will need a TCP socket. Connect it to the service and listen for the data event. When the data event is fired look at the buffers length. If it is <= 4 byte, you propably should discard it*. Else read the first 4 bytes using readUInt32() specifying 'little' as the endianess. Then use this number for the length of the remainding buffer. If the buffer is shorter than the given length, only "read" the remaining length, else "read" the given length. Use the toString method for this. You will get a string that can be parsed using the JSON.parse method, which will return you the JavaScript object matching the JSON.

You can build your packets basicly the same way by instanciating a buffer and writing all the data to it.

Also see the Buffers and net documentation for details.

* I do not know when node fires it's data events but your data might be received fragmented (that is splitted up into multiple data events). It could happen and due to the streaming nature of the tcp protocol it most likely will happen if the JSON string is long enough to not fit into a single frame. In that case, you propably should not simply discard the buffer, but try to reassemble the fragmented data.


So if you want just send request to server and get response you could do this:

var net = require('net');

var soc = net.Socket();
soc.connect(8088);

soc.on('connect', function(){
  var data, request, header;

  data = {request : true};
  data = JSON.stringify(data);

  request = new Buffer(Buffer.byteLength(data));
  request.write(data);

  header = new Buffer(4);
  header.write(request.length.toString());


  // send request  
  soc.end(header.toString('binary') + request.toString('binary'));
});

soc.on('data', function(buffer){
  // Crop length bytes
  var data = JSON.parse(buffer.slice(4).toString('utf-8'));
  soc.destroy();

  console.log(data);
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜