简体   繁体   中英

java client talking to c++ server through TCP connection

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM