-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient.lua
More file actions
282 lines (234 loc) · 6.61 KB
/
client.lua
File metadata and controls
282 lines (234 loc) · 6.61 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
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
local BASE = (...):match("(.-)[^%.]+$")
local socket = require("socket")
local User = require( BASE .. "user" )
local CMD = require( BASE .. "commands" )
local utility = require( BASE .. "utility" )
local Client = {}
Client.__index = Client
local userList = {}
local numberOfUsers = 0
local partMessage = ""
local messageLength = nil
function Client:new( address, port, playerName, authMsg )
local o = {}
setmetatable( o, self )
authMsg = authMsg or ""
print("[NET] Initialising Client...")
o.conn = socket.tcp()
o.conn:settimeout(5)
local ok, msg = o.conn:connect( address, port )
--ok, o.conn = pcall(o.conn.connect, o.conn, address, port)
if ok and o.conn then
o.conn:settimeout(0)
self.send( o, CMD.AUTHORIZATION_REQUREST, authMsg )
print("[NET] -> Client connected", o.conn)
else
o.conn = nil
return nil
end
o.callbacks = {
authorized = nil,
received = nil,
connected = nil,
disconnected = nil,
otherUserConnected = nil,
otherUserDisconnected = nil,
customDataChanged = nil,
}
userList = {}
partMessage = ""
o.clientID = nil
o.playerName = playerName
numberOfUsers = 0
-- Filled if user is kicked:
o.kickMsg = ""
return o
end
function Client:update( dt )
if self.conn then
local data, msg, partOfLine = self.conn:receive( 9999 )
if data then
partMessage = partMessage .. data
else
if msg == "timeout" then
if #partOfLine > 0 then
partMessage = partMessage .. partOfLine
end
elseif msg == "closed" then
--self.conn:shutdown()
print("[NET] Disconnected.")
if self.callbacks.disconnected then
self.callbacks.disconnected( self.kickMsg )
end
self.conn = nil
return false
else
print("[NET] Err Received:", msg, data)
end
end
if not messageLength then
if #partMessage >= 1 then
local headerLength = nil
messageLength, headerLength = utility:headerToLength( partMessage:sub(1,5) )
if messageLength and headerLength then
partMessage = partMessage:sub(headerLength + 1, #partMessage )
end
end
end
-- if I already know how long the message should be:
if messageLength then
if #partMessage >= messageLength then
-- Get actual message:
local currentMsg = partMessage:sub(1, messageLength)
-- Remember rest of already received messages:
partMessage = partMessage:sub( messageLength + 1, #partMessage )
command, content = string.match( currentMsg, "(.)(.*)")
command = string.byte( command )
self:received( command, content )
messageLength = nil
end
end
--[[if data then
if #partMessage > 0 then
data = partMessage .. data
partMessage = ""
end
-- First letter stands for the command:
command, content = string.match(data, "(.)(.*)")
command = string.byte( command )
self:received( command, content )
else
if msg == "timeout" then -- only part of the message could be received
if #partOfLine > 0 then
partMessage = partMessage .. partOfLine
end
elseif msg == "closed" then
--self.conn:shutdown()
print("[NET] Disconnected.")
if self.callbacks.disconnected then
self.callbacks.disconnected( self.kickMsg )
end
self.conn = nil
return false
else
print("[NET] Err Received:", msg, data)
end
end]]
return true
else
return false
end
end
function Client:received( command, msg )
if command == CMD.PING then
-- Respond to ping:
self:send( CMD.PONG, "" )
elseif command == CMD.USER_PINGTIME then
local id, ping = msg:match("(.-)|(.*)")
id = tonumber(id)
if userList[id] then
userList[id].ping.pingReturnTime = tonumber(ping)
end
elseif command == CMD.NEW_PLAYER then
local id, playerName = string.match( msg, "(.*)|(.*)" )
id = tonumber(id)
local user = User:new( nil, playerName, id )
userList[id] = user
numberOfUsers = numberOfUsers + 1
if self.callbacks.newUser then
self.callbacks.newUser( user )
end
elseif command == CMD.PLAYER_LEFT then
local id = tonumber(msg)
local u = userList[id]
userList[id] = nil
numberOfUsers = numberOfUsers - 1
if self.callbacks.otherUserDisconnected then
self.callbacks.otherUserDisconnected( u )
end
elseif command == CMD.AUTHORIZED then
local authed, reason = string.match( msg, "(.*)|(.*)" )
if authed == "true" then
self.authorized = true
print( "[NET] Connection authorized by server." )
-- When authorized, send player name:
self:send( CMD.PLAYERNAME, self.playerName )
else
print( "[NET] Not authorized to join server. Reason: " .. reason )
end
if self.callbacks.authorized then
self.callbacks.authorized( self.authorized, reason )
end
elseif command == CMD.PLAYERNAME then
local id, playerName = string.match( msg, "(.*)|(.*)" )
self.playerName = playerName
self.clientID = tonumber(id)
-- At this point I am fully connected!
if self.callbacks.connected then
self.callbacks.connected()
end
--self.conn:settimeout(5)
elseif command == CMD.USER_VALUE then
local id, keyType, key, valueType, value = string.match( msg, "(.*)|(.*)|(.*)|(.*)|(.*)" )
key = stringToType( key, keyType )
value = stringToType( value, valueType )
id = tonumber( id )
userList[id].customData[key] = value
if self.callbacks.customDataChanged then
self.callback.customDataChanged( user, value, key )
end
elseif command == CMD.KICKED then
self.kickMsg = msg
print("[NET] Kicked from server: " .. msg )
elseif self.callbacks.received then
self.callbacks.received( command, msg )
end
end
function Client:send( command, msg )
local fullMsg = string.char(command) .. (msg or "") --.. "\n"
local len = #fullMsg
assert( len < 256^4, "Length of packet must not be larger than 4GB" )
fullMsg = utility:lengthToHeader( len ) .. fullMsg
local result, err, num = self.conn:send( fullMsg )
while err == "timeout" do
fullMsg = fullMsg:sub( num+1, #fullMsg )
result, err, num = self.conn:send( fullMsg )
end
return
end
function Client:getUsers()
return userList
end
function Client:getNumUsers()
return numberOfUsers
end
function Client:close()
if self.conn then
--self.conn:shutdown()
self.conn:close()
print( "[NET] Closed.")
end
end
function Client:setUserValue( key, value )
local keyType = type( key )
local valueType = type( value )
self:send( CMD.USER_VALUE, keyType .. "|" .. tostring(key) ..
"|" .. valueType .. "|" .. tostring(value) )
end
function Client:getID()
return self.clientID
end
function Client:getUserValue( key )
if not self.clientID then return nil end
local u = userList[self.clientID]
if u then
return u.customData[key]
end
return nil
end
function Client:getUserPing( id )
if users[id] then
return users[id].ping.pingReturnTime
end
end
return Client