-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.lua
105 lines (103 loc) · 2.02 KB
/
client.lua
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
-- manages client sockets
-- buffers sending and receiving
clients={}
client={}
local buffering={}
function client.new(sk,norec)
local cl
cl={
closed=false,
sk=sk,
sbuffer="",
send=function(txt)
if txt then
cl.sbuffer=cl.sbuffer..txt
end
local t,err,c=sk:send(cl.sbuffer)
if not t and err~="timeout" then
cl.onError("send",err)
return
elseif not c then
print("done sending")
hook.remrsocket(cl.sk)
bfrind=1
cl.sbuffer=""
buffering[cl.sk]=nil
if cl.onDoneSending then
local f=cl.onDoneSending
cl.onDoneSending=nil
f(cl)
end
return
elseif not buffering[cl.sk] then
hook.newrsocket(cl.sk)
buffering[cl.sk]=cl
end
cl.sbuffer=cl.sbuffer:sub(c+1)
end,
close=function(...)
print("cl tryclose")
if not cl.closed then
print("cl close")
-- cleanup
hook.remsocket(sk)
hook.remrsocket(sk)
clients[sk]=nil
buffering[cl]=nil
sk:close()
cl.closed=true
if cl.onClose then
cl.onClose(...)
end
end
end,
onError=function(t,err)
print("cl error "..err)
cl.close()
end,
rbuffer="",
receive=function(mode)
if mode then
if cl.rbuffer<mode then
return
end
local txt=cl.rbuffer:sub(1,mode)
cl.rbuffer=cl.rbuffer:sub(5)
return txt
end
local line,rbuffer=cl.rbuffer:match("^(.-)\r?\n(.*)")
if line then
cl.rbuffer=rbuffer
return line
end
end,
}
clients[sk]=cl
if not norec then
receivehead(cl)
end
return cl
end
hook.new("select",function(rq,sq)
for k,v in pairs(sq) do
if type(v)~="number" then
if buffering[v] then
buffering[v].send()
end
end
end
for k,v in pairs(rq) do
if clients[v] then
local cl=clients[v]
local s2,err,s=v:receive("*a")
if err=="closed" then
cl.close()
else
cl.rbuffer=cl.rbuffer..(s or s2)
if cl.onReceive then
cl.onReceive()
end
end
end
end
end,"client socket manager")