-
Notifications
You must be signed in to change notification settings - Fork 0
/
ClientHandler.py
167 lines (156 loc) · 6.23 KB
/
ClientHandler.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
import socket
import threading
class Client:
"""All commands end with a newline \n. After a connection from the client,
the handler sends an "ID\n" request and to that the client responds with data
describing itself in the format for example "type=PC;name=Doe;\n" and so on with all
of the parameters. The parameters are saved in a dict. The parameters can be changed
by sending for example "param;name=test\n", to which the server responds "OK\n".
Also the server can change a parameter by sending the previous command.
After this the server assigns the device an unique id currently not
in use like this "ID=1\n", to which the client responds "OK\n". Now the connection is
established.
The server sends the id of the first client with the given name to
the request "GetID?name\n" with the syntax "ID=7\n". It also sends all the IDs in use with ; separator as
a response to "GetIDs?\n"".
Data can be sent for example from client 1 to client 7 by using it's id "To7=message\n",
to which the server responds "OK\n".
The server sends to the other client "From1=message\n", to which it must respond something.
"""
clientDict = {}
clientDictLock = threading.Lock()
def send(self, string):
with self.msgLock:
print("Sending:", string)
self.conn.sendall(string.encode("utf-8"))
def recv(self, bytes):
string = self.conn.recv(bytes).decode("utf-8")
print("Received:", string)
return string
def recvcmd(self):
string = ""
while True:
character = self.conn.recv(1).decode("utf-8")
if character == "\n":
break
string+=character
print("Received command:", string)
return string
def sendcmd(self,string):
with self.msgLock:
print("Sending command:", string)
self.conn.sendall((string+"\n").encode("utf-8"))
def checkOK(self):
if self.recvcmd() != "OK":
print("Did not receive OK!!!")
def __init__(self, conn, address, site):
self.conn = conn
self.address = address
self.data = {}
self.msgLock = threading.Lock()
self.dataLock = threading.Lock()
self.waitingForAResponse = False
self.site = site
print("Connection from:", address)
self.thread = threading.Thread(target = self.startCommunication).start()
def startCommunication(self):
#exchange the initial information as explained before
self.sendcmd("ID")
self.conn.settimeout(4)
try:
msg = self.recvcmd()
with self.dataLock:
for pairs in msg.split(";"):
param, value = pairs.split("=",1)
self.data[param] = value
except socket.timeout as err:
print("Client didn't respond, dropping")
conn.close()
return
#give the client a unique id and put it in a dictionary
with Client.clientDictLock:
self.id = 1
while True:
if self.id in Client.clientDict:
self.id += 1
else:
break
Client.clientDict[self.id] = self
self.sendcmd("ID={}".format(self.id))
self.checkOK()
self.site.update()
self.msgloop()
def msgloop(self):
while True:
#wait for a command
self.conn.settimeout(None)
try:
command = self.recvcmd()
except:
with Client.clientDictLock:
del Client.clientDict[self.id]
self.site.update()
return
self.conn.settimeout(4)
if self.waitingForAResponse:
with self.dataLock:
#a message was sent to the device by the webserver, update the site with the response
self.waitingForAResponse = False
self.responseDestination.write(command)
self.responseDestination.finish()
continue
if command == "":
continue
elif command.startswith("GetID?"):
sent = False
name = command.split("?",1)[1]
for client in Client.clientDict.values():
if client.data["name"] == name:
self.sendcmd("ID="+str(client.id))
sent = True
break
if not sent:
self.sendcmd("NONE")
elif command == "GETIDs?":
response = ""
for id, client in Client.clientDict.items():
response += client.data["name"] + "=" + str(id)+";"
sendcmd(response[:-1])
elif command.startswith("To"):
match = re.match(r"To(\d*)=(.*)", command)
if match:
id, data = match.groups()
if int(id) in Client.clientDict:
self.sendcmd("OK")
Client.clientDict[int(id)].sendcmd("From"+id+"="+data)
else:
self.sendcmd("BAD ID")
else:
self.sendcmd("BAD REQUEST")
elif command.startswith("param;"):
match = re.match(r"param;(.*?)=(.*)", command)
if match:
param, value = match.groups()
with self.dataLock:
self.data[param] = value
self.site.update()
self.sendcmd("OK")
if __name__ == "__main__":
from WebPageGen import *
port = 8890
HOST = ''
site = website()
print("Website starting.")
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST,port))
s.listen(10)
except socket.error as err:
print("Error:", err)
sys.exit()
while True:
while 1:
#wait for new connections and make a new object, which handles the client in a new thread
conn, address = s.accept()
Client(conn, address, site)