WebSockets
WebSockets allow you to communicate in real time with your Cloudflare Workers serverless functions. For a complete example, refer to Using the WebSockets API.
The WebSocketPair returned from this constructor is an Object, with two WebSockets at keys 0
and 1
.
These WebSockets are commonly referred to as client
and server
. The below example combines Object.values
and ES6 destructuring to retrieve the WebSockets as client
and server
:
-
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(eventWebSocketEvent, callbackFunctionFunction)
- Add callback functions to be executed when an event has occurred on the WebSocket.
-
event
WebSocketEvent- 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(codenumber, reasonstring)
- Close the WebSocket connection.
-
codeinteger
optional- 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
optional- A human-readable string indicating why the WebSocket connection was closed.
-
send(messagestring | ArrayBuffer | ArrayBufferView)
- Send a message to the other WebSocket in this WebSocket pair.
-
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
-
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.
data
any - The data passed back from the other WebSocket in your pair.type
string - Defaults tomessage
.
- Mozilla Developer Network's (MDN) documentation on the WebSocket class ↗
- Our WebSocket template for building applications on Workers using WebSockets ↗