blob: 2c7dd3ee0806bcd7adc18c9c7072fedeb3aad620 [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):
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 Sleec98d0502006-09-06 02:42:25 +000040 raise Exception('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:
49 raise Exception('sent 0 bytes')
50 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)
66 self.handle.bind(('', self.port))
67 self.handle.listen(128)
68
69 def accept(self):
70 (client, addr) = self.handle.accept()
71 result = TSocket()
72 result.set_handle(client)
73 return result
74
75 def close(self):
76 self.handle.close()
77 self.handle = None