问题
I have a general socket programming question for you.
I have a C struct called Data:
struct data {
double speed;
double length;
char carName[32];
struct Attribs;
}
struct Attribs {
int color;
}
I would like to be able to create a similar structure in Java, create a socket, create the data packet with the above struct, and send it to a C++ socket listener.
What can you tell me about having serialized data (basically, the 1's and 0's that are transferred in the packet). How does C++ "read" these packets and recreate the struct? How are structs like this stored in the packet?
Generally, anything you can tell me to give me ideas on how to solve such a matter.
Thanks!
回答1:
- Be weary of endianness if you use binary serialization. Sun's JVM is Big Endian, and if you are on an Intel x86 you are on a little endian machine.
- I would use Java's ByteBuffer for fast native serialization. ByteBuffers are part of the NIO library, thus supposedly higher performance than the ol' DataInput/OutputStreams.
- Be especially weary of serializing floats! As suggested above, its safer to transfer all your data to character strings across the wire.
- On the C++ side, regardless of the the networking, you will have a filled buffer of data at some point. Thus your deserialization code will look something like:
size_t amount_read = 0;
data my_data;
memcpy(buffer+amount_read, &my_data.speed, sizeof(my_data.speed))
amount_read += sizeof(my_data.speed)
memcpy(buffer+amount_read, &my_data.length, sizeof(my_data.length))
amount_read += sizeof(my_data.length)
- Note that the sizes of basic C++ types is implementation defined, so you primitive types in Java and C++ don't directly translate.
- You could use Google Protocol buffers. My preferred solution if dealing with a variety of data structures.
- You could use JSON for serialization too.
回答2:
The basic process is:
- java app creates some portable version of the structs in the java app, for example XML
- java app sends XML to C++ app via a socket
- C++ app receives XML from java app
- C++ app creates instances of structs using the data in the XML message
来源:https://stackoverflow.com/questions/3419322/general-socket-question-transferring-c-structs-from-java-to-c