Beej's network programming package data pack data

Source: Internet
Author: User
7.4. serialization-how to pack data

It's easy enough to send text data into ss the network, you're finding, but what happens if you want to send some "binary" data likeIntS orFloatS? It turns out you have a few options.

  1. Convert the number into text with a function likeSprintf (), Then send the text. The caller will parse the text back into a number using a function likeStrtol ().
  2. Just send the data raw, passing a pointer to the dataSend (). (Because of the prototype of send:

    Ssize_t send (INT sockfd, const void * Buf, size_t Len, int flags );)

  3. Encode the number into a portable binary form. The Handler er will decode it.

Sneak preview! Tonight only!

[Curtain raises]

Beej says, "I prefer method three, above! "

[The end]

(Before I begin this section in earnest)

I shoshould tell you that there are libraries out there for doing this, and rolling your own and remaining portable and error-free is quite a challenge. so hunt around and do your homework before deciding to implement this stuff yourself. I include the information here for those curious about how things like this work .)

Actually all the methods, above, have their drawbacks and advantages, but, like I said, in general, I prefer the third method. first, though, let's talk about some of the drawbacks and advantages to the other two.

The first method, encoding the numbers as text before sending, has the advantage that you can easily print and read the data that's coming over the wire. sometimes a human-readable protocol is excellent to use in a non-bandwidth-intensive situation, such as with Internet Relay Chat (IRC ). however, it has the disadvantage that it is slow to convert, and the results almost always take up more space t Han the original number!

METHOD Two: passing the raw data. This one is quite easy (but dangerous !) : Just take a pointer to the data to send, and call send with it.

Beej's network programming package data pack data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.