简体   繁体   English

通过TCP将数据从Node.js发送到Java

[英]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). 我正在尝试通过TCP套接字(使用protobuf序列化)将消息(字节数组)从Node.js发送到Java。

I create a server socket on the java side, and connect to it from Node: 我在Java端创建一个服务器套接字,然后从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: 在Java方面,我从输入流中获取内容并反序列化它:

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

The problem is following - looks like only serializedMsg2 is passed/deserialized, whilst serializedMsg1 is ignored. 问题在后面-看起来只有serializedMsg2被传递/反serializedMsg1 ,而serializedMsg1被忽略。 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. 不应直接从Java端的流中读取数据-应当首先读取经过修饰的块,然后再将其反序列化为字节数组。

You can use Buffer in order to pass the size of the data-chunk you're writing to the stream: 您可以使用Buffer来将要写入的数据块的大小传递给流:

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: 在Java方面:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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