3

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.

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes. recv() gives me a bytestring. I can get whole string using client[0].recv(1024) but i don't khow string length. It may be various. I need to get all data byte by byte and then get a bytestring.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.