【旧博客迁移】使用lua表设计简单RPC协议

协议设计

   p = {
       name = "hanxi",
       tel = 1383838,
       addresslist = {
           address = "gz",
           addtype = "work",
       },
   }

p 是定义一个协议格式,其中,addresslist是array类型,定义的内容表示array的元素的格式。协议的实际内容格式如下:

  p = {
      name = "hanxi",
      tel = 1383838,
      addresslist = {
          {
              address = "gz",
              addtype = "work",
          },
          { 
              address = "jj",
              addtype = "home", 
          },
  }

协议打包

p = {
      _keysort = {"addresslist","name","tel"},
      name = "hanxi",
      tel = 1383838,
      addresslist = {
          _keysort = {"addtype","address"},
          address = "gz",
          addtype = "work",
      },
}

协议解包

实现

在c中提供接口:

    luaL_Reg l[] ={
        { "packinit", lpackinit },
        { "write", lwrite },
        { "getpack", lgetpack },
        { "unpackinit", lunpackinit },
        { "read", lread },
        { NULL, NULL },
    };

packinit, write, getpack三个函数用于打包协议

unpackinit, read 两个函数用于解包协议

全部代码: https://github.com/hanxi/lproto

点击进入评论 ...