码迷,mamicode.com
首页 > 其他好文 > 详细

beej's 网络编程 打包数据pack data

时间:2014-10-31 11:35:37      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:http   io   os   ar   for   sp   strong   数据   on   

7.4. Serialization—How to Pack Data

It‘s easy enough to send text data across the network, you‘re finding, but what happens if you want to send some "binary" data like ints or floats? It turns out you have a few options.

  1. Convert the number into text with a function like sprintf(), then send the text. The receiver will parse the text back into a number using a function like strtol().
  2. Just send the data raw, passing a pointer to the data to send(). (因为send的原型:

    ssize_t send(int sockfd, const void *buf, size_t len, int flags);)

  3. Encode the number into a portable binary form. The receiver 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 should 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 than 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 网络编程 打包数据pack data

标签:http   io   os   ar   for   sp   strong   数据   on   

原文地址:http://www.cnblogs.com/youxin/p/4064508.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!