tcp - 发送大量数据时滞后

标签 tcp lua udp multiplayer love2d

我正在构建一个多人游戏,我的问题是当我发送子弹超过 80 颗时会有延迟。

我使用 UDP 类型,我连接到服务器的代码:

udp = socket.udp()
udp:settimeout(0)
udp:setpeername(address, port)

我的 udp: 将子弹发送到服务器:

udp:send('%S03'..startX..','..startY..','..bulletAngleX..','..bulletAngleY)

服务器:检索子弹并将它们发送回其余客户端:

    elseif code == '%S03' then

        local bulleta = string.gmatch(params, "[^,]+")

        local sX = tonumber(bulleta())
        local sY = tonumber(bulleta())
        local dX = tonumber(bulleta())
        local dY = tonumber(bulleta())


        for i,v in ipairs(clients) do
            udp:sendto('%C01'..math.random(120, 200)..','..sX..','..sY..','..dX..','..dY, v['ip'], tonumber(v['port']))
        end
    end

客户端:获取子弹数据并在表中创建它们:

        elseif code == '%C01' then
        local xy = string.gmatch(re, "[^,]+")
        local dis = tonumber(xy())
        local xStart = tonumber(xy())
        local yStart = tonumber(xy())
        local xAngle = tonumber(xy())
        local yAngle = tonumber(xy())
        table.insert(bullets, {distance = dis, sX = xStart, sY = yStart, x = xStart, y = yStart, dx = xAngle, dy = yAngle})

子弹的 x 和 y 坐标系的更新发生在客户端,当他获得子弹 x、y 并在它们距离第一个位置超过 300 像素时移除子弹。

但是我的问题还是拍的时候有卡顿..

最佳答案

我不太熟悉网络细节,但是很可能您只是发送了太多数据包,并且需要捆绑或以其他方式压缩您发送的数据以减少您发送的 UDP 消息的总数。

来自 this Love2d networking tutorial (也使用 UDP):

It's very easy to completely saturate a network connection if you aren't careful with the packets we send (or request!), so we hedge our chances by limiting how often we send (and request) updates.

(For the record, ten times a second is considered good for most normal games (including many MMOs), and you shouldn't ever really need more than 30 updates a second, even for fast-paced games.)

We could send updates for every little move, but we'll consolidate the last update-worth here into a single packet, drastically reducing our bandwidth use.

如果没有看到您的所有/更多代码,我无法确认这是否是问题所在。但是,每秒多次向每个客户端单独发送每个子弹的数据,带宽使用率可能会变得非常高,最显着的是分别发送每个子弹的数据。

我会先尝试将每个子弹的数据捆绑在一起,然后再将捆绑的数据发送给每个客户端,这将大大减少发送的单个数据包的数量。另外,如果你不是,请确保你没有在 love.update 中发送数据包,它被调用得非常非常频繁。相反,创建一个单独的函数来通过网络进行更新,并使用计时器每 100 毫秒仅调用一次。

让我知道代码中是否已经考虑到这些问题,或者向我们展示您的网络代码的更大上下文。

关于tcp - 发送大量数据时滞后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16813505/

相关文章:

python - Lua 等同于 NumPy 和 SciPy?

api - 如何在Lua中创建表,然后从C API添加值?

lua - 通过引用与 ipairs 循环访问表的性能

c - Linux 上的 UDP 或 TCP 缓冲区大小应该有多大?

c - 协议(protocol)不支持地址族?发给

c - TCP 的不一致实现

c - 如何从popen()函数中读取stdout并将其存储在C语言中的char数组中?

tcp - 通过 TCP Erlang 接收错误数据

tcp - 在 tcp 中,每个连接一个接收缓冲区?或者所有连接共享一个缓冲区?

networking - Erlang:如何设置或检查UDP数据包中的TTL?