Search code examples
pythonc++qtwebsockettornado

How to transfer .png or .jpg file over websocket in Tornado


I'm new to Tornado and web services in general. In my application, I've Qt/c++ client and python Tornado on server side. The Qt client sends commands in the form of text messages. On server side the 'on_message' method receives the message, parses it and calls the relevant script to generate .png image. Now, I want to send this image back to client along with the short description of the image. How do I do this on server and client side? Pointer to any online example would be also helpful. Thanks.


Solution

  • You can encode the image into Base64 format and send the message in JSON format, together with the description.

    On your server you do

    import base64
    
    ws_client.write_message({
        "img": base64.b64encode(img_data),
        "desc": img_description,
    })
    

    And on your client, you parse the JSON string and decode the Base64 encoded image to get the data.