0Pricing
Serverless Backend with AWS Lambda & API Gateway · 课时

用于实时通信的 WebSocket API

使用 API Gateway WebSocket API 构建双向实时连接。了解连接、断开连接和消息路由,以及如何将数据推送回客户端。

用于实时通信的 WebSocket API 是 CoddyKit 上的免费 Serverless Backend with AWS Lambda & API Gateway 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Serverless Backend with AWS Lambda & API Gateway 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Serverless Backend with AWS Lambda & API Gateway 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why WebSockets?

REST APIs are request/response — the server cannot push. For chat, live dashboards, or notifications you need a persistent two-way channel. API Gateway WebSocket APIs provide exactly that.

The Three Built-in Routes

A WebSocket API has special routes:

  • $connect when a client connects
  • $disconnect when it leaves
  • $default for unmatched messages

Route Selection Expression

Custom routes are chosen by a route selection expression, usually a field in the incoming JSON such as $request.body.action.

{
  "action": "sendMessage",
  "data": "hello"
}

Handling $connect

The $connect handler receives a unique connectionId. Store it (e.g. in DynamoDB) so you can message that client later.

exports.handler = async (event) => {
  const id = event.requestContext.connectionId;
  await save(id);
  return { statusCode: 200 };
};

Handling $disconnect

On disconnect, remove the stored connectionId so you do not try to message a dead client.

exports.handler = async (event) => {
  await remove(event.requestContext.connectionId);
  return { statusCode: 200 };
};

Pushing Messages to a Client

To send data back, call the management API with the target connectionId.

const api = new ApiGatewayManagementApi({ endpoint });
await api.postToConnection({
  ConnectionId: id,
  Data: JSON.stringify({ msg: "hi" })
});

Broadcasting to Many Clients

To broadcast, loop over all stored connectionIds and post to each. Remove any that return a 410 Gone status — those clients have disconnected.

Authorizing Connections

Attach a Lambda authorizer to the $connect route to validate a token before the connection is accepted, rejecting unauthorized clients up front.

Connection Lifetime and Limits

WebSocket connections last up to 2 hours, with a 10-minute idle timeout. Clients should reconnect when dropped, and you should handle stale connectionIds gracefully.

Pricing Model

You pay for messages transferred and for connection-minutes, not for idle request count. This makes WebSocket APIs cost-effective for bursty real-time traffic.

When to Use WebSockets

Reach for WebSocket APIs when you need:

  • Live chat or collaboration
  • Real-time dashboards
  • Server-initiated notifications

For simple request/response, stick with REST or HTTP APIs.

Quick Check

Test your WebSocket API knowledge.

Recap

You learned real-time APIs:

  • WebSocket APIs add two-way communication
  • $connect, $disconnect, $default plus custom routes
  • Store connectionIds and push via postToConnection
  • Authorize on $connect; handle stale connections

常见问题解答

「用于实时通信的 WebSocket API」课时是免费的吗?

是的 — 「用于实时通信的 WebSocket API」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Serverless Backend with AWS Lambda & API Gateway 课程的其余内容,请升级到 CoddyKit PRO。 Serverless Backend with AWS Lambda & API Gateway 课程共包含 4 节课。

「用于实时通信的 WebSocket API」这节课中我会学到什么?

使用 API Gateway WebSocket API 构建双向实时连接。了解连接、断开连接和消息路由,以及如何将数据推送回客户端。 你通过在浏览器中直接运行的动手代码来练习 Serverless Backend with AWS Lambda & API Gateway,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Serverless Backend with AWS Lambda & API Gateway 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Serverless Backend with AWS Lambda & API Gateway 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「用于实时通信的 WebSocket API」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Serverless Backend with AWS Lambda & API Gateway 课中编写并运行代码吗?

能。每节 Serverless Backend with AWS Lambda & API Gateway 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 缓存与限流
  2. 请求/响应转换
  3. 自定义域名与边缘优化
  4. 用于实时通信的 WebSocket API
← 返回 Serverless Backend with AWS Lambda & API Gateway