通过 TCP 将数据从 Node.js 发送到 Java
我正在尝试通过 TCP 套接字(使用 protobuf 序列化)将消息(字节数组)从 Node.js 发送到 Java。
我在 java 端创建一个服务器套接字,并从 Node 连接到它:
var client = net.createConnection(12345, "localhost")
client.addListener("connect", function(){
client.write(serializedMsg1)
client.end(serializedMsg2)
})
在 java 端,我从输入流中获取内容并反序列化它:
Protocol1.parseFrom(inputStream);
Protocol2.parseFrom(inputStream);
问题如下 - 看起来只有 serializedMsg2 被传递/反序列化,而
serializedMsg1
被忽略。据我了解,这种情况发生是因为字节流没有定界,并且应该明确指定数据块的大小。数据不应直接从 java 端的流中读取 - 应首先读取分隔的块,然后将其反序列化为字节数组。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 Buffer 来传递要写入流的数据块的大小:
在 Java 端:
You can use
Buffer
in order to pass the size of the data-chunk you're writing to the stream:On the Java side: