Design Your Own Protocol In Five Minutes
https://mayaposch.wordpress.com/2011/10/03/design-your-own-protocol-in-five-minutes
-----------------------------------------
Among the most scary and official sounding terms in computing we find the word ‘protocol’. Its meaning really isn’t that scary, however. Just like when used in other contexts, all it means is a collection of agreements about how to go about something. In this case we’re talking about communication protocols, protocols which allow two or more devices and/or applications to communicate with each other.
Much like how humans have developed their own communication protocols, basically. We also do a handshake part during which we initialize the connection, whether it’s by smiling at each other, remarking on the beautiful/terrible weather or asking after something specific, depending on whether there was previous contact or not. Possible failure modes include getting ignored (Server Time-out), getting slapped in the face after a failed pick-up line (Connection Closed By Host) or interrupted by the girl’s muscular boyfriend (Connection Reset By Peer), as well as addressing the wrong person (Connection Denied).
After successfully establishing the connection, information is exchanged. For humans both during handshake and communication the form used for information exchange is a so-called language, a rather organic and informal set of syllables which when put into the right order (‘spelling’ and ‘grammar’) can be used to evoke understanding in the receiving party. To even get to this level, humans needed tens of thousands of years to evolve a series of grunts and other random noises into something coherent. Suffice it to say that human communication protocols are elaborate, imprecise, filled with misunderstandings and are a clear example of how not to design a communication protocol Finally, ending the connection. Again, for humans this can take many forms, generally fails to result in a clean termination and can add many more minutes to a connection. Aren’t we glad now that we are designing a communication protocol for computers?
All joking aside, designing a communication protocol is fairly easy. The first choice we have to make is whether we want the protocol to be binary or text-based. Text-based protocols include the HTTP protocol, which is what we use to browse webpages with. Main benefit of it is that it’s easy for humans to write it out and debug it. Main disadvantage is that it’s less precise and exact in that generally you can’t parse it in one go, can’t instantly verify that it is valid as a whole and using the wrong text encoding can mess things up quite badly. You’ll quickly find that it’s a cumbersome and error-prone way to go about a communication protocol. It’s no wonder that they’re fairly rarely used, mostly with network applications for some reason.
Text-based protocols have the benefit of not being affected by endianness [1], which is the byte order used by a particular system. Little endian is what Intel and AMD processors use and mean that the least important (little) bits are placed at the front of a byte, while big endian is the opposite. This means that if we take the number 14 (hexidecimal 0x0E), in little endian a resulting four-byte integer looks like this: 0E 00 00 00, whereas with big endian it looks like: 00 00 00 0E. Confusing little endian with big or the other way around will lead to interpreting the number wrongly and making our small number of 14 into a much larger number of 917,504. Oops.
To solve this problem with binary protocols which might be used in mixed endian environments, we add a magic number to the front of the header, usually two bytes with known values. By reading those we know which endianness the data is in. One example is using ‘MM’ like in TIFF file headers to indicate big endian (MSB) and ‘ll’ to indicate little endian (LSB) byte order. We can then enter a different parsing routine, or swap the byte order while parsing.
Writing out the protocol itself is a fairly easy and in my experience fun task, but I may just be a tad crazy. It is made easiest when you know what the requirements for the protocol are, but in general we start with the endianness indicator if needed, then one or more indicators identifying the header as being what is expected. I generally use the name of my company followed by the protocol name. After that the data follows. Sections within the data have their own text headers to detect corruption. Where offsets aren’t fixed such as with text strings, an unsigned integer precedes the data to indicate the length of the segment.
The basic protocol thus looks like follows:
1
2
3
4
5
|
ll/MM uint8(2) size uint32 NYANKO uint8(6) UDS uint8(3) command uint8(4) |
To send a UDS protocol ‘LIST’ command to the server, we would use the following code, this one using a QByteArray:
1
2
3
4
5
6
7
8
9
|
QByteArray data; data = "ll" ; quint32 size = 19; for ( int i = sizeof (size); i > 0 ; --i) { data.append((size >> (i * 8)) & 0xFF); } data += "NYANKOUDS" ; data += "LIST" ; |
Did I mention yet that bitwise operators are important? When dealing with low-level interactions such as communication protocols, they are invaluable and one’d do well to study them. Finally, I’d like to comment on the ‘size’ variable used. With network protocols it’s hard for the receiving socket to know when the end of the data has been reached. Putting the size of the whole data at the front of the header like this allows it to know exactly how much data still has to be received, when the data end has been reached and when a download is incomplete.
Parsing the protocol is essentially the opposite of putting it together. It’s done in a linear fashion, with checks for every value read. If done right it’s very robust and quite fool-proof.
Anyway, these are the basics of putting a communication protocol together. It’s very easy, absolutely not scary and even pretty fun Go give it a try some time.
Design Your Own Protocol In Five Minutes的更多相关文章
- WCF WS-Security and WSE Nonce Authentication【转】
原文:http://weblog.west-wind.com/posts/2012/Nov/24/WCF-WSSecurity-and-WSE-Nonce-Authentication?utm_sou ...
- Verification of WISHBONE I2C Master Core(IRUN+Simvision)
一.前言 很久没写技术博客了,有些懈怠,生活还得继续折腾.转眼工作一年多,时间越长越发觉得自己知之甚少,当然这跟IC行业技术密集有关.用空余时间在opencores网站上下载些小的IP看看 验证下,让 ...
- [源码解析] PyTorch 分布式 Autograd (5) ---- 引擎(上)
[源码解析] PyTorch 分布式 Autograd (5) ---- 引擎(上) 目录 [源码解析] PyTorch 分布式 Autograd (5) ---- 引擎(上) 0x00 摘要 0x0 ...
- [源码解析] PyTorch 分布式 Autograd (6) ---- 引擎(下)
[源码解析] PyTtorch 分布式 Autograd (6) ---- 引擎(下) 目录 [源码解析] PyTtorch 分布式 Autograd (6) ---- 引擎(下) 0x00 摘要 0 ...
- Serial Communication Protocol Design Hints And Reference
前面转载的几篇文章详细介绍了UART.RS-232和RS-485的相关内容,可以知道,串口通信的双方在硬件层面需要约定如波特率.数据位.校验位和停止位等属性,才可以正常收发数据.实际项目中使用串口通信 ...
- Latency Compensating Methods in Client/Server In-game Protocol Design and Optimization【转】
https://developer.valvesoftware.com/wiki/Latency_Compensating_Methods_in_Client/Server_In-game_Proto ...
- How the Bitcoin protocol actually works
sklearn实战-乳腺癌细胞数据挖掘(博客主亲自录制视频教程) https://study.163.com/course/introduction.htm?courseId=1005269003&a ...
- Hessian 2.0 序列化协议 - Hessian 2.0 Serialization Protocol 翻译
Hessian是一种轻量.快速的web协议,在微服务场景下经常被使用. Hessian协议实际上包含两种含义: 1. Web网络通信远程调用服务,具体可以参考:http://hessian.cauch ...
- Web API design
Web API design 28 minutes to read Most modern web applications expose APIs that clients can use to i ...
随机推荐
- Standard NSD file
%pool: pool=system blockSize=256K layoutMap=cluster allowWriteAffinity=no %pool: pool=datapool block ...
- 第一个ASP.NET MVC应用程序
首先打开vs2015 文件->新建->项目 选择模版选empty,下面[为下项添加文件夹和核心引用]勾选mvc 点击确定就好
- CI Weekly #15 | 据说新版 flow.ci Dashboard 界面很酷
好久不见 :) 最近工程师们卯足了劲,全新的 flow.ci dashboard 页面 已经与所有用户见面了.更快捷地创建项目,构建列表页面新增分支,Pull Request 界面:侧边栏新增构建任务 ...
- 自顶向下学搜索引擎——北大天网搜索引擎TSE分析及完全注释[1]寻找搜索引擎入口
转自:http://blog.csdn.net/jrckkyy/article/category/402818 由于百度博客http://hi.baidu.com/jrckkyy发表文章字数有限,以后 ...
- java多线程技术之条件变量
上一篇讲述了并发包下的Lock,Lock可以更好的解决线程同步问题,使之更面向对象,并且ReadWriteLock在处理同步时更强大,那么同样,线程间仅仅互斥是不够的,还需要通信,本篇的内容是基于上篇 ...
- 重庆市队选拔 CQOI2015 解题报告
文章链接:http://www.cnblogs.com/Asm-Definer/p/4434601.html 题目链接:http://pan.baidu.com/s/1mgxIKli 官方数据:htt ...
- Linux下nmon工具安装及nmon analyser的使用
步骤一:下载nmon及nmon analyser工具 nmon:http://nmon.sourceforge.net/pmwiki.php 根据自己系统的版本下载相应的版本即可 nmon analy ...
- centos7安装maven
下载maven 下载地址:http://mirrors.tuna.tsinghua.edu.cn/apache/maven/maven-3/3.3.9/binaries/apache-maven-3. ...
- Google的Shell开发规范
官方:https://google.github.io/styleguide/shell.xml 中文: http://zh-google-styleguide.readthedocs.io/en/l ...
- hdu1238 Substrings (暴力)
http://acm.hdu.edu.cn/showproblem.php?pid=1238 Substrings Time Limit : 2000/1000ms (Java/Other) Me ...