blob: f12f539ee8d65aa782d8d608d46622256787c361 [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
Aditya Agarwalf954f972007-02-06 01:26:12 +000010 self.por t= port
Mark Sleecde2b612006-09-03 21:13:07 +000011 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):
Aditya Agarwalf954f972007-02-06 01:26:12 +000017 return self.handle != None
18
19 def setTimeout(self, ms):
20 if (self.handle != None):
21 self.handle.settimeout(ms/1000.00)
Mark Sleecde2b612006-09-03 21:13:07 +000022
23 def open(self):
24 self.handle = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
25 self.handle.connect((self.host, self.port))
26
27 def close(self):
Mark Sleed788b2e2006-09-07 01:26:35 +000028 if self.handle != None:
29 self.handle.close()
30 self.handle = None
Mark Sleecde2b612006-09-03 21:13:07 +000031
Mark Sleecde2b612006-09-03 21:13:07 +000032 def read(self, sz):
33 buff = self.handle.recv(sz)
Mark Sleec9676562006-09-05 17:34:52 +000034 if len(buff) == 0:
Mark Slee4f0fed62006-10-02 17:50:08 +000035 raise TTransportException('TSocket read 0 bytes')
Mark Sleecde2b612006-09-03 21:13:07 +000036 return buff
37
38 def write(self, buff):
Mark Sleec9676562006-09-05 17:34:52 +000039 sent = 0
40 have = len(buff)
41 while sent < have:
42 plus = self.handle.send(buff)
43 if plus == 0:
Mark Slee4f0fed62006-10-02 17:50:08 +000044 raise TTransportException('sent 0 bytes')
Mark Sleec9676562006-09-05 17:34:52 +000045 sent += plus
46 buff = buff[plus:]
Mark Sleecde2b612006-09-03 21:13:07 +000047
48 def flush(self):
49 pass
Mark Sleec9676562006-09-05 17:34:52 +000050
51class TServerSocket(TServerTransportBase):
52
53 """Socket implementation of TServerTransport base."""
54
55 def __init__(self, port):
56 self.port = port
57 self.handle = None
58
59 def listen(self):
60 self.handle = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Mark Slee4f0fed62006-10-02 17:50:08 +000061 self.handle.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
62 if hasattr(self.handle, 'set_timeout'):
63 self.handle.set_timeout(None)
Mark Sleec9676562006-09-05 17:34:52 +000064 self.handle.bind(('', self.port))
65 self.handle.listen(128)
66
67 def accept(self):
68 (client, addr) = self.handle.accept()
69 result = TSocket()
Mark Slee4f0fed62006-10-02 17:50:08 +000070 result.setHandle(client)
Mark Sleec9676562006-09-05 17:34:52 +000071 return result
72
73 def close(self):
74 self.handle.close()
75 self.handle = None