-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathex3utils.py
208 lines (155 loc) · 3.9 KB
/
ex3utils.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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
"""
ex3.py - Module for ex3 - David Thorne / AIG / 15-01-2009
"""
import threading
import time
import socket as socketlib
class Socket():
"""
Mutable wrapper class for sockets.
"""
def __init__(self, socket):
# Store internal socket pointer
self._socket = socket
def send(self, msg):
# Ensure a single new-line after the message
self._socket.send("%s\n" % msg.strip())
def close(self):
self._socket.close()
class Receiver():
"""
A class for receiving newline delimited text commands on a socket.
"""
def __init__(self):
# Protect access
self._lock = threading.RLock()
self._running = True
def __call__(self, socket):
"""Called for a connection."""
# Set timeout on socket operations
socket.settimeout(1)
# Wrap socket for events
wrappedSocket = Socket(socket)
# Store the unprocessed data
stored = ''
chunk = ''
# On connect!
self._lock.acquire()
self.onConnect(wrappedSocket)
self._lock.release()
# Loop so long as the receiver is still running
while self.isRunning():
# Take everything up to the first newline of the stored data
(message, sep, rest) = stored.partition('\n')
if sep == '': # If no newline is found, store more data...
while self.isRunning():
try:
chunk = ''
chunk = socket.recv(1024)
stored += chunk
break
except socketlib.timeout:
pass
except:
print 'EXCEPTION'
# Empty chunk means disconnect
if chunk == '':
break;
continue
else: # ...otherwise store the rest
stored = rest
# Process the command
self._lock.acquire()
success = self.onMessage(wrappedSocket, message)
self._lock.release()
if not success:
break;
# On disconnect!
self._lock.acquire()
self.onDisconnect(wrappedSocket)
self._lock.release()
socket.close()
del socket
# On join!
self.onJoin()
def stop(self):
"""Stop this receiver."""
self._lock.acquire()
self._running = False
self._lock.release()
def isRunning(self):
"""Is this receiver still running?"""
self._lock.acquire()
running = self._running
self._lock.release()
return running
def onConnect(self, socket):
pass
def onMessage(self, socket, message):
pass
def onDisconnect(self, socket):
pass
def onJoin(self):
pass
class Server(Receiver):
def start(self, ip, port):
# Set up server socket
serversocket = socketlib.socket(socketlib.AF_INET, socketlib.SOCK_STREAM)
serversocket.setsockopt(socketlib.SOL_SOCKET, socketlib.SO_REUSEADDR, 1)
serversocket.bind((ip, int(port)))
serversocket.listen(10)
serversocket.settimeout(1)
# On start!
self.onStart()
# Main connection loop
threads = []
while self.isRunning():
try:
(socket, address) = serversocket.accept()
thread = threading.Thread(target = self, args = (socket,))
threads.append(thread)
thread.start()
except socketlib.timeout:
pass
except:
self.stop()
# Wait for all threads
while len(threads):
threads.pop().join()
# On stop!
self.onStop()
def onStart(self):
pass
def onStop(self):
pass
class Client(Receiver):
def start(self, ip, port):
# Set up server socket
self._socket = socketlib.socket(socketlib.AF_INET, socketlib.SOCK_STREAM)
self._socket.settimeout(1)
self._socket.connect((ip, int(port)))
# On start!
self.onStart()
# Start listening for incoming messages
self._thread = threading.Thread(target = self, args = (self._socket,))
self._thread.start()
def send(self, message):
# Send message to server
self._lock.acquire()
self._socket.send("%s\n" % message.strip())
self._lock.release()
time.sleep(0.5)
def stop(self):
# Stop event loop
Receiver.stop(self)
# Join thread
if self._thread != threading.currentThread():
self._thread.join()
# On stop!
self.onStop()
def onStart(self):
pass
def onStop(self):
pass
def onJoin(self):
self.stop()