How do I send an array of integers over TCP in C?

后端 未结 7 512
小蘑菇
小蘑菇 2020-12-17 06:39

I\'m lead to believe that write() can only send data buffers of byte (i.e. signed char), so how do I send an array of long integers using the C write()

7条回答
  •  旧巷少年郎
    2020-12-17 07:29

    I think what you need to come up with here is a protocol.

    Suppose your integer array is:

    100, 99, 98, 97
    

    Instead of writing the ints directly to the buffer, I would "serialize" the array by turning it into a string representation. The string might be:

    "100,99,98,97"
    

    That's what would be sent over the wire. On the receiving end, you'd split the string by the commas and build the array back up.

    This is more standardised, is human readable, and means people don't have to think about hi/lo byte orders and other silly things.

    // Sarcasm

    If you were working in .NET or Java, you'd probably encode it in XML, like this:

    100999897
    

    :)

提交回复
热议问题