Protocol buffers 从java客户端向C++服务器发送协议缓冲消息 我尝试从java客户端向C++服务器发送协议缓冲消息。在运行服务器和客户端之后,我只得到0作为Api字段的值,甚至在Java客户端将其设置为1

Protocol buffers 从java客户端向C++服务器发送协议缓冲消息 我尝试从java客户端向C++服务器发送协议缓冲消息。在运行服务器和客户端之后,我只得到0作为Api字段的值,甚至在Java客户端将其设置为1,protocol-buffers,Protocol Buffers,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

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;

验证为数据读入的字节数是否与info.toByteArray的大小相同。我的猜测是,它们是不同的,在这种情况下,您需要更改默认情况下从new_sock newline分隔的IO读取数据的方式?

您应该添加调试消息,以检查是否确实接收到与发送相同的字节数。我不认为新的数据;正在使用换行符和“\0”字符正常工作。ProtoBuf消息不包含有关自身长度的信息。当您通过原始套接字发送它们时,您必须首先告诉对方以下消息的长度。您应该看看protobufs CodedInputStream和CodedOutStream。