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(seria开发者_运维知识库lizedMsg2)
})
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);
精彩评论