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

byte, python, sockets, string

Solution

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)))

Problem

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?

Original source