Lua 中避免低效解析 TCP 网络数据包体的一种方式(续)

Stella981
• 阅读 534

上一篇避免通过拼接字符串作为接收数据的缓冲区,解决办法是通过一个 Lua 模块来获取接收后的完整数据,若没有完整数据则读取 socket ,若还没有完整数据则 sleep 一小会儿,然后再尝试。 了解过 Lua 或用过 skynet 可知,使用 coroutine 可以实现 sock:read(1000) 这种同步的写法但实际是异步的方式读取 1000 字节数据,当网络连接正常时,函数 read 只有在接收了指定字节数后的数据后才会返回。这里不讨论如何在等待网络数据到达时使当前的 coroutine 让出执行,而在 socket 读取到数据后再将此 coroutine 唤醒。这里讨论如何在 Lua 中实现一个相对高效的数据缓冲区,通过 local bytes = sock:read(2); local data = sock:read(bytes) 这种方式解包,获取接收到的完整数据。这种方式和前面一种方式的不同点在于不需要调用 sleep ,接收到完整的数据后就返回。完整的代码在这里

先列出通过字符串拼接的方式实现的接收数据缓冲区。每次收到数据后则拼接,产生新的字符串。然后再根据字节数返回相应的子串。

local setmetatable = setmetatable

local mt = {}
mt.__index = mt

function mt:init()
    self.cache = ""
end

function mt:input(str)
    self.cache = self.cache .. str
end

function mt:output(num_bytes)
    local cache = self.cache
    if #cache < num_bytes then
        return
    end

    local data = cache:sub(1, num_bytes)
    self.cache = cache:sub(num_bytes + 1)

    return data
end

local function _new(...)
    local obj = setmetatable({}, mt)
    obj:init(...)
    return obj
end

return _new

下面是不拼接字符串实现的接收数据缓冲区。由于高频的拼接字符串是很耗时的操作,这里的核心想法就是避免这种情况。每次接收到数据后将数据缓存在 Lua 数组中,然后根据字节数拼接产生字符串。

local setmetatable = setmetatable
local table = table

local mt = {}
mt.__index = mt

function mt:init()
    self.str_blocks = {}
    self.total_bytes = 0
end

function mt:input(str)
    table.insert(self.str_blocks, str)
    self.total_bytes = self.total_bytes + #str
end

function mt:output(num_bytes)
    if self.total_bytes < num_bytes then
        return
    end

    local blocks = self.str_blocks
    local num = #blocks

    local index
    local stat_bytes = 0
    for i, block in ipairs(blocks) do
        index = i
        stat_bytes = stat_bytes + #block
        if stat_bytes >= num_bytes then
            break
        end
    end

    local str = table.concat(blocks, "", 1, index)
    local data = str:sub(1, num_bytes)
    local left_num = num - index

    local new_blocks = {}
    if stat_bytes > num_bytes then
        new_blocks[#new_blocks + 1] = str:sub(num_bytes + 1)
    end
    if left_num > 0 then
        table.move(blocks, index + 1, num, #new_blocks + 1, new_blocks)
    end

    self.str_blocks = new_blocks
    self.total_bytes = self.total_bytes - num_bytes
    return data
end

local function _new(...)
    local obj = setmetatable({}, mt)
    obj:init(...)
    return obj
end

return _new

下面是测试的代码。在我的机器上,优化前需要花几十秒的时间,优化后不到 200 毫秒运行完毕。

local ipairs = ipairs
local assert = assert
local os = os
local string = string

local p1_func = require "string1"
local p2_func = require "string2"

local p1 = p1_func(2)
local p2 = p2_func(2)

local function test(obj)
    local raw = {}
    local list = {}
    local total = 0
    local max = 64 * 1024
    for i = 1, max, 32 do
        total = total + i
        local s = string.rep("A", i)
        raw[#raw + 1] = s
        list[#list + 1] = string.pack(">s2", s)
    end

    for _, str in ipairs(list) do
        obj:input(str)
    end

    local start = os.clock()
    local ret = {}
    for _, str in ipairs(raw) do
        local data = obj:output(2)
        local n = string.unpack(">I2", data)
        assert(n == #str)
        ret[#ret + 1] = obj:output(n)
    end
    print(os.clock() - start)

    assert(#raw == #ret, #raw .. " vs " .. #ret)
    for i = 1, #raw do
        assert(raw[i] == ret[i])
    end
end

local new = ...
test(new and p2 or p1)

由于项目中用到的工具对性能有些要求,但又没有那么高的要求,所以就还是想在 Lua 层面解决问题。目前看来,应该是满足需求了。

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Wesley13 Wesley13
2年前
java将前端的json数组字符串转换为列表
记录下在前端通过ajax提交了一个json数组的字符串,在后端如何转换为列表。前端数据转化与请求varcontracts{id:'1',name:'yanggb合同1'},{id:'2',name:'yanggb合同2'},{id:'3',name:'yang
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
为什么mysql不推荐使用雪花ID作为主键
作者:毛辰飞背景在mysql中设计表的时候,mysql官方推荐不要使用uuid或者不连续不重复的雪花id(long形且唯一),而是推荐连续自增的主键id,官方的推荐是auto_increment,那么为什么不建议采用uuid,使用uuid究
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这