views:

73

answers:

2

I have to connect to a existing C system, and the tcp packet looks like

typedef struct exampleDataPacket{
  int messageType;
  float dataValue;
  char  dataDesc[100];
} 

So to send this kind of data using java, I can't find anything in my books. What would be the best way to send/receive this kind of data?

Thanks, CP

+5  A: 

You can use a DataOutputStream if the data you're trying to write is compatible with how it's going to be read on the C side. Check the documentation on writeFloat and writeChar carefully to see if that will actually work.

Otherwise you'll have to use a raw OutputStream and encode the data into bytes yourself.

Edit: Just wanted to add - my best guess is that for your purposes, writeFloat will work but writeChars will not, due to encoding issues. Instead, you'll have to use the getBytes method on your Java String to get a byte array in whatever single-byte character encoding your C code is expecting, then write those bytes to the DataOutputStream.

Dan
I would emphasize "Check the documentation ... carefully". When moving primitives across the wire, you're very likely to run into problems with encodings and different byte ordering.
kdgregory
Not only that, but everything in Java is signed while many C/C++ variables tend to be unsigned.
Jason Nichols
+1  A: 

Remember that Java is going to have things in network byte order; it is likely the C programmer was lazy and is not expecting that (at least in my experience) and you may have to compensate for their mistake and do some byte swapping.

danpaq