I’m developing a client-server app where the server is C++ and the client is Java.
To communicate them, I use sockets. Now, I can transfer sucessfully Strings via the socket with this:
Client side:
public void serializeAndSendMessage(String msg) {
try {
os.write( msg.getBytes() );
os.flush();
}
catch ( Exception e ) {
e.printStackTrace();
}
}
Server side:
char recvbuf[DEFAULT_BUFLEN];
int iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
if (iResult > 0) {
printf("Bytes received: %d\n", iResult);
recvbuf[iResult] = 0; //set the end of the msg
How can I pass other data, like a Double or an Int? Is it possible to get a Double into a String, and then convert it back in the C++ server from char to Double?
Thanx.
You really want something like Google ProtocolBuffers which takes care of the serialization and deserialization of arbitrary data structures in a cross-platform and cross-language manner.
There are other libraries providing an alternative to ProtoBuf such as Apache thrift (and some of which add the networking which ProtoBuf is missing). That said, ProtoBuf is a fine choice as it is mature, used by Google themselves and has Java and C++ as core languages with first-tier support.