Echo server: Difference between revisions

→‎{{header|Lua}}: Added a non-blocking, non-busy implementation.
(→‎{{header|Lua}}: I fixed error with require("socket"); made code more clear.)
(→‎{{header|Lua}}: Added a non-blocking, non-busy implementation.)
Line 1,528:
{{works with|Lua|5.3}}
{{libheader|LuaSocket}}
 
This implementation doesn't rely on coroutines because they're an additional (often confusing) notion that could make the example needlessly hard to understand. Instead it uses a table of not-quite-non-blocking socket client objects (they block for 4 milliseconds), which is iterated over to check on whether each one has either a line to echo or an error to warrant deletion.
<lang Lua>local socket = require("socket")
 
local function has_value(tab, value)
for i, v in ipairs(tab) do
if v == value then return i end
end
return false
end
 
local function checkOn(client)
local line, err = client:receive()
if line then
client:send(line .. "\n")
end
if err and err ~= "timeout" then
print(tostring(client) .. " " .. err)
client:close()
return true -- end this connection
end
return false -- do not end this connection
end
 
local server = assert(socket.bind("*",12321))
server:settimeout(0) -- make non-blocking
local connections = { } -- a list of the client connections
while true do
local newClient = server:accept()
if newClient then
newClient:settimeout(0) -- make non-blocking
table.insert(connections, newClient)
end
local readList = socket.select({server, table.unpack(connections)})
for _, conn in ipairs(readList) do
if conn ~= server and checkOn(conn) then
table.remove(connections, has_value(connections, conn))
end
end
end</lang>
----
ThisThe following implementation doesn'tuses relytiny ondelays coroutines because they're anrather additionalthan (often confusing) notion that could make the example needlessly hard to understandsocket.select. Instead itIt uses a table of not-quite-non-blocking socket client objects (they block for 4 milliseconds), which is iterated over to check on whether each one has either a line to echo or an error to warrant deletion. Without the millisecond delays, the whole thing would become one 'hot' loop and eat all the CPU time for one core. With them, it uses close to zero percent.
<lang Lua>local socket=require("socket")
 
Line 1,561 ⟶ 1,601:
table.insert(connections, newClient)
end</lang>
Without the millisecond delays, the whole thing would become one 'hot' loop and eat all the CPU time for one core. With them, it uses close to zero percent.
 
=={{header|Nim}}==
27

edits