You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.2 KiB

9 years ago
  1. # Simple read() method around a bytearray
  2. class BytesBuffer():
  3. def __init__(self, b):
  4. self.buf = b
  5. self.readCount = 0
  6. def count(self):
  7. return self.readCount
  8. def reset_count(self):
  9. self.readCount = 0
  10. def size(self):
  11. return len(self.buf)
  12. def peek(self):
  13. return self.buf[0]
  14. def write(self, b):
  15. # b should be castable to byte array
  16. self.buf += bytearray(b)
  17. def read(self, n):
  18. if len(self.buf) < n:
  19. print("reader err: buf less than n")
  20. # TODO: exception
  21. return
  22. self.readCount += n
  23. r = self.buf[:n]
  24. self.buf = self.buf[n:]
  25. return r
  26. # Buffer bytes off a tcp connection and read them off in chunks
  27. class ConnReader():
  28. def __init__(self, conn):
  29. self.conn = conn
  30. self.buf = bytearray()
  31. # blocking
  32. def read(self, n):
  33. while n > len(self.buf):
  34. moreBuf = self.conn.recv(1024)
  35. if not moreBuf:
  36. raise IOError("dead connection")
  37. self.buf = self.buf + bytearray(moreBuf)
  38. r = self.buf[:n]
  39. self.buf = self.buf[n:]
  40. return r