简体   繁体   中英

Sending data from Node.js to Java over TCP

I'm trying to send messages (byte arrays) from Node.js to Java via TCP socket (serialized with protobuf).

I create a server socket on the java side, and connect to it from Node:

var client = net.createConnection(12345, "localhost")

client.addListener("connect", function(){
    client.write(serializedMsg1)
    client.end(serializedMsg2)
})

On the java-side I'm fetching the content from the input stream and deserializing it:

Protocol1.parseFrom(inputStream);
Protocol2.parseFrom(inputStream);

The problem is following - looks like only serializedMsg2 is passed/deserialized, whilst serializedMsg1 is ignored. As I understand, it happens, because the byte stream is not delimited, and size of the data chunks should be specified explicitly. Data shouldn't be read directly from the stream on the java side - delimeted chunkds should be read first, and deserialized as byte arrays afterwards.

You can use Buffer in order to pass the size of the data-chunk you're writing to the stream:

function writeInt(stream, int){
   var bytes = new Array(4)
   bytes[0] = int >> 24
   bytes[1] = int >> 16
   bytes[2] = int >> 8
   bytes[3] = int
   stream.write(new Buffer(bytes))
}

...

writeInt(client, data.length)
client.write(data)

On the Java side:

int size = inputStream.readInt();
byte[] result = new byte[size];
inputStream.read(byteArray);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM