websocket send binary data

Issue #272 resolved
Wenjie Wu created an issue

hi John I still haven't solved the problem about “send binary” and need your help.

When I use websocket-client (Python client) to send binary data to MicroBlocks(1.1.46), the MicroBlocks websocket server received 'BM6'. It seems like something was cut off.

when I send b'hello' , the MicroBlocks websocket server received 'hello', MicroBlocks tell me the message type is binary, but the content seems to be a string. Possible problem caused by Python client but I can't find the reason(The Python MQTT client issue seems to be the same), if you'd like to test it for me, I'd appreciate it.

# pip install pillow websocket-client

from websocket import create_connection
from PIL import Image

size = (16, 16)
img = Image.new('RGB', size, "black")
pixels = img.load()
for i in range(img.size[0]):
    for j in range(img.size[1]):
        if i == j:
            pixels[i,j] = (255, 0, 0)
        else:
            pixels[i,j] = (0, 255, 0)

img.save("image.bmp")

client = create_connection("ws://192.168.21.133:81")
with open('image.bmp', 'rb') as f: # opening a binary file
    content = f.read()

# bytearray(b'hello') # is ok
client.send_binary(bytearray(content))

Comments (10)

  1. John Maloney repo owner

    Sure, I can test.

    Just checking: did you remember to install the new firmware? The "about" dialog should report "Firmware v145".

  2. John Maloney repo owner

    I tested websocket binary and it seems to be working.

    One thing might be confusing your test -- a disconnect message is delivered immediately after the data is sent. Here is the sequence of messages with their payloads:

    connected 1 bytes
    binary message 822 bytes
    disconnected 0 bytes
    

    You can slow things down by adding sleep() calls to the Python program:

    # pip install pillow websocket-client
    
    from websocket import create_connection
    from PIL import Image
    from time import sleep
    
    size = (16, 16)
    img = Image.new('RGB', size, "black")
    pixels = img.load()
    for i in range(img.size[0]):
        for j in range(img.size[1]):
            if i == j:
                pixels[i,j] = (255, 0, 0)
            else:
                pixels[i,j] = (0, 255, 0)
    
    img.save("image.bmp")
    
    client = create_connection("ws://192.168.0.156:81")
    with open('image.bmp', 'rb') as f: # opening a binary file
        content = f.read()
    
    sleep(2)
    client.send_binary(bytearray(content))
    sleep(2)
    

    Here is the MicroBlocks code I used:

    scriptImage1031617.png

  3. Wenjie Wu reporter

    Just checking: did you remember to install the new firmware? The "about" dialog should report "Firmware v145".

    This is what caused it!

    Thank you for helping test.

  4. Log in to comment