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 ...
随机推荐
- CSS3组件化之单线箭头
<div class="parent-box"> <div class="top-arrow"></div> <div ...
- 基于ONVIF协议的摄像头开发总结
<什么是ONVIF协议> 2008年5月,由安讯士(AXIS)联合博世(BOSCH)及索尼(SONY)公司三方宣布携手共同成立一个国际开放型网络视频产品标准网络接口开发论坛,取名为 ...
- CentOS7.4 关闭firewall防火墙,改用iptables
1.关闭默认的firewall防火墙 systemctl stop firewalld.service #停止firewall systemctl disable firewalld.service ...
- BZOJ.2460.[BeiJing2011]元素(线性基 贪心)
题目链接 线性基:https://blog.csdn.net/qq_36056315/article/details/79819714. \(Description\) 求一组矿石,满足其下标异或和不 ...
- python日常碎碎念
关于取命令行中参数的方法 1,sys.argv 这个方法自动获取参数,并split.一般情况下第一个元素是程序的名字.即 python script.py arg1 arg2 然后sys.argv返回 ...
- 移动web开发经验总结(1)
1.<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, minimum-sca ...
- js解析顺序了解一下??
我们在学习一种新事物的时候,总是知其然,而不知其所然.有些人会探究到底,有一些人会得过且过. 好了,开场白结束,直接进入正题. js不像C语言那样只要编译一次之后成.exe文件之后就不用在编译可以直接 ...
- php 获取开始日期与结束日期之间所有日期
话不多说,源码奉上! function getDateRange($startdate, $enddate) { $stime = strtotime($startdate); $etime = st ...
- Syncovery 是目前功能最为强大的实时自动备份工具
Syncovery Pro(原名叫做Super Flexible Synchronizer) 是目前功能最为强大的实时自动备份工具,连FTP.WebDAV等全部支持! 最近从V6开始改用比较好记.易懂 ...
- 完整的POM文档内容
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/20 ...