I want to send a message to a websocket client when it connects to the server on AWS lambda and API gateway. Currently, I use wscat as a client. Since the response ‘connected’ is not shown on the wscat console when I connect to the server, I added post_to_connection to send a message ‘hello world’ to the client. However, it raises GoneException.
An error occurred (GoneException) when calling the PostToConnection operation
How can I solve this problem and send some message to wscat when connecting to the server?
My python code is below. I use Python 3.8.5.
import os import boto3 import botocore dynamodb = boto3.resource('dynamodb') connections = dynamodb.Table(os.environ['TABLE_NAME']) def lambda_handler(event, context): domain_name = event.get('requestContext',{}).get('domainName') stage = event.get('requestContext',{}).get('stage') connection_id = event.get('requestContext',{}).get('connectionId') result = connections.put_item(Item={ 'id': connection_id }) apigw_management = boto3.client('apigatewaymanagementapi', endpoint_url=F"https://{domain_name}/{stage}") ret = "hello world"; try: _ = apigw_management.post_to_connection(ConnectionId=connection_id, Data=ret) except botocore.exceptions.ClientError as e: print(e); return { 'statusCode': 500, 'body': 'something went wrong' } return { 'statusCode': 200, "body": 'connected'};
Advertisement
Answer
Self-answer: you cannot post_to_connection to the connection itself in onconnect.