Skip to content

Instantly share code, notes, and snippets.

@arkenidar
Forked from whiler/echo.lua
Last active October 11, 2021 12:56
Show Gist options
  • Save arkenidar/b5efe28ca2988c16d9581ecdcc88a273 to your computer and use it in GitHub Desktop.
Save arkenidar/b5efe28ca2988c16d9581ecdcc88a273 to your computer and use it in GitHub Desktop.
Simple TCP Echo Server in Lua
-- sudo luarocks install luasocket
-- sudo apt install lua-socket
local socket=require("socket")
local server=assert(socket.bind("localhost",9999))
server:settimeout(0) -- for server:accept()
local ip,port=server:getsockname()
print("ncat".." "..ip.." "..port)
local clients={}
while true do -- don't exit
-- new client
local client_new,err=server:accept()
if client_new then
client_new:settimeout(0) -- for client:receive()
table.insert(clients,client_new)
end
-- clients
for i,client in ipairs(clients) do
--print(i.." receive...") -- debug info
local msg=client:receive()
if msg then
--print("received: "..msg) -- debug info
client:send(msg.."\n") -- send back
end
end
end -- end while
server:close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment