I need to read data from socket byte by byte. I try to do with this code:
lineF = ''
for DataByte in client[0].recv(1):
lineF += DataByte
result lineF must be an data string.
What type of object is client[0]? Assuming it is a socket object from the standard library, then recv() already gives you a bytestring. If you want it as a text string, you would use the .decode() with whatever encoding whoever is sending you the data is using - eg,
data = client[0].recv(1).decode('utf-8')
EDIT: in the case that, per your comment below, you don't know the length of the stream in advance, you need to keep reading until the data comes back empty. The built-in iter() helps with this:
def read_socket():
return client[0].recv(1)
data = b''.join(iter(read_socket, b''))
Also, if this is the only reason for reading a byte at a time - you can, and probably should, use a larger buffer size. If there's fewer bytes in the stream than the buffer can hold, it will just give you those bytes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With