Created
June 28, 2013 22:25
-
-
Save d33tah/5888643 to your computer and use it in GitHub Desktop.
A sketch of a chat service implemented in Lua.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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") | |
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
i can't use this on ncat version 6.40
how to use this?!