Echo server: Difference between revisions

→‎{{header|Lua}}: I fixed error with require("socket"); made code more clear.
m (Write a message when a connection is accepted.)
(→‎{{header|Lua}}: I fixed error with require("socket"); made code more clear.)
Line 1,526:
 
=={{header|Lua}}==
{{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 one4 microsecondmilliseconds), 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")
 
function checkOn (client)
Line 1,539 ⟶ 1,540:
print(tostring(client) .. " " .. err)
client:close()
return errtrue -- end this connection
end
return nilfalse -- do not end this connection
end
 
local delay, clients,= newClient0.004 = 10^-6,- anything less than this uses up my {}CPU
local connections = {} -- an array of connections
local newClient
local server = assert(socket.bind("*", 12321))
server:settimeout(delay)
while 1true do
print("Server started")
while 1 do
repeat
newClient = server:accept()
for kidx, vclient in pairsipairs(clientsconnections) do
if checkOn(vclient) then table.remove(clientsconnections, kidx) end
end
until newClient
newClient:settimeout(delay)
print(tostring(newClient) .. " connected")
table.insert(clientsconnections, newClient)
end</lang>
Without the microsecondmillisecond 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