简体   繁体   中英

What is the best way for streaming C++ struct data through TCP socket in Real-time between two projects in the same solution?

Basically I have a struct:

typedef struct MyStruct1 {
  vector<MyStruct2> data;
  chrono::high_resolution_clock::time_point time_stamp;
} MyStruct1;

MyStruct2 is a struct that contains some opencv data such as: Point2f . I want to share this between two projects that are in the same VS solution via TCP socket (because I need reliable connection). Also I tried shared memory but figured out that is not a good way to share complex data structures but for POD. But every time I dereference pointer to MyStruct1 in the client (project that receives data) my program crashes. Is there any solution to this? Or should I try some other way (and what would that way be)? The code that I used is here: server and client (NOTE: I am not using argv and argc but everything else is the same). Thanks in advance.

As long as it is on the same machine and compiled at the same time with all settings the same and the data class is shared on both you can get away with defining an friend operator<< and operator>> for each type, that are to be send.

Totally untested incomplete code

ostream& operator<<(ostream& os, const MyStruct1 & dt) {
    os << dt.time_stamp << dt.data.size(); // time_stamp might need more magic
    for(auto& val : dt.data) // the MyStruct2 must also have an <<
      os << val;
    return os;
}

Write it to a strstream and send the string to the other side, decode it with the >> .

TCP provides a stream of bytes. To send something over TCP, you need to serialize it into a stream of bytes. You can't just write the MyStruct1 object over the TCP connection. That will never work correctly because the object's internal representation in memory will contain data meaningful only inside the process and that will mean nothing to another process.

Another issue to keep in mind: There might be one entry in that vector. There might be a thousand. How will the receiver know how many bytes to read or know where the object ends?

There are lots of libraries and tools for serialization and deserialization.

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