Echo server: Difference between revisions
Content added Content deleted
No edit summary |
(Added Lua version) |
||
Line 1,165: | Line 1,165: | ||
"wassup?" |
"wassup?" |
||
</pre> |
</pre> |
||
=={{header|Lua}}== |
|||
{{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 I've used a table of not-quite-non-blocking sockets (they block for one microsecond), which I loop through, checking on whether each one has either a line to echo or an error to warrant deletion. |
|||
<lang Lua>require("socket") |
|||
function checkOn (client) |
|||
local line, err |
|||
line, err = client:receive() |
|||
if line then |
|||
print(tostring(client) .. " said " .. line) |
|||
client:send(line .. "\n") |
|||
end |
|||
if err and err ~= "timeout" then |
|||
print(tostring(client) .. " " .. err) |
|||
client:close() |
|||
return err |
|||
end |
|||
return false |
|||
end |
|||
local delay, clients, newClient = 10^-6, {} |
|||
local server = assert(socket.bind("*", 12321)) |
|||
server:settimeout(delay) |
|||
print("Server started") |
|||
while 1 do |
|||
repeat |
|||
newClient = server:accept() |
|||
for k, v in pairs(clients) do |
|||
if checkOn(v) then table.remove(clients, k) end |
|||
end |
|||
until newClient |
|||
newClient:settimeout(delay) |
|||
print(tostring(newClient) .. " connected") |
|||
table.insert(clients, newClient) |
|||
end</lang> |
|||
=={{header|Nim}}== |
=={{header|Nim}}== |