为什么在Java套接字中使用protobuf挂起parseFrom()函数? [英] Why did parseFrom() function hang using protobuf in java socket?

查看:56
本文介绍了为什么在Java套接字中使用protobuf挂起parseFrom()函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想使用protobuf和java创建回显服务器/客户端.

I just want to create echo server/client using protobuf and java.

我使用protobuf-java-2.4.1和jdk1.7进行了测试.

I tested with protobuf-java-2.4.1 and jdk1.7.

我写了如下的回显服务器代码

I wrote echo server code like below

// create server socket and accept for client connection.
// ...
link = servSock.accept();                       
Person person = Person.parseFrom(link.getInputStream()); // blocking position
person.writeTo(link.getOutputStream());

我认为没有必要注意Person.proto.

I think it is not necessary to note Person.proto.

客户端代码仅使用套接字输入流发送Person对象,并接收echo Person对象.

The client code is only send Person object using socket input stream and receive echo Person object.

// socket connect code was omitted.
Person person = Person.newBuilder().setId(1).setName("zotiger").build();
person.writeTo(echoSocket.getOutputStream());
person = Person.parseFrom(echoSocket.getInputStream());

但是当服务器和客户端都运行时,服务器在parseFrom函数中被阻止.

But server was blocked in parseFrom function when the server and client both run.

我发现如果我使用writeDelimitedTo()和parseDelimitedFrom(),那就可以了.我不明白为什么writeTo()和parseFrom()函数不能正常工作.

I found if i use writeDelimitedTo() and parseDelimitedFrom(), then that is ok. I don't understand why the writeTo() and parseFrom() function does not working.

为什么服务器在那里阻塞?

Why did the server blocking in there?

是否有必要从客户端发送一些结束信号?

Is it necessary to send some end signal from client side?

推荐答案

您必须使用 writeDelimitedTo()/ parseDelimitedFrom()的原因是,否则协议缓冲区可能会不知道需要从套接字读取多少数据.这就提出了一个问题(我说 may ,因为您当然可以创建仅具有固定长度字段的消息,而这并不需要此消息……但是协议缓冲区必须处理这两种情况)

The reason you have to use writeDelimitedTo()/parseDelimitedFrom() is that otherwise protocol buffers may have no idea how much data it needs to read from the socket. That presents a problem (I say may because you could of course create a message with only fixed length fields that wouldn't require this ... but protocol buffers has to deal with both cases)

writeDelimitedTo()方法将消息的长度写入 OutputStream ,然后写入消息本身.其对应的 parseDelimitedFrom()读取长度,然后读取消息.

The writeDelimitedTo() method writes the length of the message to the OutputStream then the message itself. Its counterpart parseDelimitedFrom() reads the length, then the message.

您可以对流使用 writeTo() pasrseFrom(),但是仅当您要写入/读取一条消息并且在写入后关闭流时才可以使用.然后,阅读者将获得EOF来指示消息的结尾(从仅包含一条消息的文件中读取时也是如此).

You can use writeTo() and pasrseFrom() with streams but only if you want to write/read a single message and are closing the stream after writing. The reader will then get an EOF to indicate the end of the message (also the case when reading from a file that contains only a single message).

这篇关于为什么在Java套接字中使用protobuf挂起parseFrom()函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆