blob: 61f1cff8eb091a692b17ef5fb717df1bb38076b9 [file] [log] [blame]
Mark Sleecde2b612006-09-03 21:13:07 +00001from TTransport import *
2import socket
3
4class TSocket(TTransportBase):
5
6 """Socket implementation of TTransport base."""
7
Mark Sleec9676562006-09-05 17:34:52 +00008 def __init__(self, host='localhost', port=9090):
Mark Sleecde2b612006-09-03 21:13:07 +00009 self.host = host
10 self.port = port
11 self.handle = None
12
Mark Sleec9676562006-09-05 17:34:52 +000013 def set_handle(self, h):
14 self.handle = h
15
Mark Sleecde2b612006-09-03 21:13:07 +000016 def isOpen(self):
17 return handle != None
18
19 def open(self):
20 self.handle = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
21 self.handle.connect((self.host, self.port))
22
23 def close(self):
24 self.handle.close()
25 self.handle = None
26
27 def readAll(self, sz):
28 buff = ''
29 have = 0
30 while (have < sz):
31 chunk = self.read(sz-have)
32 have += len(chunk)
33 buff += chunk
34 return buff
35
36 def read(self, sz):
37 buff = self.handle.recv(sz)
Mark Sleec9676562006-09-05 17:34:52 +000038 if len(buff) == 0:
Mark Sleec98d0502006-09-06 02:42:25 +000039 raise Exception('TSocket read 0 bytes')
Mark Sleecde2b612006-09-03 21:13:07 +000040 return buff
41
42 def write(self, buff):
Mark Sleec9676562006-09-05 17:34:52 +000043 sent = 0
44 have = len(buff)
45 while sent < have:
46 plus = self.handle.send(buff)
47 if plus == 0:
48 raise Exception('sent 0 bytes')
49 sent += plus
50 buff = buff[plus:]
Mark Sleecde2b612006-09-03 21:13:07 +000051
52 def flush(self):
53 pass
Mark Sleec9676562006-09-05 17:34:52 +000054
55class TServerSocket(TServerTransportBase):
56
57 """Socket implementation of TServerTransport base."""
58
59 def __init__(self, port):
60 self.port = port
61 self.handle = None
62
63 def listen(self):
64 self.handle = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
65 self.handle.bind(('', self.port))
66 self.handle.listen(128)
67
68 def accept(self):
69 (client, addr) = self.handle.accept()
70 result = TSocket()
71 result.set_handle(client)
72 return result
73
74 def close(self):
75 self.handle.close()
76 self.handle = None