lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hello, I didn't stumble on a good example code, so I'm checking that
way, as far I understood the luasocket documentation.
This code wants to receive whole line and send arbitrary data in
nonblocking mode. I just want to ask, since in normal operation
this things are harder to test, as the buffers are usually
written/read in one sweep.

(Suppose socket is opened and set to nonblock via socket:settimeout(0))

-- This function is called by select when ready to read.
local rBuf = ""
local function canRead(socket)
    local l, err, rBuf = socket:receive("*l", rBuf)
    if not l then
        if err ~= "timeout" then
            print("connection failed: ", err)
            os.exit(-1)
        end
    else
        rBuf = ""
    end
    print("Received Line:" l)
end

(Is that a correct way of doing it?)
And for writing I came up with this:
Function gets also called with no arguments if the buffer is non empty
and the socket
selected for being writeable.

local wBuf = ""
function write(...)
    wBuf = wBuf..table.concat({...})
    local s, err = socket:send(wBuf)
    if not s and err~="timeout" then
        print("connection failed: ", err)
        os.exit(-1)
    end
    wBuf = wBuf:sub(s + 1, -1)
end