-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuloopchat.lua
More file actions
80 lines (61 loc) · 1.67 KB
/
uloopchat.lua
File metadata and controls
80 lines (61 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env lua
--[[
uloopchat - Chat Server over lua-uloop and lua-socket
Copyright 2014 Agustí Moll <agusti@biruji.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local socket = require("socket")
local uloop = require("uloop")
clients = {}
port = 9099
-- Functions
function sendAll(msg,myip,anonymous)
for yourip,csocket in pairs(clients) do
if ( yourip ~= myip ) then
if (anonymous ~= true) then
csocket:send("[" .. myip .. "]: ")
else
csocket:send(" *** ")
end
csocket:send(msg .. "\n")
end
end
end
uloop.init()
-- TCP Chat Server
local tcp = socket.tcp()
tcp:setoption("reuseaddr", true);
tcp:settimeout(0)
tcp:bind("*", port);
tcp:listen();
print("Start chat daemon.")
tcp_ev = uloop.fd_add( tcp, function(tfd, events)
-- Is new client?
tfd:settimeout(3)
local new_client = assert(tfd:accept())
if new_client ~= nil then
client_ip , port = new_client:getpeername()
client_id = client_ip .. ":" .. port
clients[client_id] = new_client
print("New client from " .. client_id)
sendAll("New client from " .. client_id, client_id,true)
-- Wait read event...
uloop.fd_add(new_client, function(csocket,events)
myip , port = csocket:getpeername()
myid = myip .. ":" .. port
local msg = csocket:receive()
if msg == nil then
csocket:close()
clients[myid] = nil
print("Remove client: " .. myid)
sendAll("Close connection from ".. myid, myid,true)
else
sendAll(msg,myid)
end
end, uloop.ULOOP_READ)
end
end, uloop.ULOOP_READ)
uloop.run()