Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending struct via Socket using JAVA and C++

I have a socket where server 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.

like image 517
looktt Avatar asked Feb 04 '10 18:02

looktt


3 Answers

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.

like image 54
jmanning2k Avatar answered Nov 15 '22 01:11

jmanning2k


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

like image 2
jojo Avatar answered Nov 15 '22 02:11

jojo


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;
}
like image 2
Peter Lawrey Avatar answered Nov 15 '22 02:11

Peter Lawrey