-
Notifications
You must be signed in to change notification settings - Fork 10
/
server.py
executable file
·72 lines (63 loc) · 2.24 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
#!/usr/bin/python3
import socket
import multiprocessing
import configparser
from strip_devices import smartstrip
config = configparser.ConfigParser()
config.read('/home/pi/kindbot/config.ini')
strip = smartstrip(logging=config['PATHS']['DB_PATH'])
def handle(connection, address):
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("process-%r" % (address,))
try:
logger.debug("Connected %r at %r", connection, address)
while True:
data = connection.recv(1024).decode()
if data == "":
logger.debug("Socket closed remotely")
break
logger.debug("Received data %r", data)
connection.sendall(data.encode())
logger.debug("Sent data")
dev, comm = data.split()
strip.dev_comm(comm, int(dev))
except:
logger.exception("Problem handling request")
finally:
logger.debug("Closing socket")
connection.close()
class Server(object):
def __init__(self, hostname, port):
import logging
self.logger = logging.getLogger("server")
self.hostname = hostname
self.port = port
def start(self):
self.logger.debug("listening")
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.bind((self.hostname, self.port))
self.socket.listen(1)
while True:
conn, address = self.socket.accept()
self.logger.debug("Got connection")
process = multiprocessing.Process(target=handle, args=(conn, address))
process.daemon = True
process.start()
self.logger.debug("Started process %r", process)
if __name__ == "__main__":
import logging
logging.basicConfig(filename='/home/pi/kindbot.log', level=logging.DEBUG)
server = Server("0.0.0.0", 9000)
try:
logging.info("Listening")
server.start()
except:
logging.exception("Unexpected exception")
finally:
logging.info("Shutting down")
for process in multiprocessing.active_children():
logging.info("Shutting down process %r", process)
process.terminate()
process.join()
logging.info("All done")