You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/content/docs/durable-objects/best-practices/websockets.mdx
+138-9Lines changed: 138 additions & 9 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -51,7 +51,8 @@ To use WebSockets with Durable Objects, you first need to proxy the `request` ob
51
51
52
52
If an event occurs for a hibernated Durable Object's corresponding handler method, it will return to memory. This will call the Durable Object's constructor, so it is best to minimize work in the constructor when using WebSocket hibernation.
# If the client closes the connection, the runtime will invoke the webSocketClose() handler.
177
+
ws.close(code, "Durable Object is closing WebSocket")
178
+
```
179
+
</TabItem>
180
+
</Tabs>
140
181
141
182
Similar to the [WebSocket Standard API example](/durable-objects/examples/websocket-server/), to execute this code, configure your Wrangler file to include a Durable Object [binding](/durable-objects/get-started/#4-configure-durable-object-bindings) and [migration](/durable-objects/reference/durable-objects-migrations/) based on the <GlossaryTooltipterm="namespace">namespace</GlossaryTooltip> and class name chosen previously.
142
183
@@ -192,7 +233,8 @@ Both Workers and Durable Objects are billed, in part, based on the number of req
# This example will refer to a single Durable Object instance, since the name "foo" is
341
+
# hardcoded
342
+
stub =self.env.WEBSOCKET_SERVER.getByName("foo")
343
+
344
+
# The Durable Object's fetch handler will accept the server side connection and return
345
+
# the client
346
+
returnawait stub.fetch(request)
347
+
348
+
return Response(
349
+
None,
350
+
status=400,
351
+
status_text="Bad Request",
352
+
headers={
353
+
"Content-Type": "text/plain",
354
+
},
355
+
)
356
+
```
357
+
</TabItem>
358
+
</Tabs>
276
359
277
360
Each WebSocket server in this example is represented by a Durable Object. This WebSocket server creates a single WebSocket connection and responds to all messages over that connection with the total number of accepted WebSocket connections. In the Durable Object's fetch handler we create client and server connections and add event listeners for relevant event types.
To execute this code, configure your Wrangler file to include a Durable Object [binding](/durable-objects/get-started/#4-configure-durable-object-bindings) and [migration](/durable-objects/reference/durable-objects-migrations/) based on the <GlossaryTooltipterm="namespace">namespace</GlossaryTooltip> and class name chosen previously.
0 commit comments