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. HDU 5695 Gym Class 拓扑排序

    题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=5695 题解: 求出字典序最大的拓扑序.然后把求好的数列翻转过来就是满足条件的数列,然后模拟求一下va ...

  2. 【BZOJ】【1597】【USACO 2008 Mar】土地购买

    DP/斜率优化 Orz Hzwer…… 想到排序了,但没想到其实可以将序列转化为x递增且y递减的序列……因为x是递增的,若y[i]>y[i-1]那么第i-1个就足够小……以至于可以在搞定第 i ...

  3. 编写一函数用来实现左右循环移位。函数原型为move(value,n);n>0时右移n位,n<0时左移|n|位。

    #include<stdio.h> #include<stdlib.h> int main(){ setbuf(stdout,NULL); int move(int,int); ...

  4. Gitlab 7.12 发布 SAML支持及其他更多功能

    官方文章:https://about.gitlab.com/2015/06/22/gitlab-7-12-released/ CSDN翻译文章:http://geek.csdn.net/news/de ...

  5. 深入理解javacript之prototype

    对于javascript这样一种前端语言,个人觉得,要真正的理解其oop, 就必须要彻底搞清楚javascript的对象,原型链,作用域,闭包,以及this所引用的对象等概念.这些对弄明白了,应该就可 ...

  6. IOS-闪光灯操作

    AVCaptureDevice.h主要用来获取iphone一些关于相机设备的属性. 前置和后置摄像头 enum { AVCaptureDevicePositionBack = , AVCaptureD ...

  7. oracle OVER(PARTITION BY) 函数

    OVER(PARTITION BY)函数介绍 开窗函数               Oracle从8.1.6开始提供分析函数,分析函数用于计算基于组的某种聚合值,它和聚合函数的不同之处是:对于每个组返 ...

  8. 高质量图形库:pixellib

    点这里 pixellib 是高质量 2D 图形库: 高质量抗锯齿,矢量图形绘制 多种图像格式: RGB, BGR, ARGB, ABGR, RGBA, BGRA 8 / 15 / 16 / 24 / ...

  9. URAL 1152. False Mirrors (记忆化搜索 状压DP)

    题目链接 题意 : 每一颗子弹破坏了三个邻近的阳台.(第N个阳台是与第1个相邻)射击后后的生存的怪物都对主角造成伤害- 如此,直到所有的怪物被消灭,求怎样射击才能受到最少伤害. 思路 : 状压,数据不 ...

  10. (转)Android之ListView原理学习与优化总结

    转自: http://jishu.zol.com.cn/12893.html 在整理前几篇文章的时候有朋友提出写一下ListView的性能优化方面的东西,这个问题也是小马在面试过程中被别人问到的….. ...