在 AWS lambda 和 API 网关上调用 post_to_connection 时出现 GoneException

nem*_*emy 9 python websocket aws-lambda aws-api-gateway

我想在 Websocket 客户端连接到 AWS lambda 和 API 网关上的服务器时向其发送消息。目前,我使用 wscat 作为客户端。由于当我连接到服务器时,wscat 控制台上未显示响应“已连接”,因此我添加了 post_to_connection 来向客户端发送消息“hello world”。但是,它会引发 GoneException。

调用 PostToConnection 操作时发生错误 (GoneException)

如何解决这个问题并在连接到服务器时向 wscat 发送一些消息?

我的Python代码如下。我使用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'};
Run Code Online (Sandbox Code Playgroud)

nem*_*emy 18

自我回答:您不能在 onconnect 中将 post_to_connection 发送到连接本身。