comparison samples/tinyirc.lua @ 0:4b915342e2a8

LuaSocket 2.0.2 + CMake build description.
author Eric Wing <ewing . public |-at-| gmail . com>
date Tue, 26 Aug 2008 18:40:01 -0700
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:4b915342e2a8
1 -----------------------------------------------------------------------------
2 -- Select sample: simple text line server
3 -- LuaSocket sample files.
4 -- Author: Diego Nehab
5 -- RCS ID: $Id: tinyirc.lua,v 1.14 2005/11/22 08:33:29 diego Exp $
6 -----------------------------------------------------------------------------
7 local socket = require("socket")
8 host = host or "*"
9 port1 = port1 or 8080
10 port2 = port2 or 8181
11 if arg then
12 host = arg[1] or host
13 port1 = arg[2] or port1
14 port2 = arg[3] or port2
15 end
16
17 server1 = assert(socket.bind(host, port1))
18 server2 = assert(socket.bind(host, port2))
19 server1:settimeout(1) -- make sure we don't block in accept
20 server2:settimeout(1)
21
22 io.write("Servers bound\n")
23
24 -- simple set implementation
25 -- the select function doesn't care about what is passed to it as long as
26 -- it behaves like a table
27 -- creates a new set data structure
28 function newset()
29 local reverse = {}
30 local set = {}
31 return setmetatable(set, {__index = {
32 insert = function(set, value)
33 if not reverse[value] then
34 table.insert(set, value)
35 reverse[value] = table.getn(set)
36 end
37 end,
38 remove = function(set, value)
39 local index = reverse[value]
40 if index then
41 reverse[value] = nil
42 local top = table.remove(set)
43 if top ~= value then
44 reverse[top] = index
45 set[index] = top
46 end
47 end
48 end
49 }})
50 end
51
52 set = newset()
53
54 io.write("Inserting servers in set\n")
55 set:insert(server1)
56 set:insert(server2)
57
58 while 1 do
59 local readable, _, error = socket.select(set, nil)
60 for _, input in ipairs(readable) do
61 -- is it a server socket?
62 if input == server1 or input == server2 then
63 io.write("Waiting for clients\n")
64 local new = input:accept()
65 if new then
66 new:settimeout(1)
67 io.write("Inserting client in set\n")
68 set:insert(new)
69 end
70 -- it is a client socket
71 else
72 local line, error = input:receive()
73 if error then
74 input:close()
75 io.write("Removing client from set\n")
76 set:remove(input)
77 else
78 io.write("Broadcasting line '", line, "'\n")
79 writable, error = socket.skip(1, socket.select(nil, set, 1))
80 if not error then
81 for __, output in ipairs(writable) do
82 if output ~= input then
83 output:send(line .. "\n")
84 end
85 end
86 else io.write("No client ready to receive!!!\n") end
87 end
88 end
89 end
90 end