【发布时间】:2011-05-25 04:57:43
【问题描述】:
我正在尝试将协议缓冲区消息从 Java 客户端发送到 C++ 服务器。运行服务器和客户端后,我只得到“0”作为 Api 字段的值,即使我在 Java 客户端将其设置为“1”。
Java 客户端代码如下所示:
public static void main(String[] args) throws IOException {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
//the protocol buffers message is called INFO and have only one field Api
INFO info = INFO.newBuilder()
.setApi(1)
.build();
try {
echoSocket = new Socket("localhost", 30000);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: Localhost.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: Localhost.");
System.exit(1);
}
out.println((info.toByteArray())); // serialize and the message
System.out.println("send ");
}
}
C++ 服务器代码如下所示:
int main ( int argc, int argv[] ){
INFO info;
try
{
// Create the socket
ServerSocket server ( 30000 );
while ( true )
{
ServerSocket new_sock;
server.accept ( new_sock );
try
{
while(true){
std::string data;
// in the next i'll i receive Data from the Java client i already test it with a string, and it works
new_sock >> data;
info.ParseFromString(data);
cout << "api: " << info.api() << endl;
}
}
catch ( SocketException& ) {}
}
}
catch ( SocketException& e )
{
std::cout << "Exception was caught:" << e.description() << "\nExiting.\n";
}
return 0;
}
我不确定我做错了什么。我不知道我是否正确序列化解析。我没有得到任何错误,只有一个错误的 Api 值。如果您发现任何问题,请告诉我!非常感谢!
【问题讨论】:
-
您应该添加调试消息以检查您是否真的收到了与您发送的一样多的字节。我不认为“new_sock >> data;”使用换行符和 '\0' 字符可以正常工作。 ProtoBuf 消息不包含有关自身长度的信息。当您通过原始套接字发送它们时,您必须首先告诉对方以下消息的长度。你应该看看 protobufs CodedInputStream 和 CodedOutputStream。
标签: protocol-buffers