luasocket/samples/tinyirc.lua

90 lines
2.6 KiB
Lua
Raw Normal View History

-----------------------------------------------------------------------------
-- Select sample: simple text line server
-- LuaSocket sample files.
-- Author: Diego Nehab
-----------------------------------------------------------------------------
2004-06-20 23:07:58 -07:00
local socket = require("socket")
2001-03-12 11:42:46 -08:00
host = host or "*"
port1 = port1 or 8080
2003-06-29 23:10:02 -07:00
port2 = port2 or 8181
2001-03-12 11:42:46 -08:00
if arg then
host = arg[1] or host
port1 = arg[2] or port1
port2 = arg[3] or port2
end
2005-01-02 14:44:00 -08:00
server1 = assert(socket.bind(host, port1))
server2 = assert(socket.bind(host, port2))
server1:settimeout(1) -- make sure we don't block in accept
2004-05-30 14:36:22 -07:00
server2:settimeout(1)
2001-03-12 11:42:46 -08:00
2003-06-29 23:10:02 -07:00
io.write("Servers bound\n")
-- simple set implementation
-- the select function doesn't care about what is passed to it as long as
-- it behaves like a table
2005-04-20 20:15:34 -07:00
-- creates a new set data structure
function newset()
local reverse = {}
local set = {}
2005-04-20 20:15:34 -07:00
return setmetatable(set, {__index = {
insert = function(set, value)
if not reverse[value] then
table.insert(set, value)
reverse[value] = #set
2005-04-20 20:15:34 -07:00
end
end,
remove = function(set, value)
2005-04-20 20:15:34 -07:00
local index = reverse[value]
if index then
reverse[value] = nil
local top = table.remove(set)
if top ~= value then
reverse[top] = index
set[index] = top
end
end
end
}})
end
2003-06-29 23:10:02 -07:00
set = newset()
2002-07-08 13:56:36 -07:00
2003-06-29 23:10:02 -07:00
io.write("Inserting servers in set\n")
set:insert(server1)
set:insert(server2)
2001-03-12 11:42:46 -08:00
while 1 do
2003-06-29 23:10:02 -07:00
local readable, _, error = socket.select(set, nil)
2004-05-30 14:36:22 -07:00
for _, input in ipairs(readable) do
-- is it a server socket?
if input == server1 or input == server2 then
2003-06-29 23:10:02 -07:00
io.write("Waiting for clients\n")
local new = input:accept()
if new then
new:settimeout(1)
2003-06-29 23:10:02 -07:00
io.write("Inserting client in set\n")
set:insert(new)
2001-03-12 11:42:46 -08:00
end
2002-07-08 13:56:36 -07:00
-- it is a client socket
2001-03-12 11:42:46 -08:00
else
local line, error = input:receive()
if error then
input:close()
2003-06-29 23:10:02 -07:00
io.write("Removing client from set\n")
set:remove(input)
2001-03-12 11:42:46 -08:00
else
2003-06-29 23:10:02 -07:00
io.write("Broadcasting line '", line, "'\n")
2004-05-30 14:36:22 -07:00
writable, error = socket.skip(1, socket.select(nil, set, 1))
2002-07-08 13:56:36 -07:00
if not error then
2004-05-30 14:36:22 -07:00
for __, output in ipairs(writable) do
if output ~= input then
2004-05-30 14:36:22 -07:00
output:send(line .. "\n")
end
end
2003-06-29 23:10:02 -07:00
else io.write("No client ready to receive!!!\n") end
end
2001-03-12 11:42:46 -08:00
end
end
end