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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
What type of object is
client[0]? Assuming it is asocketobject from the standard library, thenrecv()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,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: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.