How can I read a byte array from a socket in Python

12,906

You're already doing exactly what you asked.

data is the bytes received from the socket, as-is.

In Python 3.x, it's a bytes object, which is just an immutable version of bytearray. In Python 2.x, it's a str object, since str and bytes are the same type. But either way, that type is just a string of bytes.

If you want to access those bytes as numbers rather than characters: In Python 3.x, just indexing or iterating the bytes will do that, but in Python 2.x, you have to call ord on each character. That's easy.

Or, in both versions, you can just call data = bytearray(data), which makes a mutable bytearray copy of the data, which gives you numbers rather than characters when you index or iterate it.

So, for example, let's say we want to write the decimal values of each bytes on a separate line to a text file (a silly thing to do, but it demonstrates the ideas) in Python 2.7:

data = client_sock.recv(1024)
with open('textfile.txt', 'a') as f:
    for ch in data:
        f.write('{}\n'.format(ord(ch)))
Share:
12,906
user2426316
Author by

user2426316

Updated on June 04, 2022

Comments

  • user2426316
    user2426316 almost 2 years

    I am using bluetooth to send a 16-byte byte-array to a Python server. Basically what I would like to achieve is read the byte-array as it is. How can I do that in Python.

    What I am doing right now is reading a string since that is the only way I know how I can read data from a socket. This is my code from the socket in python

    data = client_sock.recv(1024)
    

    Where data is the string. Any ideas?

  • user2426316
    user2426316 over 10 years
    thanks, that is great! would it also be possible to use the ord function to take 4 bytes instead of one and to represent those 4 bytes as a float?
  • abarnert
    abarnert over 10 years
    @user2426316: No, the ord function can just get you each value as an integer from 0-255; you'd have to figure out how to construct a float out of those four integers manually, which you don't want to do. You're probably looking for struct.unpack.
  • abarnert
    abarnert over 10 years
    That does sound like what he ultimately wants, from his comments, but it definitely isn't the way to read the bytes as-is.
  • MJ Howard
    MJ Howard over 10 years
    True, I really meant it as an expansion of your answer. The only thing I might add is (potential) endian-ness issues with multi-byte value conversion, but if they're doing binary data over a network, they should already be aware of those issues.