跳转到内容
本站为社区维护的非官方中文翻译,与 Cloudflare, Inc. 无关联。本站不提供账户登录,请勿在任何非官方站点输入您的 Cloudflare 账户信息。官方文档:developers.cloudflare.com

WebSockets

最后更新 查看 MarkdownAgent 设置

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 方法

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 }。

后续步骤

状态

将一个值与每个已连接的 client 同步。

这篇文档对您有帮助吗?