Search code examples
pythonsocketsio

How to keep received image from the socket in the buffer


I am working on the project that receives an image from a remote computer through sockets. As I don`t know what is going to be the size of the image I am receiving the image chunk by chunk, and saving to io.BytesIO()

    def imgdisplayer():
        nonlocal conn, display
        with io.BytesIO() as f:
            while True:
                bytes = conn.recv(1024)
                if not bytes: break
                f.write(bytes)
            imgobj = pickle.loads(f)

But my code is not working, I guess I have a misuderstanding of the io.BytesIO The error being risen here is that:

TypeError: a bytes-like object is required, not '_io.BytesIO'

Can someone help on how I can fix the problem or suggest another way to do the procedure?


Solution

  • BytesIO is a file-like object. You should use the getvalue() method if you need its value:

    imgobj = pickle.loads(f.getvalue())