-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
socket-server.py
80 lines (61 loc) · 2.13 KB
/
socket-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
import socket, json
import threading
buffer = {}
def process(address, source):
d = json.loads(source)
if d['type'] == 'start_applet':
print('applet content', d['data'])
elif d['type'] == 'start_activity':
print('start activity', d['data'])
elif d['type'] == 'restart_activity':
print('restart activity', d['data'])
elif d['type'] == 'resume_activity':
print('resume activity', d['data'])
elif d['type'] == 'set_response':
print('set response', d['data'])
elif d['type'] == 'finish_activity':
print('finish activity', d['data'])
elif d['type'] == 'live_event':
print('live response', d['data'])
def readData(address, data):
if address not in buffer:
buffer[address] = ''
buffer[address] += data.decode()
index = buffer[address].find('$$$')
if index >= 0:
process(address, buffer[address][:index])
buffer[address] = buffer[address][index+3:]
def serveClient(socket, address):
while 1:
receivedData = socket.recv(1024)
if not receivedData: break
readData(address, receivedData)
socket.close()
print ( "Disconnected from", address)
def startServer():
# Create a socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Ensure that you can restart your server quickly when it terminates
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Set the client socket's TCP "well-known port" number
well_known_port = 8881
sock.bind(('127.0.0.1', well_known_port))
# Set the number of clients waiting for connection that can be queued
sock.listen(5)
print ('waiting for connection')
# loop waiting for connections (terminate with Ctrl-C)
try:
while 1:
newSocket, address = sock.accept()
thread = threading.Thread(
target=serveClient,
kwargs={
'socket': newSocket,
'address': address
}
)
print ("Connected from", address)
thread.start()
finally:
sock.close()
startServer()