blob: c8f9e3627447588807d14fe1bbe7f672056f5375 [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
Aditya Agarwal9bae5e72007-02-07 02:36:56 +00008
Mark Sleec9676562006-09-05 17:34:52 +00009 def __init__(self, host='localhost', port=9090):
Mark Sleecde2b612006-09-03 21:13:07 +000010 self.host = host
Aditya Agarwal9bae5e72007-02-07 02:36:56 +000011 self.port = port
Mark Sleecde2b612006-09-03 21:13:07 +000012 self.handle = None
13
Mark Slee4f0fed62006-10-02 17:50:08 +000014 def setHandle(self, h):
Mark Sleec9676562006-09-05 17:34:52 +000015 self.handle = h
16
Mark Sleecde2b612006-09-03 21:13:07 +000017 def isOpen(self):
Aditya Agarwalf954f972007-02-06 01:26:12 +000018 return self.handle != None
19
20 def setTimeout(self, ms):
21 if (self.handle != None):
22 self.handle.settimeout(ms/1000.00)
Mark Sleecde2b612006-09-03 21:13:07 +000023
24 def open(self):
25 self.handle = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
26 self.handle.connect((self.host, self.port))
27
28 def close(self):
Mark Sleed788b2e2006-09-07 01:26:35 +000029 if self.handle != None:
30 self.handle.close()
31 self.handle = None
Mark Sleecde2b612006-09-03 21:13:07 +000032
Mark Sleecde2b612006-09-03 21:13:07 +000033 def read(self, sz):
34 buff = self.handle.recv(sz)
Mark Sleec9676562006-09-05 17:34:52 +000035 if len(buff) == 0:
Mark Slee4f0fed62006-10-02 17:50:08 +000036 raise TTransportException('TSocket read 0 bytes')
Mark Sleecde2b612006-09-03 21:13:07 +000037 return buff
38
39 def write(self, buff):
Mark Sleec9676562006-09-05 17:34:52 +000040 sent = 0
41 have = len(buff)
42 while sent < have:
43 plus = self.handle.send(buff)
44 if plus == 0:
Mark Slee4f0fed62006-10-02 17:50:08 +000045 raise TTransportException('sent 0 bytes')
Mark Sleec9676562006-09-05 17:34:52 +000046 sent += plus
47 buff = buff[plus:]
Mark Sleecde2b612006-09-03 21:13:07 +000048
49 def flush(self):
50 pass
Mark Sleec9676562006-09-05 17:34:52 +000051
52class TServerSocket(TServerTransportBase):
53
54 """Socket implementation of TServerTransport base."""
55
56 def __init__(self, port):
57 self.port = port
58 self.handle = None
59
60 def listen(self):
61 self.handle = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Mark Slee4f0fed62006-10-02 17:50:08 +000062 self.handle.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
63 if hasattr(self.handle, 'set_timeout'):
64 self.handle.set_timeout(None)
Mark Sleec9676562006-09-05 17:34:52 +000065 self.handle.bind(('', self.port))
66 self.handle.listen(128)
67
68 def accept(self):
69 (client, addr) = self.handle.accept()
70 result = TSocket()
Mark Slee4f0fed62006-10-02 17:50:08 +000071 result.setHandle(client)
Mark Sleec9676562006-09-05 17:34:52 +000072 return result
73
74 def close(self):
75 self.handle.close()
76 self.handle = None