def msg_recv(conn, sendfunc, closefunc):
'''
Function msg_recv reads null-delimited series of bytes from `conn`, which
is a socket. Each series of bytes is then de-serialized into a json object,
and `sendfunc` is called with that json object.
`closefunc` is called if/when the socket `conn` is closed.
'''
buf = bytes()
while True:
try:
data = conn.recv(8192)
# No data means the connection is closed
if not data:
closefunc()
return
inbuf = buf + data
if SEP in inbuf:
parts = inbuf.split(SEP)
# logging.debug("Length of parts: {}".format(len(parts)))
tosend = [parts[0]]
for p in parts[1:-1]:
tosend.append(p)
buf = parts[-1]
for msg in tosend:
m = gzip.decompress(msg)
m = m.decode('utf-8')
logging.debug("Msg: {}".format(m[:150]+'...' if len(m) > 150 else m))
obj = json.loads(m)
sendfunc(obj)
else:
buf += data
except Exception as e:
logging.exception(e)
评论列表
文章目录