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

发布于 2024-09-29 06:11:03 字数 616 浏览 0 评论 0原文

我正在尝试通过 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

欲拥i 2024-10-06 06:11:03

您可以使用 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)

在 Java 端:

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

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文