在API Gateway WebSocket中,可以使用同一个Lambda函数来处理不同的事件。以下是一个示例代码,其中包含了两个不同的处理程序:
import json
def connect_handler(event, context):
# 处理WebSocket连接事件
connection_id = event['requestContext']['connectionId']
print(f"New connection: {connection_id}")
# 返回连接成功的响应
return {
'statusCode': 200,
'body': 'Connected successfully.'
}
def message_handler(event, context):
# 处理WebSocket消息事件
connection_id = event['requestContext']['connectionId']
message = event['body']
print(f"Message received from {connection_id}: {message}")
# 返回消息处理结果
return {
'statusCode': 200,
'body': 'Message received and processed successfully.'
}
def disconnect_handler(event, context):
# 处理WebSocket断开连接事件
connection_id = event['requestContext']['connectionId']
print(f"Connection closed: {connection_id}")
# 返回连接关闭的响应
return {
'statusCode': 200,
'body': 'Connection closed successfully.'
}
def lambda_handler(event, context):
# 根据事件类型调用不同的处理程序
if event['requestContext']['eventType'] == 'CONNECT':
return connect_handler(event, context)
elif event['requestContext']['eventType'] == 'MESSAGE':
return message_handler(event, context)
elif event['requestContext']['eventType'] == 'DISCONNECT':
return disconnect_handler(event, context)
在上面的代码中,lambda_handler
函数是主处理程序,它通过检查事件类型来调用相应的处理程序。connect_handler
处理WebSocket连接事件,message_handler
处理WebSocket消息事件,disconnect_handler
处理WebSocket断开连接事件。
你可以根据实际需求修改处理程序中的逻辑,并根据需要返回相应的响应。
请注意,以上代码是使用Python编写的示例代码,如果你使用其他编程语言,可以根据相应的语法和框架进行修改。