WebSockets
Background
WebSockets are long-lived TCP connections that enable bi-directional, real-time communication between client and server.
Durable Objects support WebSockets — your Durable Object can act as a single point-of-coordination for WebSocket sessions, giving you full control over messages sent to and from clients, allowing you to build applications like chat rooms and multiplayer games.
For more information beyond the API reference, refer to Use WebSockets in Durable Objects.
WebSocket Methods
accept
accept()- Accepts the WebSocket connection and begins terminating requests for the WebSocket on Cloudflare’s global network. This effectively enables the Workers runtime to begin responding to and handling WebSocket requests.
addEventListener
addEventListener(eventWebSocketEvent, callbackFunctionFunction)- Add callback functions to be executed when an event has occurred on the WebSocket.
Parameters
eventWebSocketEvent- The WebSocket event (refer to Events) to listen to.
callbackFunction(messageMessage)Function- A function to be called when the WebSocket responds to a specific event.
close
close(codenumber, reasonstring)- Close the WebSocket connection.
Parameters
codeinteger- An integer indicating the close code sent by the server. This should match an option from the list of status codes provided by the WebSocket spec.
reasonstring- A human-readable string indicating why the WebSocket connection was closed.
send
send(messagestring | ArrayBuffer | ArrayBufferView)- Send a message to the other WebSocket in this WebSocket pair.
Parameters
messagestring- The message to send down the WebSocket connection to the corresponding client. This should be a string or something coercible into a string; for example, strings and numbers will be simply cast into strings, but objects and arrays should be cast to JSON strings using
JSON.stringify, and parsed in the client.
- The message to send down the WebSocket connection to the corresponding client. This should be a string or something coercible into a string; for example, strings and numbers will be simply cast into strings, but objects and arrays should be cast to JSON strings using
serializeAttachment
serializeAttachment(valueany):voidThis method is part of the Hibernatable WebSockets API.
Keeps a copy of
valuein memory (not on disk) to survive hibernation. The value can be any type supported by the structured clone algorithm, which is true of most types.If you modify
valueafter calling this method, those changes will not be retained unless you call this method again. The serialized size ofvalueis limited to 2,048 bytes, otherwise this method will throw an error. If you need larger values to survive hibernation, use the Transactional Storage API and pass the corresponding key to this method so it can be retrieved later.
deserializeAttachment
deserializeAttachment():anyThis method is part of the Hibernatable WebSockets API.
Retrieves the most recent value passed to
serializeAttachment(), ornullif none exists.
State Methods
These methods are part of the Hibernatable WebSockets API.
acceptWebSocket
acceptWebSocket(wsWebSocket, tagsArray<string>):voidAdds a WebSocket to the set attached to this Durable Object.
ws.accept()must not have been called separately. Once called, any incoming messages will be delivered by calling the Durable Object’swebSocketMessage()handler, andwebSocketClose()will be invoked upon disconnect.After calling
state.acceptWebSocket(ws), the WebSocket is accepted. Therefore, you can use itssend()andclose()methods to send messages. ItsaddEventListener()method will not ever receive any events as they will be delivered to the Durable Object.tagsare optional string tags used to look up the WebSocket withgetWebSockets(). Each tag is limited to 256 characters, and each WebSocket is limited to 10 tags associated with it.The Hibernatable WebSockets API permits a maximum of 32,768 WebSocket connections per Durable Object instance, but the CPU and memory usage of a given workload may further limit the practical number of simultaneous connections.
getWebSockets
getWebSockets(tagstring):Array<WebSocket>Gets an array of accepted WebSockets matching the given tag. Disconnected WebSockets 1 are automatically removed from the list. Calling
getWebSockets()with notagargument will return all WebSockets.1
getWebSockets()may still return websockets even afterws.close()has been called. For example, if your server-side WebSocket (the Durable Object) sends a close, but does not receive one back (and has not detected a disconnect from the client), then the connection is in theCLOSING“readyState”. The client might send more messages, so the WebSocket is technically not disconnected.
setWebSocketAutoResponse
setWebSocketAutoResponse(webSocketRequestResponsePairWebSocketRequestResponsePair):voidSets an application level auto response that does not wake hibernated WebSockets.
state.setWebSocketAutoResponsereceivesWebSocketRequestResponsePair(requeststring, responsestring)as an argument, enabling any WebSocket that was accepted viastate.acceptWebSocket()belonging to this Object to automatically reply withresponsewhen it receives the specifiedrequest.setWebSocketAutoResponse()is preferable to setting up a server for static ping/pong messages becausesetWebSocketAutoResponse()handles application level ping/pongs without waking the WebSocket from hibernation, preventing unnecessary duration charges.Both
requestandresponseare limited to 2,048 characters each.If
state.setWebSocketAutoResponse()is set without any argument, it will remove any previously set auto-response configuration. Settingstate.setWebSocketAutoResponse()without any argument will stop a Durable Object from replying withresponsefor arequest. It will also stop updating the last timestamp of arequest, but if there was any auto-response timestamp set, it will remain accessible withstate.getWebSocketAutoResponseTimestamp().
getWebSocketAutoResponse
getWebSocketAutoResponse():Object | nullGets the
WebSocketRequestResponsePair(requeststring, responsestring)currently set, ornullif there is none.Each
WebSocketRequestResponsePair(requeststring, responsestring)Object provides methods forgetRequest()andgetResponse().
getWebSocketAutoResponseTimestamp
getWebSocketAutoResponseTimestamp(wsWebSocket):Date | null- Gets the most recent
Datewhen the WebSocket received an auto-response request, ornullif the given WebSocket never received an auto-response request.
- Gets the most recent
Handler Methods
These methods are part of the Hibernatable WebSockets API.
webSocketMessage
webSocketMessage(wsWebSocket, messageString | ArrayBuffer):voidCalled by the system when an accepted WebSocket receives a message.
This method can be
async.This method is not called for WebSocket control frames. The system will respond to an incoming WebSocket protocol ping automatically without interrupting hibernation.
webSocketClose
webSocketClose(wsWebSocket, codenumber, reasonstring, wasCleanboolean):voidCalled by the system when a WebSocket is closed.
wasClean()is true if the connection closed cleanly, false otherwise.This method can be
async.
webSocketError
webSocketError(wsWebSocket, errorany):voidCalled by the system when any non-disconnection related errors occur.
This method can be
async.
WebSocketEvent
close- An event indicating the WebSocket has closed.
error- An event indicating there was an error with the WebSocket.
message- An event indicating a new message received from the client, including the data passed by the client.
Types
Message
dataany- The data passed back from the other WebSocket in your pair.typestring- Defaults tomessage.