Language:
Lua     Change language:
Pastebin: 92422
Author: middayc
Subject: publish to all tcp server
Created: 2008-07-25 07:09:42
Download and save
Toggle line numbers
1-- simple publish-to-all TCP server with persistent connections in LUA 
2-- ( I am just learning about coroutines and closures a little) 
3 
4local sock = require("socket"
5local stop = 0 
6 
7 
8function list_iter (t) 
9  local i = 0 
10  local n = table.getn(t) 
11  return function () 
12           i = i + 1 
13           if i <= n then return t[i] end 
14         end 
15end 
16 
17 
18function serve() 
19 
20    local srv = assert(sock.bind("*", 9049)) 
21    print ("server created 9049"
22 
23    local clis = {} 
24 
25    local stop = 0 
26 
27    function acceptClis() 
28        while 1 do 
29            srv:settimeout(0
30            local cli = srv:accept() 
31            if cli ~= nil then 
32                print("accepted con. cnt: " .. ( table.getn(clis) + 1 ) ) 
33                cli:settimeout(0.01
34                table.insert(clis, cli) 
35            else 
36                return 
37            end 
38            coroutine.yield() 
39        end 
40    end 
41 
42    function recieveAll() 
43        for cli in list_iter(clis) do 
44            if cli ~= nil then 
45                msg, er = cli:receive() 
46                if msg ~= nil then 
47                    print(msg) 
48                    if msg == "STOPALL" then stop = 1 
49                    elseif msg == "STOP" then cli:close() 
50                    else publishToAll(msg) end 
51                    print("recieved>>> " .. msg) 
52                    cli:send("(accepted)"
53                end 
54            end 
55            coroutine.yield() 
56        end 
57    end 
58 
59    function publishToAll(msg) 
60        for cli in list_iter(clis) do cli:send("NEWS>> " .. msg) ; coroutine.yield() end 
61    end 
62 
63    function closeClis() 
64        for cli in list_iter(clis) do cli:close() end 
65    end 
66 
67 
68    while stop == 0 do 
69        acceptClis() 
70        recieveAll() 
71    end 
72 
73 
74    closeClis() 
75    srv:close() 
76 
77end 
78 
79 
80local coServe = coroutine.create(function () serve() end
81 
82while coroutine.status(coServe) ~= "dead" do 
83    coroutine.resume(coServe) 
84    -- more coroutines here or there is no point in using them like I do now 
85end 
86 
87-- TODO 
88-- we need to detect when client disconnects without STOP and act on it 
89-- we need to remove closed clients from clis list 
90 
Download and save
Toggle line numbers
Thread:
[92422] publish to all tcp server by middayc at 2008-07-25 07:09:42
Tip: Click the line numbers to toggle highliting on that line.

Paste followup:

Language:
Author:
Subject:


    Tabstop:     bigger biggest
Note: You can prefix a line with "@@@" to highlight it.