我是 Lua 新手,并尝试使用luasocket和copas在 Openwrt 中实现 TCP 服务器和客户端。目标是使 3 个程序在异步网络中通过套接字相互通信。
下面是脚本
local copas = require("copas")
local socket = require("socket")
local host = "localhost"
local port = 20000
local hostcl1 = "localhost"
local portcl1 = 20001
local hostcl2 = "localhost"
local portcl2 = 20002
local function echoHandler(skt)
skt = copas.wrap(skt)
while true do
local data = skt:receive()
print("data received:", data, "from:", skt:getsockname())
if not data or data == nil then
break
end
end
end
local function sendToNeighbor(host, port, data)
skt = socket.connect(host, port)
if (skt ~= nil) then
skt = copas.wrap(skt)
print("client connected to " ..host.. ":" ..port.. "...")
copas.send(skt, data.."\n")
print("data sent")
skt:close()
print("Closed!")
else
print("client failed to send to " ..host.. ":" ..port.. "...")
end
end
local server = socket.bind(host, port)
copas.addserver(server, echoHandler, 0)
SendInterval = 10
SecBefore = os.date('%S')
SecSend = (SecBefore + SendInterval)%60
while true do
copas.step(0)
local Sec = os.date('%S')
if ( tonumber(Sec) == SecSend ) then
dataToClient1 = "Test1"
dataToClient2 = "Test2"
sendToNeighbor(hostcl1, portcl1, dataToClient1)
sendToNeighbor(hostcl2, portcl2, dataToClient2)
SecBefore = Sec
SecSend = (SecBefore + SendInterval)%60
end
end
在上面的脚本中,我在 host = "localhost" 和 3 个不同的端口(20000、20001 和 20002)中使用了 3 个类似的程序。我希望每个程序互相监听,每 10 秒互相发送一次数据。问题是程序每次用 copas.send 函数发送数据时,都会出现这个错误。
luajit: /usr/local/share/lua/5.1/copas.lua:285: attempt to yield across C-call boundary
我曾尝试使用 lua 5.1、lua 5.1 + CoCo 和 LuaJIT,但总是会出现此错误。有什么办法解决这个问题吗?谢谢