从Java客户端向C ++服务器发送协议缓冲区消息

时间:2011-03-09 15:11:14

标签: protocol-buffers

我试图从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值。如果您发现任何问题,请告诉我!非常感谢!

1 个答案:

答案 0 :(得分:0)

我认为问题在于:

new_sock >> data;

验证data读入的字节数是否与info.toByteArray()的大小相同。我的猜测是他们不同,在这种情况下,您需要更改read(2) new_sock数据的方式(默认情况下换行符分隔?)。