Mark Slee | cde2b61 | 2006-09-03 21:13:07 +0000 | [diff] [blame] | 1 | from TTransport import * |
| 2 | import socket |
| 3 | |
| 4 | class TSocket(TTransportBase): |
| 5 | |
| 6 | """Socket implementation of TTransport base.""" |
| 7 | |
Mark Slee | c967656 | 2006-09-05 17:34:52 +0000 | [diff] [blame] | 8 | def __init__(self, host='localhost', port=9090): |
Mark Slee | cde2b61 | 2006-09-03 21:13:07 +0000 | [diff] [blame] | 9 | self.host = host |
| 10 | self.port = port |
| 11 | self.handle = None |
| 12 | |
Mark Slee | c967656 | 2006-09-05 17:34:52 +0000 | [diff] [blame] | 13 | def set_handle(self, h): |
| 14 | self.handle = h |
| 15 | |
Mark Slee | cde2b61 | 2006-09-03 21:13:07 +0000 | [diff] [blame] | 16 | 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 Slee | c967656 | 2006-09-05 17:34:52 +0000 | [diff] [blame] | 38 | if len(buff) == 0: |
Mark Slee | c98d050 | 2006-09-06 02:42:25 +0000 | [diff] [blame] | 39 | raise Exception('TSocket read 0 bytes') |
Mark Slee | cde2b61 | 2006-09-03 21:13:07 +0000 | [diff] [blame] | 40 | return buff |
| 41 | |
| 42 | def write(self, buff): |
Mark Slee | c967656 | 2006-09-05 17:34:52 +0000 | [diff] [blame] | 43 | 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 Slee | cde2b61 | 2006-09-03 21:13:07 +0000 | [diff] [blame] | 51 | |
| 52 | def flush(self): |
| 53 | pass |
Mark Slee | c967656 | 2006-09-05 17:34:52 +0000 | [diff] [blame] | 54 | |
| 55 | class 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 |