David Reiss | 9f3296b | 2010-08-31 16:58:41 +0000 | [diff] [blame^] | 1 | # |
| 2 | # Licensed to the Apache Software Foundation (ASF) under one |
| 3 | # or more contributor license agreements. See the NOTICE file |
| 4 | # distributed with this work for additional information |
| 5 | # regarding copyright ownership. The ASF licenses this file |
| 6 | # to you under the Apache License, Version 2.0 (the |
| 7 | # "License"); you may not use this file except in compliance |
| 8 | # with the License. You may obtain a copy of the License at |
| 9 | # |
| 10 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | # |
| 12 | # Unless required by applicable law or agreed to in writing, |
| 13 | # software distributed under the License is distributed on an |
| 14 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | # KIND, either express or implied. See the License for the |
| 16 | # specific language governing permissions and limitations |
| 17 | # under the License. |
| 18 | # |
| 19 | import zmq |
| 20 | from cStringIO import StringIO |
| 21 | from thrift.transport.TTransport import TTransportBase, CReadableTransport |
| 22 | |
| 23 | class TZmqClient(TTransportBase, CReadableTransport): |
| 24 | def __init__(self, ctx, endpoint, sock_type): |
| 25 | self._sock = ctx.socket(sock_type) |
| 26 | self._endpoint = endpoint |
| 27 | self._wbuf = StringIO() |
| 28 | self._rbuf = StringIO() |
| 29 | |
| 30 | def open(self): |
| 31 | self._sock.connect(self._endpoint) |
| 32 | |
| 33 | def read(self, size): |
| 34 | ret = self._rbuf.read(size) |
| 35 | if len(ret) != 0: |
| 36 | return ret |
| 37 | self._read_message() |
| 38 | return self._rbuf.read(size) |
| 39 | |
| 40 | def _read_message(self): |
| 41 | msg = self._sock.recv() |
| 42 | self._rbuf = StringIO(msg) |
| 43 | |
| 44 | def write(self, buf): |
| 45 | self._wbuf.write(buf) |
| 46 | |
| 47 | def flush(self): |
| 48 | msg = self._wbuf.getvalue() |
| 49 | self._wbuf = StringIO() |
| 50 | self._sock.send(msg) |
| 51 | |
| 52 | # Implement the CReadableTransport interface. |
| 53 | @property |
| 54 | def cstringio_buf(self): |
| 55 | return self._rbuf |
| 56 | |
| 57 | # NOTE: This will probably not actually work. |
| 58 | def cstringio_refill(self, prefix, reqlen): |
| 59 | while len(prefix) < reqlen: |
| 60 | self.read_message() |
| 61 | prefix += self._rbuf.getvalue() |
| 62 | self._rbuf = StringIO(prefix) |
| 63 | return self._rbuf |