reading socket into buffer and then reading buffer by line
Posted: Sun Dec 29, 2019 2:38 am
I need to read from the socket and cannot use readline() as it is possible that the data does not contain line endings, in which case it will wait forever.
So I am reading into a byte string as per the code below, however I realise that using a byte string may not be as efficient as reading into a buffer which I have no experience with.
The following code works, but is the method I am using the best way to do this ?? - I need to be able to read by length, line and to pop the data off the buffer after reading it.
So I am reading into a byte string as per the code below, however I realise that using a byte string may not be as efficient as reading into a buffer which I have no experience with.
The following code works, but is the method I am using the best way to do this ?? - I need to be able to read by length, line and to pop the data off the buffer after reading it.
Code: Select all
inbuf = b''
def read():
inbuf += self.sock.read()
return len(self.inbuf)
def readbuf(size=0,pop=True,line=False):
os = 0
if line:
os=2
size = inbuf.find(b'\r\n')
if size < 0: size = 0
data = inbuf[:size]
if pop: inbuf = self.inbuf[size+os:]
return data