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.

double d = 3490.15926535;

send(s, &d, sizeof d, 0);  /* DANGER--non-portable! */

The receiver gets it like this:

double d;

recv(s, &d, sizeof d, 0);  /* DANGER--non-portable! */

Fast, simple—what's not to like? Well, it turns out that not all architectures represent a double (or int for that matter) with the same bit representation or even the same byte ordering! The code is decidedly non-portable. (Hey—maybe you don't need portability, in which case this is nice and fast.)

When packing integer types, we've already seen how the htons()-class of functions can help keep things portable by transforming the numbers into Network Byte Order, and how that's the Right Thing to do. Unfortunately, there are no similar functions for float types. Is all hope lost?

Fear not! (Were you afraid there for a second? No? Not even a little bit?) There is something we can do: we can pack (or "marshal", or "serialize", or one of a thousand million other names) the data into a known binary format that the receiver can unpack on the remote side.

What do I mean by "known binary format"? Well, we've already seen the htons() example, right? It changes (or "encodes", if you want to think of it that way) a number from whatever the host format is into Network Byte Order. To reverse (unencode) the number, the receiver calls ntohs().

But didn't I just get finished saying there wasn't any such function for other non-integer types? Yes. I did. And since there's no standard way in C to do this, it's a bit of a pickle (that a gratuitous pun there for you Python fans).

The thing to do is to pack the data into a known format and send that over the wire for decoding. For example, to pack floats, here's something quick and dirty with plenty of room for improvement:

http://beej.us/guide/bgnet/output/html/singlepage/bgnet.html#serialization

pack模拟实现:

beej's 网络编程 打包数据pack data的更多相关文章

  1. TCP/IP网络编程之数据包协议

    一.概要 在了解了网络字节序之后,接下来就是要讲最最重点的消息协议.数据包是什么呢,数据包可以理解为两个人讲电话说的每一句话的内容.通过大家约定好的方式去理解.达到只有接听电话两个人才懂的东西.在程序 ...

  2. 网络编程-pcap数据包格式

    Libpcap的官方网站是http://www.tcpdump.org/,该项目和Tcpdump项目是同一个团队维护.Libpcap是一个平台独立的 数据包捕获开发包,制定了数据包离线存储的事实标准. ...

  3. java网络编程——多线程数据收发并行

    基本介绍与思路 收发并行 前一篇博客中,完成了客户端与服务端的简单TCP交互,但这种交互是触发式的:客户端发送一条消息,服务端收到后再回送一条.没有做到收发并行.收发并行的字面意思很容易理解,即数据的 ...

  4. 【Linux 网络编程】数据在网络中传输过程(以ping命令为例)

    (1)应用程序ping会判断发送的是主机名还是IP地址,调用函数gethostbyname()解析主机B,将主机转换为一个32位的    IP地址.这个过程叫做DNS域名解析. (2)ping程序向目 ...

  5. 初探iOS网络开发,数据解析。

    通过大众点评平台开发来简单了解一下,oc的网络编程和数据解析(json) 首先我们需要到大大众点评开发者平台申请一个key.http://developer.dianping.com/app/tech ...

  6. core java 10~12(多线程 & I/O & Network网络编程)

    MODULE 10 Threads 多线程-------------------------------- 进程: 计算机在运行过程中的任务单元,CPU在一个时间点上只能执行一个进程,但在一个时间段上 ...

  7. 梦入IBM之java基础-网络编程

    如今我们来谈谈最后的内容:网络编程: 1):TCP中是线程与线程进行通讯!内部的执行机制是这种:先有一个线程去监听某个port.然后假设有Socket连接上来了以后,server会生成一个Socket ...

  8. 用C++实现网络编程---抓取网络数据包的实现方法

    一般都熟悉sniffer这个工具,它可以捕捉流经本地网卡的所有数据包.抓取网络数据包进行分析有很多用处,如分析网络是否有网络病毒等异常数据,通信协议的分析(数据链路层协议.IP.UDP.TCP.甚至各 ...

  9. Android之网络编程利用PHP操作MySql插入数据(四)

    因为最近在更新我的项目,就想着把自己在项目中用到的一些的简单的与网络交互的方法总结一下,所以最近Android网络编程方面的博文会比较多一些,我尽量以最简单的方法给大家分享,让大家明白易懂.如果有什么 ...

随机推荐

  1. 常见的百度蜘蛛IP

    根据不同的IP我们可以分析网站是个怎样的状态, 以下常见的百度蜘蛛IP: 123.125.68.*这个蜘蛛经常来,别的来的少,表示网站可能要进入沙盒了,或被者降权. 220.181.68.*每天这个I ...

  2. android开发 获取父控件的高宽

    @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(wi ...

  3. 前端之JavaScript第三天学习(7)-JavaScript-数据类型

    字符串.数字.布尔.数组.对象.Null.Undefined JavaScript 拥有动态类型 JavaScript 拥有动态类型.这意味着相同的变量可用作不同的类型: 实例 var x      ...

  4. HDU 5781 ATM Mechine 期望dp

    题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=5781 ATM Mechine Time Limit: 6000/3000 MS (Java/Othe ...

  5. 【转】EXT VTYPE自定义举例

    原文地址:http://www.blogjava.net/xiaohuzi2008/archive/2012/12/08/392676.html 近日来对Ext特别感兴趣,也许是它那种OO的设计思想吸 ...

  6. hdu 4004 The Frog's Games

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4004 The annual Games in frogs' kingdom started again ...

  7. 【BZOJ】【2756】【SCOI2012】奇怪的游戏

    网络流-最大流 这题……建模部分先略过 这道题是会卡时限的T_T俺的Dinic被卡了,在此放几篇很棒的讲网络流算法的文章,至于大家耳熟能详的论文就不放了…… http://www.cppblog.co ...

  8. Docker学习资料

    官方Docker:https://www.docker.com/ CSDN Docker : http://docker.csdn.net/ Docker中文社区:http://www.docker. ...

  9. Web流程

    Web阻塞加载,异步加载. 延迟执行,立即执行. 加载并执行,不要调用代码. 加载并执行时会调用代码,但是加载并执行时不要调用代码,否则会改变逻辑. 上面是Web流程,JS只是web的一部分.如果关注 ...

  10. poj 3686

    The Windy's Time Limit: 5000MS   Memory Limit: 65536K Total Submissions: 3791   Accepted: 1631 Descr ...