-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocketMiddleware.py
More file actions
executable file
·61 lines (56 loc) · 1.72 KB
/
SocketMiddleware.py
File metadata and controls
executable file
·61 lines (56 loc) · 1.72 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
#!/usr/bin/env python3
# -*- coding: utf-*- -*-
from middleware_common import *
from os import fork
from time import sleep
import socket
import sys
def listen_on_socket(socket, *args):
if socket is None:
return
command = ""
file = socket.makefile('rwb')
while True:
try:
data = file.read(1)
if data == b'':
sleep(0.001)
continue
else:
data = data.decode('ascii')
if data == AtHomeProtocol['end_of_communication']:
print('Communication ended', file=sys.stderr)
return
if data != AtHomeProtocol['end_of_command']:
command += data
else:
command = ""
continue
if command.endswith(AtHomeProtocol['end_of_line']):
command = command[0:-2]
if command in AtHomeCommands:
AtHomeCommands[command](file)
else:
command = ""
raise NameError('[Unknown Command] %s' % command)
command = ""
except EOFError:
file.close()
socket.close()
return
except Exception as e:
print('[Exception] %s' % e, file=sys.stderr)
if __name__ == "__main__":
socket = socket.socket()
socket.bind(('0.0.0.0', 4444))
socket.listen(5)
while True:
conn, address = socket.accept()
if conn is not None:
print('Accepted connection', file=sys.stderr)
if fork() == 0:
listen_on_socket(conn, address)
sys.exit(0)
else:
conn.close()
sleep(0.001)