| 21 | return result.encode('utf-8') |
| 22 | |
| 23 | class Client(asyncore.dispatcher): |
| 24 | def __init__(self, host, port): |
| 25 | asyncore.dispatcher.__init__(self) |
| 26 | self.create_socket(socket.AF_INET, socket.SOCK_STREAM) |
| 27 | self.connect((host, port)) |
| 28 | self.buf = b'' |
| 29 | self.inbuf = b'' |
| 30 | self.callbacks = list() |
| 31 | self.client_id = 0 |
| 32 | self.get_client_id() |
| 33 | |
| 34 | def handle_connect(self): |
| 35 | pass |
| 36 | |
| 37 | def handle_read(self): |
| 38 | self.inbuf += self.recv(8192) |
| 39 | self.parse_response() |
| 40 | |
| 41 | def handle_write(self): |
| 42 | sent = self.send(self.buf) |
| 43 | self.buf = self.buf[sent:] |
| 44 | |
| 45 | def handle_close(self): |
| 46 | self.close() |
| 47 | |
| 48 | def writable(self): |
| 49 | return len(self.buf) > 0 |
| 50 | |
| 51 | def parse_array(self, startpos): |
| 52 | assert(self.inbuf[startpos] == ord('*')) |
| 53 | endrange = self.inbuf[startpos+1:].find(ord('\r')) + 1 + startpos |
| 54 | assert(endrange > 0) |
| 55 | numargs = int(self.inbuf[startpos+1:endrange]) |
| 56 | if numargs == -1: # Nil array, used in some returns |
| 57 | startpos = endrange + 2 |
| 58 | return startpos, [] |
| 59 | assert(numargs > 0) |
| 60 | args = list() |
| 61 | startpos = endrange + 2 # plus 1 gets us to the '\n' and the next gets us to the start char |
| 62 | |
| 63 | while len(args) < numargs: |
| 64 | # We're parsing entries of the form "$N\r\nnnnnnn\r\n" |
| 65 | if startpos >= len(self.inbuf): |
| 66 | return # Not the full response |
| 67 | if self.inbuf[startpos] == ord('*'): |
| 68 | startpos, arr = self.parse_array(startpos) |
| 69 | args.append(arr) |
| 70 | else: |
| 71 | assert(self.inbuf[startpos] == ord('$')) |
| 72 | startpos = startpos + 1 |
| 73 | endrange = self.inbuf[startpos:].find(b'\r') |
| 74 | if endrange < 0: |
| 75 | return |
| 76 | endrange += startpos |
| 77 | assert(endrange <= len(self.inbuf)) |
| 78 | length = int(self.inbuf[startpos:endrange]) |
| 79 | if length < 0: |
| 80 | return |
no outgoing calls
no test coverage detected