@@ -159,6 +159,8 @@ class MyAgent extends Agent<Env, MyState> {
159159
160160### WebSocket API
161161
162+ The WebSocket API allows you to accept and manage WebSocket connections made to an Agent.
163+
162164#### Connection
163165
164166Represents a WebSocket connection to an Agent.
@@ -191,30 +193,32 @@ interface Connection<State = unknown> {
191193
192194``` ts
193195// Example of handling WebSocket messages
194- async onMessage (connection : Connection , message : WSMessage ) {
195- if (typeof message === ' string' ) {
196- try {
197- // Parse JSON message
198- const data = JSON .parse (message );
199-
200- if (data .type === ' update' ) {
201- // Update connection-specific state
202- connection .setState ({ ... connection .state , lastActive: Date .now () });
203-
204- // Update global Agent state
205- this .setState ({
206- ... this .state ,
207- connections: this .state .connections + 1
208- });
209-
210- // Send response back to this client only
211- connection .send (JSON .stringify ({
212- type: ' updated' ,
213- status: ' success'
214- }));
196+ export class YourAgent extends Agent {
197+ async onMessage(connection : Connection , message : WSMessage ) {
198+ if (typeof message === ' string' ) {
199+ try {
200+ // Parse JSON message
201+ const data = JSON .parse (message );
202+
203+ if (data .type === ' update' ) {
204+ // Update connection-specific state
205+ connection .setState ({ ... connection .state , lastActive: Date .now () });
206+
207+ // Update global Agent state
208+ this .setState ({
209+ ... this .state ,
210+ connections: this .state .connections + 1
211+ });
212+
213+ // Send response back to this client only
214+ connection .send (JSON .stringify ({
215+ type: ' updated' ,
216+ status: ' success'
217+ }));
218+ }
219+ } catch (e ) {
220+ connection .send (JSON .stringify ({ error: ' Invalid message format' }));
215221 }
216- } catch (e ) {
217- connection .send (JSON .stringify ({ error: ' Invalid message format' }));
218222 }
219223 }
220224}
0 commit comments