can someone share a code for non-blocking tcp client read?
The trick is to set connection timeout to 0 to make the socket non-blocking. Here’s an example based on another project I have. The code is modified and not tested. The basic idea is to wrap reading of data from the socket in a coroutine and set the socket timeout to 0 so that the socket doesn’t block. Modify this code to fit your specific use-case.
local socket_co = nil
--- Try to receive data on a socket.
-- This function assumes that it is called from within a coroutine. Each
-- time the coroutine is resumed this function will try receive data. It
-- will attempt this until a timeout or an error occurs or data is received.
-- @param conn The socket connection to receive data on
-- @return response
-- @return error_message
local function non_blocking_receive(conn)
local response
local error_message
conn:settimeout(0)
while (err == "timeout") or (error_message == nil and (response == nil or response == "")) do
response, error_message = conn:receive()
coroutine.yield()
end
conn:settimeout(nil)
return response, error_message
end
--- Create a socket connection, accept incoming connections and read received
-- data until the connection is closed or an error occurs
local function start_receiving()
socket_co = coroutine.create(function()
local host = "www.my_host.com"
local port = 12345
local sock = assert(socket.bind(host, port))
local conn = assert(sock:accept())
while true do
local response, error_message = non_blocking_receive(conn)
if error_message then
break
end
-- do stuff with response
end
end)
coroutine.resume(self.co)
end
function update(self, dt)
if coroutine.status(self.socket_co) == "suspended" then
coroutine.resume(self.socket_co)
end
end