1
'''defines a class that handles the send and receive operations of a socket
11
log = logging.getLogger('msn.Socket')
13
class Socket(threading.Thread):
14
'''a socket that runs on a thread, it reads the data and put it on the
15
output queue, the data to be sent is added to the input queue'''
17
def __init__(self, host, port):
18
'''class constructor'''
19
threading.Thread.__init__(self)
24
self.input = Queue.Queue()
25
self.output = Queue.Queue()
26
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
30
'''add data to the input queue'''
34
'''close the thread'''
38
'''the main method of the socket, wait until there is something to
39
send or there is something to read, if there is something to send, get
40
it from the input Queue, wait until we can send it and send it, if
41
there is something to read, read it and put it on the output queue'''
42
self.socket.connect((self.host, self.port))
46
# see if we can send or read something
47
(iwtd, owtd) = select.select([self], [self], [])[:2]
49
# if we can read, we try to read
51
if not self._receive():
52
# nothing received, socket closed
54
# do not write until everything is read
58
input_ = self.input.get(True, 0.3)
67
# try to get something to send, wait 0.3 seconds
69
self.socket.send(input_)
70
log.debug('>>> ' + str(input_))
72
self._on_socket_error()
75
log.debug('closing socket thread')
79
'''method that is used by select'''
80
return self.socket.fileno()
83
'''receive data from the socket'''
84
data = self._readline()
85
# if we got something add it to the output queue
87
log.debug('<<< ' + data)
93
'''read until new line'''
94
output = StringIO.StringIO()
97
chunk = self.socket.recv(1)
99
self._on_socket_error()
102
while chunk != '\n' and chunk != '':
105
chunk = self.socket.recv(1)
107
self._on_socket_error()
115
def receive_fixed_size(self, size):
116
'''receive a fixed size of bytes, return it as string'''
117
output = StringIO.StringIO()
119
while output.len < size:
121
output.write(self.socket.recv(size - output.len))
123
self._on_socket_error()
129
def _on_socket_error(self):
130
'''send a message that the socket was closed'''