-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.py
294 lines (271 loc) · 11.5 KB
/
server.py
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
283
284
285
286
287
288
289
290
291
292
293
294
import random
import selectors
import socket
import struct
import time
import types
from threading import Thread
from config import *
group1_key, group2_key = 'group 1', 'group 2'
team_map = {group1_key: [], group2_key: []}
group1_ips, group2_ips = [], []
group1_names, group2_names = [], []
counter_group1, counter_group2 = 0, 0
total_games = 0
high_score = 0
sel = selectors.DefaultSelector()
# This module allows high-level and efficient I/O multiplexing
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as lsock:
"""
Sockets write into a local socket specific write buffer and read from a socket specific read buffer throughout the connection.
"""
lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
lsock.bind((host, port))
lsock.listen()
print(Bold, 'Server started, listening on IP address ', host, RESET)
lsock.setblocking(False)
sel.register(lsock, selectors.EVENT_READ, data=None)
def accept_wrapper(sock):
"""
accepts connection requests from clients while still sending offer requests.
"""
try:
conn, address = sock.accept() # Should be ready to read
print(Green, 'accepted connection from', RESET, address)
conn.setblocking(False)
data = types.SimpleNamespace(addr=address, inb=b'', outb=b'')
sel.register(conn, selectors.EVENT_READ |
selectors.EVENT_WRITE, data=data)
except:
pass
def send_udp_broadcast():
"""
Servers broadcast their announcements with destination port X using UDP
"""
magic = [0xfe, 0xed, 0xbe, 0xef] # Magic cookie
m_type = [0x02] # Message type
host_port = struct.pack('>H', port) # Server port
msg = bytes(magic) + bytes(m_type) + bytes(host_port)
ip_start = host[:host.rfind('.') + 1]
ip_range_list = ['{}{}'.format(ip_start, x) for x in range(0, 256)]
time_end = time.time() + udp_time
while time.time() < time_end:
for ip in ip_range_list:
sock = socket.socket(
socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) # UDP
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sock.sendto(msg, (ip, port))
sock.close()
def create_team(key, mask, recv_data):
"""
divides all clients into two groups in a random way.
"""
global group1_ips, group2_ips, group1_names, group2_names
if len(team_map.get(group1_key)) == len(team_map.get(group2_key)):
group, arr = random.choice(list(team_map.items()))
team_map[group].append((recv_data, key, mask))
if group == group1_key:
group1_ips.append(key.data.addr)
group1_names.append(arr[0][0][:-1])
else:
group2_ips.append(key.data.addr)
group2_names.append(arr[0][0][:-1])
elif len(team_map.get(group1_key)) < len(team_map.get(group2_key)):
team_map[group1_key].append((recv_data, key, mask))
group1_ips.append(key.data.addr)
group1_names.append(recv_data)
elif len(team_map.get(group2_key)) < len(team_map.get(group1_key)):
team_map[group2_key].append((recv_data, key, mask))
group2_ips.append(key.data.addr)
group2_names.append(recv_data)
def get_char_from_client(sock, data, mask):
"""
Get characters from the client
"""
if mask & selectors.EVENT_READ:
try:
# Should be ready to read
recv_data = sock.recv(RECIEVE_BUFFER_SIZE)
if recv_data:
update_counter(data)
else:
sel.unregister(sock)
sock.close()
print(Yellow + Bold + 'closing connection to', data.addr)
except:
pass
if mask & selectors.EVENT_WRITE:
if data.outb:
sent = sock.send(data.outb) # Should be ready to write
data.outb = data.outb[sent:]
def update_counter(data):
"""
Update the global counter
"""
if data.addr in group1_ips:
global counter_group1
counter_group1 += 1
elif data.addr in group2_ips:
global counter_group2
counter_group2 += 1
def send_game_over(key, mask, msg):
"""
Sent to all the clients the game over message via TCP connection and close this one.
"""
sock = key.fileobj
data = key.data
if mask & selectors.EVENT_READ:
data.outb += msg
if mask & selectors.EVENT_WRITE:
if data.outb:
sent = sock.send(data.outb) # Should be ready to write
data.outb = data.outb[sent:]
sel.unregister(sock)
sock.close()
print(Cyan + Bold + 'closing connection to', data.addr)
def display_team():
"""
Send to multiple client a starting message.
"""
for client in team_map.get(group1_key) + team_map.get(group2_key):
sock = client[1].fileobj
data = client[1].data
sent_client_start_msg(sock, data, client[1], client[2])
def sent_client_start_msg(sock, data, key, mask):
"""
Sent to multiple clients the starting message via TCP connection.
"""
if mask & selectors.EVENT_READ:
group1_names = ''.join([i[0] for i in team_map.get(group1_key)])
group2_names = ''.join([i[0] for i in team_map.get(group2_key)])
start_msg = f"Welcome to Keyboard Spamming Battle Royale.\n Group 1:\n ==\n " \
f"{group1_names}\n Group 2:\n ==\n {group2_names}\n " \
f"Start pressing keys on your keyboard as fast as you can!! "
data.outb += start_msg.encode('ascii')
if mask & selectors.EVENT_WRITE:
if data.outb:
try:
sent = sock.send(data.outb) # Should be ready to write
data.outb = data.outb[sent:]
except:
delete_team(sock, data, key)
def delete_team(sock, data, key):
"""
Delete team from the server.
"""
try:
for conn in team_map.get(group1_key):
if conn[1] == key:
team_map.get(group1_key).remove(conn)
for conn in team_map.get(group2_key):
if conn[1] == key:
team_map.get(group2_key).remove(conn)
sel.unregister(sock)
sock.close()
print(Magenta + Bold + 'closing connection to', data.addr)
except:
pass
def display_game_result():
"""
Display the winning message.
"""
global counter_group1, counter_group2
if counter_group1 > counter_group2:
win_group = "Group 1 wins!"
winner_group_teams = ''.join(
[i[0] for i in team_map.get(group1_key)])
elif counter_group1 < counter_group2:
win_group = "Group 2 wins!"
winner_group_teams = ''.join(
[i[0] for i in team_map.get(group2_key)])
else:
win_group = "Draw between Group 1 and Group 2"
winner_group_teams = ''.join([i[0] for i in team_map.get(
group1_key)]) + ''.join([i[0] for i in team_map.get(group2_key)])
winner_msg = f"Game over!\nGroup 1 typed in {counter_group1} characters. Group 2 typed in {counter_group2} characters.\n" \
f"{win_group} \n" \
f"Congratulations to the winners:\n==\n{winner_group_teams}\n"
return winner_msg.encode('ascii')
def init_variable():
"""
Init the global variable before starting a new game.
"""
global team_map, group1_ips, group2_ips, counter_group1, counter_group2, group1_names, group2_names
team_map = {'group 1': [], 'group 2': []}
group1_ips, group2_ips = [], []
group1_names, group2_names = [], []
counter_group1, counter_group2 = 0, 0
def stats():
"""
Display some fun/intersting stats when the game finished.
"""
global high_score, total_games, team_map, group1_ips, group2_ips, counter_group1, counter_group2, group1_names, group2_names
total_games += 1
high_score = max(high_score, counter_group1, counter_group2)
print()
print(Blue, BgWhite,)
print('+'+'-'*48+'+')
print('|'+' '*18+'Server Stats'+' '*18+'|')
print('+'+'-'*48+'+', end='')
print(RESET)
print(White, '\n* Total games played on server: {}'.format(total_games))
print('* Highest score: {} keys'.format(high_score))
try:
print('* Group 1 achived {0:.2f}% from the points'.format(
(counter_group1/(counter_group1+counter_group2) * 100)))
print('* Group 2 achived {0:.2f}% from the points'.format(
(counter_group2/(counter_group1+counter_group2)) * 100))
except:
pass
print(RESET)
print(Blue, '+'+'-'*48+'+', RESET)
print()
def main():
"""
Main game loop, runs without stopping.
"""
global group1_ips, group2_ips, team_map, counter_group1, counter_group2, group1_names, group2_names
while True:
t1 = Thread(name='udp', target=send_udp_broadcast, daemon=True)
t1.start()
t_end = time.time() + udp_time
while time.time() < t_end:
events = sel.select(timeout=(t_end - time.time()))
for key, mask in events:
if key.data is None:
accept_wrapper(key.fileobj)
else:
if mask & selectors.EVENT_READ:
recv_data = key.fileobj.recv(RECIEVE_BUFFER_SIZE).decode(
"utf-8") # Should be ready to read
if recv_data:
create_team(key, mask, recv_data)
else:
try:
sel.unregister(key.fileobj)
key.fileobj.close()
print(Magenta + Bold +
'closing connection to', key.data.addr)
except:
pass
t1.join()
print(Magenta + Bold + "group1 = ", group1_names)
print(Red + Bold + "group2 = ", group2_names)
display_team()
time_end = time.time() + game_time
while time.time() < time_end:
events = sel.select(timeout=(time_end - time.time()))
for key, mask in events:
if key.data is None:
accept_wrapper(key.fileobj)
else:
sock = key.fileobj
data = key.data
get_char_from_client(sock, data, mask)
for client in team_map.get(group1_key) + team_map.get(group2_key):
send_game_over(client[1], client[2], display_game_result())
stats()
init_variable()
print(Cyan + "Game over, sending out offer requests...", RESET)
if __name__ == '__main__':
main()