我是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个类似的程序,并使用了3个不同的端口(20000、20001和20002)。我希望每个程序互相听,并每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,并且总是会发生此错误。 有解决的办法吗?谢谢