Sending struct via Socket using JAVA and C++
I have a socket where serv开发者_JAVA技巧er is in JAVA but Client is in C++.
Struct{
float length;
char[] name;
}myStruct;
How can I convert the structures to a byte stream sent by Server and can be correctly parsed by Client? Any sample code would help! (I heard XML is an option but I am not familiar with it ) Thanks.
Try using Google's protocol buffers, hosted at the ProtocolBuffers page at Google Code. Small, efficient, python, Java, and C++ support. Sounds like it suits your needs well.
Less overhead than an XML approach, and better than rolling your own - it's harder than you'd think.
XML doesn't do Magic
you can use XML or plain text
to do that think what you whould have done working with files.
you would use jave to write the data to a file
then you can use c++ to read this file.
well the same is with socket
XML isn't special. plain text can do the work
XML only add structure
i wouldn't suggested to implement serialization by yourself for heavy tasks
you may consider using JNI/JNA a better way is to use corba but that may be an overkill
based on @finnw's answer...
class MyStruct {
float length;
String name;
}
void send(SocketChannel dst, MyStruct ms) throws IOException {
int len = 5 + ms.name.length();
ByteBuffer buf = ByteBuffer.allocate(len);
buf.putInt(len);
buf.putFloat(ms.length);
buf.put(ms.name.getBytes("US-ASCII"));
buf.put((byte) 0);
buf.flip();
dst.write(buf);
}
On the C side
struct mystruct *readMyStruct(int fd) {
uint32_t size;
read(fd, &size, sizeof size);
struct mystruct *result = malloc(size);
read(fd, result, size);
return result;
}
Use JSONRPC http://www.json.org/
Very easy to generate, very easy to parse. There are out of the box libs on the homepage.
Consider JSON for simplicity (something like JSONRPC, or just roll your own JSON)
for Thrift for complexity
精彩评论