Agent 类会安装 WebSockets 功能,并调用你的 onConnect()、onMessage()、onClose() 和 onError() 方法。连接在空闲时休眠,而来自 client SDK 的 useAgent 和 AgentClient 会连接到它。本页介绍 Agent 方法。有关连接状态、tag、只读连接和 transport,请参阅 WebSockets 功能。
import { Agent } from "agents";
export class ChatAgent extends Agent {
getConnectionTags(_connection, ctx) {
const room = new URL(ctx.request.url).searchParams.get("room");
return room ? [`room:${room}`] : [];
}
onConnect(connection, ctx) {
connection.setState({ joinedAt: Date.now() });
connection.send(JSON.stringify({ type: "welcome", id: connection.id }));
}
onMessage(connection, message) {
// Send to everyone except the sender.
this.broadcast(String(message), [connection.id]);
}
onClose(connection) {
this.broadcast(JSON.stringify({ type: "left", id: connection.id }));
}
}import {
Agent,
type Connection,
type ConnectionContext,
type WSMessage,
} from "agents";
export class ChatAgent extends Agent<Env> {
getConnectionTags(_connection: Connection, ctx: ConnectionContext): string[] {
const room = new URL(ctx.request.url).searchParams.get("room");
return room ? [`room:${room}`] : [];
}
onConnect(connection: Connection, ctx: ConnectionContext) {
connection.setState({ joinedAt: Date.now() });
connection.send(JSON.stringify({ type: "welcome", id: connection.id }));
}
onMessage(connection: Connection, message: WSMessage) {
// Send to everyone except the sender.
this.broadcast(String(message), [connection.id]);
}
onClose(connection: Connection) {
this.broadcast(JSON.stringify({ type: "left", id: connection.id }));
}
}使用 routeAgentRequest() 将请求路由到 Agent,并先检查调用方身份。有关详细信息,请参阅身份验证。
| Agent 方法 | 作用 |
|---|---|
onConnect(connection, ctx) |
client 连接后运行。ctx.request 是 upgrade 请求 |
onMessage(connection, message) |
针对每条不是 Agents protocol frame 的消息运行 |
onClose(connection, code, reason, wasClean) |
连接关闭时运行 |
onError(connection, error) |
连接失败时运行。默认行为会记录日志并重新抛出错误 |
getConnectionTags(connection, ctx) |
接受连接时为其添加 tag |
broadcast(message, without?) |
向除 without 中 ID 以外的所有连接发送消息 |
getConnections(tag?), getConnection(id) |
查找 open 连接 |
shouldSendProtocolMessages(connection, ctx) |
返回 false 可关闭连接的身份、状态和 MCP frame |
这些方法对应 WebSockets 功能的 handler 和选项。有关 Connection object,请参阅连接。
空闲 Agent 会休眠,同时保持其 WebSocket 连接 open。消息会唤醒它,onMessage() 会照常运行。唤醒后需要的所有内容都应存储在 this.state、connection.state 或 SQLite 中,而不是 class field 中。要让 Agent 留在内存中,请设置 static options = { hibernate: false }。
WebSockets 功能模块
连接状态、tag、只读连接、protocol frame 和 transport。
可调用方法
让 client 通过 WebSocket 调用 Agent 上的方法。
状态
将一个值与每个已连接的 client 同步。