2

I'm new to Lua and trying to implement TCP server and client in Openwrt using luasocket and copas. The goal is to make 3 program communicate with each other via socket in asynchronous networking.

Below is the script

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

On script above, I use 3 similar program in host = "localhost" and 3 different port (20000, 20001, and 20002). I want each program listen to each other and send each other data every 10 seconds. The problem is every time the program send data with copas.send function, this error occurs.

luajit: /usr/local/share/lua/5.1/copas.lua:285: attempt to yield across C-call boundary

I have try using lua 5.1, lua 5.1 + CoCo, and LuaJIT and this error always occur. Any idea to solve this? thanks

mffathurr
  • 21
  • 1

0 Answers0