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
|
#!/usr/bin/env lua5.1
local enet = require("enet")
local util = require("util")
local common = require("common")
local host = enet.host_create("0.0.0.0:18252")
local game_to_peer = {}
local peer_to_game = {}
local function remove_game(peer)
local game = peer_to_game[peer]
if game then
game_to_peer[game] = nil
peer_to_game[peer] = nil
end
end
local function handle(peer, pkt)
if pkt.type == "match_register" then
remove_game(peer)
local game_id = util.rand_string(common.gameid_len)
peer_to_game[peer] = game_id
game_to_peer[game_id] = peer
util.send(peer, { type = "server_match", game_id = util.base64_enc(game_id) })
print(peer, "registered game")
elseif pkt.type == "match_join" then
local game_id = type(pkt.game_id) == "string" and util.base64_dec(pkt.game_id)
if game_id then
local server = game_id and game_to_peer[game_id]
if server then
util.send(server, { type = "server_join", peer_addr = tostring(peer) })
util.send(peer, { type = "client_join", peer_addr = tostring(server) })
print(peer, "joined game", server)
else
util.send(peer, { type = "client_join_fail" })
print(peer, "failed to join game")
end
end
else
print("invalid pkt type")
end
end
while true do
local event = host:service(100)
while event do
if event.type == "receive" then
local pkt = util.json_dec(event.data)
if pkt then
handle(event.peer, pkt)
end
elseif event.type == "connect" then
print(event.peer, "connected")
elseif event.type == "disconnect" then
remove_game(event.peer)
print(event.peer, "disconnected")
end
event = host:service()
end
end
|