开发者

What is easiest way to send structured data via tcp using java?

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

typedef struct e开发者_运维技巧xampleDataPacket{
  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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜