0

I am sending jpg images over API gateway using Websocket. As I need the image in real time on another machine.

I followed this post on the set up for the Websocket API and added a separate route sendMessage that calls the Lambda function

Setup a basic WebSocket mock in AWS ApiGateway

This is an example of the code that is running on Lambda

import base64
import boto3

api_client = boto3.client('apigatewaymanagementapi',endpoint_url='https://../test')
while not loaded:
    with open("/tmp/image.jpg", "rb") as image:
        b64string = base64.b64encode(image.read())
        firstpart, secondpart = b64string[:len(b64string)//2], b64string[len(b64string)//2:]
        api_client.post_to_connection(ConnectionId=connectionId, Data=firstpart)
        api_client.post_to_connection(ConnectionId=connectionId, Data=secondpart)
api_client.post_to_connection(ConnectionId=connectionId, Data="connected successfully!")

and this is on the machine

from websockets.sync.client import connect
import base64
from PIL import Image

with connect("wss...") as websocket:
    websocket.send(json.dumps({"action":"sendMessage","message":"scanning"}))
    while (b64image_string_1:=websocket.recv()) != "connected successfully!":
        b64image_string_2 =websocket.recv()
        b64image_string = b64image_string_1 + b64image_string_2

        f = io.BytesIO(base64.b64decode(b64image_string))
        img = Image.open(f)

Although the images will be sent over initially, I would get an error a few seconds after it runs.

botocore.errorfactory.GoneException: An error occurred (GoneException) when calling the PostToConnection operation:

I'm guessing that my set up for the websocket might be what's causing the error but I'm not sure how to fix it.

oJYW
  • 1
  • 3

1 Answers1

0

The error I got was actually from the machine itself, somehow the order of the strings was interrupted by other occasional warning/error messages from the web socket and that caused the order of the strings received to be wrong. The final line in the machine was the one that caused the error and stopped the web socket connection.

img = Image.open(f)

Image.open() could not load from the wrongly concatenated string and caused an error. The error was gone after adding checks for the order of strings received. If you get a GoneException, check your code for error that might've interrupted and disconnected the web socket connection. Not sure if this post will be useful but I'll just leave it up

oJYW
  • 1
  • 3