V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
finian
V2EX  ›  程序员

设计 JSON over TCP 协议

  •  
  •   finian · 2014-03-22 10:01:20 +08:00 · 4427 次点击
    这是一个创建于 3687 天前的主题,其中的信息可能已经有所发展或是发生改变。
    想整个简单的 JSON over TCP server,message framing(JSON framing)怎么设计比较好?用什么符号来作为payload之间的delimiter?怎么校验payload的完整性?
    9 条回复    1970-01-01 08:00:00 +08:00
    9hills
        1
    9hills  
       2014-03-22 10:13:35 +08:00   ❤️ 1
    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
        2
    9hills  
       2014-03-22 10:14:27 +08:00
    其实就是包头,包长,包体。。都大同小异,没啥区别
    finian
        3
    finian  
    OP
       2014-03-22 10:19:05 +08:00
    @9hills 谢,我也Google到了那个lib,不过看他最后更新在11个月之前,而且start数比较少,所以觉得可能不是那么靠谱,我还是先看看他的代码是怎么实现的
    notedit
        4
    notedit  
       2014-03-22 10:43:04 +08:00
    把json数据封装成memcache的get set
    rankjie
        5
    rankjie  
       2014-03-22 11:03:15 +08:00 via iPhone
    非常简短的json我就是stringify了再parse
    lol
    zhujinliang
        6
    zhujinliang  
       2014-03-22 11:31:26 +08:00
    websocket套json,协议不复杂,也有独立的C语言实现,各种语言几乎都有库。另外向上nginx能支持,可提供一些反向/权限控制等辅助,向下浏览器支持,可以方便地进行调试
    9hills
        7
    9hills  
       2014-03-22 11:45:40 +08:00   ❤️ 1
    @finian 你可以参考它的协议,因为json本身就能封装,所以外部协议简单的多。

    也可以换Protobuf/Thift之类的来做,比较成熟。JSON本身是string,体积太大
    taomaree
        8
    taomaree  
       2014-03-22 16:39:22 +08:00
    clino
        9
    clino  
       2014-03-22 20:50:22 +08:00
    我自己刚好在考虑类似的问题,也想用json来做
    目前的一个想法是每个json都只用一行,这样socket当作file来readline就可以取到每个json信息了
    至于"怎么校验payload的完整性",只要json能load格式正确就行了,再不放心就加个校验信息好了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5396 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 08:35 · PVG 16:35 · LAX 01:35 · JFK 04:35
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.