Skip to content

Instantly share code, notes, and snippets.

@d33tah
Created June 28, 2013 22:25
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d33tah/5888643 to your computer and use it in GitHub Desktop.
Save d33tah/5888643 to your computer and use it in GitHub Desktop.
A sketch of a chat service implemented in Lua.
#!/usr/bin/lua
peers = {}
peer_names = {}
reverse_peers = {}
function on_connect(sock)
local idx = #peers+1
local newname = string.format("Peer%d", idx)
peers[idx] = sock
peer_names[idx] = newname
reverse_peers[sock] = idx
broadcast(string.format("%s joined the channel\n",newname), sock)
end
function on_readline(sock, line)
local num = reverse_peers[sock]
if string.sub(line,1,6)=="/name " then
local newname = string.sub(line, 7, #line)
broadcast(string.format("%s changed his name to %s\n", peer_names[num], newname), nil)
peer_names[num] = newname
else
broadcast(string.format("<%s> %s\n", peer_names[num], line), sock)
end
end
function broadcast(data, exclude)
for num=1, #peers do
sock = peers[num]
if sock ~= exclude then
sock:write(data)
sock:flush()
end
end
end
function main_loop()
while true do
if ncat.socket_waiting() then
on_connect(ncat.accept())
end
--read line loop
for num=1, #peers do
sock = peers[num]
if ncat.has_line(sock) then
on_readline(sock, sock:read("*line"))
end
end
end
end
on_connect(io.stdout)
on_connect(io.stderr)
on_readline(io.stdout, "Hai")
on_readline(io.stdout, "/name ziomek")
on_readline(io.stdout, "test")
@saturn99
Copy link

i can't use this on ncat version 6.40
how to use this?!

@GlasFrost
Copy link

So this script is able to handle io.stdin, io.stdout and io.stderr. But it doesn't work with the ncat sockets even after some playing around. How do I get on_connect() to work with network connections? That seems to be the main issue for me.
Besides, the script seems to be run per user logging in and doesn't seem to be able to handle multiple users at once.
(Ncat Version 6.40 on a Ubuntu machine)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment