forked from jbs1/jhack14
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
101 lines (89 loc) · 2.6 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
import socket
import netifaces as ni
import sys
import signal
#from threading import Thread # check if still needed
import socketserver
from player import *
MSG_LEN = 4096
clients = [] # client sockets
players = {} # player data
"""
Updates all the clients connected to the server,
except for the client who is the source of the msg
(if one is specified).
"""
def updateClients(msg, source=None):
global clients
for client in clients:
if client is not source:
print("updating", str(client))
client.sendall(msg.encode())
"""
Updates a single client with a message.
"""
def updateClient(msg, client):
print("updating", str(client))
client.sendall(msg.encode())
"""
Catches SIGINT's to provide for a cleaner shutdown.
"""
def signal_handler(self, signal, frame=None):
global clients
print("Shutting down..")
for client in clients:
client.close()
# TODO shutdown / close threadedTcpServer!
sys.exit(0)
class Server(socketserver.BaseRequestHandler):
playername = ""
def receive(self):
msg = self.request.recv(MSG_LEN).decode()
print("received:", msg)
return msg
def handle(self):
global clients
global players
print("connection from", self.client_address)
clients.append(self.request)
while True:
msg = self.receive().strip()
tokens = msg.split()
if not tokens:
clients.remove(self.request) # and this as well (s.b.)
del players[self.playername] # check if this works
updateClients("DISCONNECT " + self.playername, self.request)
break
action = tokens.pop(0)
if action == "CONNECT":
p = tokens.pop(0)
if self.playername == "": # initial connection
for name in players.keys(): # send player list
updateClient("CONNECT " + name, self.request)
self.playername = p # create own player obj
players[p] = Player(p)
print("added player", p)
updateClients(msg, self.request)
elif action == "DISCONNECT":
p = tokens.pop(0)
if p == self.playername:
break
#clients.remove(self.request)
print("removing player", p)
updateClients(msg, self.request)
elif action in ["MOVE", "SET", "DECREASE", "COPY"]:
updateClients(msg, self.request)
else:
print("Unkown action in handleConnection()")
break
self.request.close()
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
pass
signal.signal(signal.SIGINT, signal_handler)
addrs = ni.ifaddresses('wlan0')
if ni.AF_INET in addrs.keys():
host = addrs[ni.AF_INET].pop(0)['addr']
else:
host = "127.0.0.1"
print("Your address: ", host)
tserver = ThreadedTCPServer((host, 9555), Server).serve_forever()