0
我试图从Java客户端向C++服务器发送协议缓冲区消息。运行服务器和客户端后,我只是将“0”作为Api字段的值,即使我在Java客户端将其设置为“1”。从Java客户端向C++服务器发送协议缓冲区消息
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”数据;“与换行符和'\ 0'字符正常工作。 ProtoBuf消息不包含有关自身长度的信息。当你通过原始套接字发送它们时,你必须首先告诉对方以下消息的长度。您应该看看CodedInputStream和CodedOutputStream的原型。 – 2011-03-23 11:35:15