简体   繁体   中英

Socket message header building

I'm working on a protocol which will transfer block of xml data via tcp socket. Now say I need to read all the bytes from a xml file and build a memory buffer. Then before sending the actual data bytes I need to send one header to other peer end. Say my protocol using below header type.

MessageID=100,Size=232,CRC=190

string strHeader = "100,232,190"

Now I would like to know how can I make this header length fixed (fixed header length is required for other peer to identify it as a header) for any amount of xml data. Currently say I'm having a xml file sized 283637bytes, so the message header will look like.

string strHeader = "100,283637,190"

How can I make it generic for any size of data? The code is being written both in c++ and c#.

There are a number of ways to do it.

Fixed Length

You can pad the numbers numbers with leading zeroes so you know exactly what length of the text you need to work with. 000100,000232,000190

Use Bytes instead of strings

If you are using integers, you can read the bytes as integers instead of manipulating the string. Look into the BinaryReader class. If needing to do this on the C++ side, the concept is still the same. I am sure there many ways to convert 4 bytes into an int.

Specify the length at the beginning

Usually when working with dynamic length strings. There is an indicator of how many bytes need to be read in order to get the entire string. You could specify the first 4 bytes of your message as the length of your string and then read up to that point.

The best approach for you is to implement this as a struct like

struct typedef _msg_hdr {
     int messageID;
     int size;
     int crc;
}msg_hdr;

This will always have 12 bytes length. Now when sending your message, first send header to the receiver. The receiver should receive it in the same structure. This is the best and easiest way

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