-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMobile.py
81 lines (68 loc) · 2.48 KB
/
Mobile.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
import threading
import socket
class Mobile(object):
def __init__(self, oInterpret):
self.oInterpret = oInterpret
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
HOST = ''
PORT = 5002
self.sock.bind((HOST,PORT))
self.sock.listen(10) # arbitrary
'''
Creates new thread for each client for I/O operation.
Continues until one of communication threads terminates.
'''
def mobile(self, communication_Event):
while communication_Event.is_set():
try:
conn, addr = self.sock.accept()
print "Client %s connected." %(addr[0],)
connThread = threading.Thread(target = self.connOperator, name = addr[0],
args = (conn, addr,))
connThread.daemon = True
connThread.start()
except:
print "Closing all threads..."
communication_Event.clear()
'''
Given a client, fork every input.
'''
def connOperator(self, conn, addr):
forked_Event = threading.Event()
forked_Event.set()
while 1:
try:
line = conn.recv(1024) # pause here and send multiple from client
if not line:
raise socket.error
thread = threading.Thread(target = self.inputOperator, name = 'forked_mobile',
args = (line, conn, forked_Event,))
thread.daemon = True
thread.start()
except socket.error as e:
print "Client %s has disconnected." %(addr[0],)
conn.close()
break
'''
Interprets input and sends the result.
'''
def inputOperator(self, line, conn, forked_Event):
res = self.oInterpret.interpret(line)
if res == None:
return
try:
if forked_Event.is_set():
conn.sendall(res)
except socket.error:
forked_Event.clear()
if __name__ == "__main__":
import Interpret
print "Testing Mobile..."
oInterpret = Interpret.Interpret()
oMobile = Mobile(oInterpret)
communication_Event = threading.Event()
communication_Event.set()
print "Objects created."
oMobile.mobile(communication_Event)
print "Successful launch."