

# 在后端服务中使用 `@connections` 命令


您的后端服务可以使用以下 WebSocket 连接 HTTP 请求向连接的客户端发送回调消息、获取连接信息或断开客户端连接。

**重要**  
这些请求使用 [IAM 授权](apigateway-websocket-control-access-iam.md)，因此您必须使用[签名版本 4 (SigV4)](https://docs.amazonaws.cn/IAM/latest/UserGuide/create-signed-request.html) 对其进行签名。为此，您可以使用 API Gateway 管理 API。有关更多信息，请参阅 [ApiGatewayManagementApi](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/apigatewaymanagementapi.html)。

在以下命令中，您需要将 `{api-id}` 替换为实际的 API ID，该 ID 显示在 API Gateway 控制台中或由 Amazon CLI [create-api](https://docs.amazonaws.cn/cli/latest/reference/apigatewayv2/create-api.html) 命令返回。在使用此命令之前，必须先建立连接。

要向客户端发送回调消息，请使用：

```
POST https://{api-id}.execute-api.us-east-1.amazonaws.com/{stage}/@connections/{connection_id}
```

您可以通过使用 `[Postman](https://www.postman.com/)` 或通过调用 `[awscurl](https://github.com/okigan/awscurl)` 来测试此请求，如以下示例所示：

```
awscurl --service execute-api -X POST -d "hello world" https://{prefix}.execute-api.us-east-1.amazonaws.com/{stage}/@connections/{connection_id}
```

您需要对命令进行 URL 编码，如以下示例所示：

```
awscurl --service execute-api -X POST -d "hello world" https://aabbccddee.execute-api.us-east-1.amazonaws.com/prod/%40connections/R0oXAdfD0kwCH6w%3D
```

要获取客户端的最新连接状态，请使用：

```
GET https://{api-id}.execute-api.us-east-1.amazonaws.com/{stage}/@connections/{connection_id}
```

要断开客户端连接，请使用：

```
DELETE https://{api-id}.execute-api.us-east-1.amazonaws.com/{stage}/@connections/{connection_id}
```

您可以通过在集成中使用 `$context` 变量来动态构建回调 URL。例如，如果您将 Lambda 代理集成与 `Node.js` Lambda 函数一起使用，则可以按如下方式构建 URL 并向连接的客户端发送消息：

```
import {
  ApiGatewayManagementApiClient,
  PostToConnectionCommand,
} from "@aws-sdk/client-apigatewaymanagementapi";

export const handler = async (event) => {
  const domain = event.requestContext.domainName;
  const stage = event.requestContext.stage;
  const connectionId = event.requestContext.connectionId;
  const callbackUrl = `https://${domain}/${stage}`;
  const client = new ApiGatewayManagementApiClient({ endpoint: callbackUrl });

  const requestParams = {
    ConnectionId: connectionId,
    Data: "Hello!",
  };

  const command = new PostToConnectionCommand(requestParams);

  try {
    await client.send(command);
  } catch (error) {
    console.log(error);
  }

  return {
    statusCode: 200,
  };
};
```

如果您为 WebSocket API 使用自定义域名，请从函数代码中移除 `stage` 变量。

发送回调消息时，您的 Lambda 函数必须有权调用 API Gateway 管理 API。如果您在连接建立之前或客户端断开连接后发布消息，则可能会收到一条包含 `GoneException` 的错误。