-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathserver.py
More file actions
70 lines (63 loc) · 1.87 KB
/
server.py
File metadata and controls
70 lines (63 loc) · 1.87 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
import random
import socket
import time
from _thread import *
import threading
from datetime import datetime
import json
clients_lock = threading.Lock()
connected = 0
clients = {}
def connectionLoop(sock):
while True:
data, addr = sock.recvfrom(1024)
data = str(data)
if addr in clients:
if 'heartbeat' in data:
clients[addr]['lastBeat'] = datetime.now()
else:
if 'connect' in data:
clients[addr] = {}
clients[addr]['lastBeat'] = datetime.now()
clients[addr]['color'] = 0
message = {"cmd": 0,"player":{"id":str(addr)}}
m = json.dumps(message)
for c in clients:
sock.sendto(bytes(m,'utf8'), (c[0],c[1]))
def cleanClients():
while True:
for c in list(clients.keys()):
if (datetime.now() - clients[c]['lastBeat']).total_seconds() > 5:
print('Dropped Client: ', c)
clients_lock.acquire()
del clients[c]
clients_lock.release()
time.sleep(1)
def gameLoop(sock):
while True:
GameState = {"cmd": 1, "players": []}
clients_lock.acquire()
print (clients)
for c in clients:
player = {}
clients[c]['color'] = {"R": random.random(), "G": random.random(), "B": random.random()}
player['id'] = str(c)
player['color'] = clients[c]['color']
GameState['players'].append(player)
s=json.dumps(GameState)
print(s)
for c in clients:
sock.sendto(bytes(s,'utf8'), (c[0],c[1]))
clients_lock.release()
time.sleep(1)
def main():
port = 12345
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('', port))
start_new_thread(gameLoop, (s,))
start_new_thread(connectionLoop, (s,))
start_new_thread(cleanClients,())
while True:
time.sleep(1)
if __name__ == '__main__':
main()