开发者

java client talking to c++ server through TCP connection

开发者 https://www.devze.com 2023-03-25 14:40 出处:网络
I\'m new to networking so hopefully I will be able to explain my issue. My boss recently made a dummy server for me to test my application\'s networking and I ran into issue regarding java to c++. Hi

I'm new to networking so hopefully I will be able to explain my issue.

My boss recently made a dummy server for me to test my application's networking and I ran into issue regarding java to c++. His server was written in c++ and when run, it waits and listens for a particular c++ data struct named "RemoteMsgStruct" to be passed:

typedef struct
{
unsigned int Length;
unsigned int BoardType;
unsigned int MsgType;
unsigned char Msg[MAX_MSG_SIZE];
} RemoteMsgStruct;

The problems lies in the fact that my program is written in java. How would I go about passing a similar message through java for the server to process?

Thanks ahead of开发者_开发问答 time for the help. If anything isn't explained well enough or appears to be missing let me know. Like I said, I'm new to both networking and stackoverflow :)


You can pass exactly the data expected by your boss's test program, without asking your boss to modify it.

On the Java side, you can write data in the layout defined by the C++ struct via several methods, including: * java.io.DataOutputStream * java.nio.ByteBuffer and java.nio.channels.SocketChannel.

You may encounter issues of field alignment and byte order. * Some fields in a C struct may start after padding to align with word boundaries. * Java will write network byte order (big-endian) by default. On the Java side, ByteBuffer allows choice of a different order.


Welcome to SO.

As to your question, there's a reason why messaging formats like XML and JSON are so popular, they solve problems like this. As it is you are going to have to battle with sending over unsigned ints and worrying about character encoding and endian-ness. If you cannot change the format on the server side then I will recommend you take a look at ByteBuffer. You will still have to do some massaging but at least it will relieve some of the pain.


Andy's answer is correct. However it should be said that your boss's program needs to be rewritten. Passing C structs directly over a network is never a good idea even when the other end is written in C. That technique relies on the following being the same at both ends:

  1. The hardware byte order
  2. The compiler's filling and packing rules
  3. The surrounding #pragmas

and therefore

  1. The compiler vendor
  2. The compiler version

This (incomplete) list is far too long already, and we are still only considering C to C.

0

精彩评论

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