以下是一个使用API Gateway Websockets的示例代码,当接收到数据后关闭客户端连接:
const AWS = require('aws-sdk');
const apiGatewayManagementApi = new AWS.ApiGatewayManagementApi({endpoint: 'YOUR_API_GATEWAY_ENDPOINT'});
exports.handler = async (event) => {
const connectionId = event.requestContext.connectionId;
try {
// 接收到数据后关闭客户端连接
await apiGatewayManagementApi.postToConnection({
ConnectionId: connectionId,
Data: 'Received your message. Closing the connection.'
}).promise();
// 关闭客户端连接
await apiGatewayManagementApi.deleteConnection({
ConnectionId: connectionId
}).promise();
return {
statusCode: 200,
body: 'Connection closed.'
};
} catch (error) {
console.error('Failed to close connection:', error);
return {
statusCode: 500,
body: 'Failed to close connection.'
};
}
};
上述代码使用AWS SDK来与API Gateway Management API进行交互,其中YOUR_API_GATEWAY_ENDPOINT
需要替换为你的API Gateway的端点。
在代码中,首先获取客户端连接的ID,然后使用postToConnection
方法向客户端发送一条消息,表示接收到数据后即将关闭连接。接着,使用deleteConnection
方法关闭客户端连接。最后,根据操作结果返回相应的状态码和消息。
请注意,为了使用上述代码,你需要安装并配置AWS SDK。