add counter app in python

This commit is contained in:
Ethan Buchman
2015-12-06 18:18:13 -05:00
parent 4a0469d3ec
commit bb4a58aa0a
6 changed files with 421 additions and 0 deletions

View File

@ -0,0 +1,31 @@
# Simple read() method around a bytearray
class BytesReader():
def __init__(self, b):
self.buf = b
def read(self, n):
if len(self.buf) < n:
# TODO: exception
return
r = self.buf[:n]
self.buf = self.buf[n:]
return r
# Buffer bytes off a tcp connection and read them off in chunks
class ConnReader():
def __init__(self, conn):
self.conn = conn
self.buf = bytearray()
# blocking
def read(self, n):
while n > len(self.buf):
moreBuf = self.conn.recv(1024)
if not moreBuf:
raise IOError("dead connection")
self.buf = self.buf + bytearray(moreBuf)
r = self.buf[:n]
self.buf = self.buf[n:]
return r