跳转到主要内容

WebSockets

import { TypeScriptExample, LinkCard } from "~/components";

The Agent class installs the WebSockets capability and calls your onConnect(), onMessage(), onClose(), and onError() methods. Connections hibernate when idle, and useAgent and AgentClient from the client SDK connect to it. This page covers the Agent methods. For connection state, tags, readonly connections, and transports, refer to the WebSockets capability.

Handle connections

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 }));
	}
}

Route requests to the Agent with routeAgentRequest(), and check who is calling first. For more information, refer to Authentication.

Agent methods

Agent method What it does
onConnect(connection, ctx) Runs after a client connects. ctx.request is the upgrade request
onMessage(connection, message) Runs for each message that is not an Agents protocol frame
onClose(connection, code, reason, wasClean) Runs when a connection closes
onError(connection, error) Runs when a connection fails. The default logs and rethrows
getConnectionTags(connection, ctx) Tags a connection when it is accepted
broadcast(message, without?) Sends to every connection, except the IDs in without
getConnections(tag?), getConnection(id) Finds open connections
shouldSendProtocolMessages(connection, ctx) Return false to turn off identity, state, and MCP frames for a connection

These methods map to the WebSockets capability's handlers and options. For the Connection object, refer to Connections.

Hibernation

An idle Agent hibernates while its WebSocket connections stay open. A message wakes it, and onMessage() runs as usual. Keep anything you need after a wake in this.state, connection.state, or SQLite, not in class fields. To keep the Agent in memory instead, set static options = { hibernate: false }.

Next steps