问题描述:

Im trying to send a Protocol buffer message from a Java Client to a C++ Server. After runing the server and the client i just get "0" as a value for the Api field, even i set it as "1" in the Java client side.

The Java Client code looks like this:

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 ");

}

}

And the C++ server code looks like this:

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;

}

I am not sure what I am doing wrong. I don't know if I am serializing an parsing correctly. i didn't get any errors only a false Api value. Please let me know if you see any problems! Thanks a lot!

网友答案:

I think the problem is with:

new_sock >> data;

Verify that the number of bytes read in for data is the same as the size of info.toByteArray(). My guess is they're different, in which case you need to change the way that you're read(2)ing data from new_sock (newline delimited IO by default?).

相关阅读:
Top