设计 JSON over TCP 协议

2014-03-22 10:01:20 +08:00
 finian
想整个简单的 JSON over TCP server,message framing(JSON framing)怎么设计比较好?用什么符号来作为payload之间的delimiter?怎么校验payload的完整性?
4431 次点击
所在节点    程序员
9 条回复
9hills
2014-03-22 10:13:35 +08:00
Google 到有现成的 https://www.npmjs.org/package/json-over-tcp
Protocol

If you would like to implement the protocol yourself, the server will expect the following in order in the byte stream:

16-bit unsigned little-endian integer with 206 as the value. This is the protocol signature, if a message is sent without this signature a protocol error will be raised.
A 32-bit unsigned little-endian integer with the length of the message being sent as the value.
A UTF-8 string with the stringified JSON as the value (the message).

校验没必要,TCP保证通信完整性,自带校验

更低层才要校验,比如以前设计的串口通信协议,这种不可靠环境才需要自己做校验
9hills
2014-03-22 10:14:27 +08:00
其实就是包头,包长,包体。。都大同小异,没啥区别
finian
2014-03-22 10:19:05 +08:00
@9hills 谢,我也Google到了那个lib,不过看他最后更新在11个月之前,而且start数比较少,所以觉得可能不是那么靠谱,我还是先看看他的代码是怎么实现的
notedit
2014-03-22 10:43:04 +08:00
把json数据封装成memcache的get set
rankjie
2014-03-22 11:03:15 +08:00
非常简短的json我就是stringify了再parse
lol
zhujinliang
2014-03-22 11:31:26 +08:00
websocket套json,协议不复杂,也有独立的C语言实现,各种语言几乎都有库。另外向上nginx能支持,可提供一些反向/权限控制等辅助,向下浏览器支持,可以方便地进行调试
9hills
2014-03-22 11:45:40 +08:00
@finian 你可以参考它的协议,因为json本身就能封装,所以外部协议简单的多。

也可以换Protobuf/Thift之类的来做,比较成熟。JSON本身是string,体积太大
taomaree
2014-03-22 16:39:22 +08:00
clino
2014-03-22 20:50:22 +08:00
我自己刚好在考虑类似的问题,也想用json来做
目前的一个想法是每个json都只用一行,这样socket当作file来readline就可以取到每个json信息了
至于"怎么校验payload的完整性",只要json能load格式正确就行了,再不放心就加个校验信息好了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/105374

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX