blob: dd4a166601da872bbeff973970596dfd4696ffb1 [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 Slee4f0fed62006-10-02 17:50:08 +000013 def setHandle(self, h):
Mark Sleec9676562006-09-05 17:34:52 +000014 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):
Mark Sleed788b2e2006-09-07 01:26:35 +000024 if self.handle != None:
25 self.handle.close()
26 self.handle = None
Mark Sleecde2b612006-09-03 21:13:07 +000027
28 def readAll(self, sz):
29 buff = ''
30 have = 0
31 while (have < sz):
32 chunk = self.read(sz-have)
33 have += len(chunk)
34 buff += chunk
35 return buff
36
37 def read(self, sz):
38 buff = self.handle.recv(sz)
Mark Sleec9676562006-09-05 17:34:52 +000039 if len(buff) == 0:
Mark Slee4f0fed62006-10-02 17:50:08 +000040 raise TTransportException('TSocket read 0 bytes')
Mark Sleecde2b612006-09-03 21:13:07 +000041 return buff
42
43 def write(self, buff):
Mark Sleec9676562006-09-05 17:34:52 +000044 sent = 0
45 have = len(buff)
46 while sent < have:
47 plus = self.handle.send(buff)
48 if plus == 0:
Mark Slee4f0fed62006-10-02 17:50:08 +000049 raise TTransportException('sent 0 bytes')
Mark Sleec9676562006-09-05 17:34:52 +000050 sent += plus
51 buff = buff[plus:]
Mark Sleecde2b612006-09-03 21:13:07 +000052
53 def flush(self):
54 pass
Mark Sleec9676562006-09-05 17:34:52 +000055
56class TServerSocket(TServerTransportBase):
57
58 """Socket implementation of TServerTransport base."""
59
60 def __init__(self, port):
61 self.port = port
62 self.handle = None
63
64 def listen(self):
65 self.handle = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Mark Slee4f0fed62006-10-02 17:50:08 +000066 self.handle.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
67 if hasattr(self.handle, 'set_timeout'):
68 self.handle.set_timeout(None)
Mark Sleec9676562006-09-05 17:34:52 +000069 self.handle.bind(('', self.port))
70 self.handle.listen(128)
71
72 def accept(self):
73 (client, addr) = self.handle.accept()
74 result = TSocket()
Mark Slee4f0fed62006-10-02 17:50:08 +000075 result.setHandle(client)
Mark Sleec9676562006-09-05 17:34:52 +000076 return result
77
78 def close(self):
79 self.handle.close()
80 self.handle = None