WebSockets allow you to communicate in real time with your Cloudflare Workers serverless functions. For a complete example, refer to Using the WebSockets API.
Note
If your application needs to coordinate among multiple WebSocket connections, such as a chat room or game match, you will need clients to send messages to a single-point-of-coordination. Durable Objects provide a single-point-of-coordination for Cloudflare Workers, and are often used in parallel with WebSockets to persist state over multiple clients and connections. In this case, refer to Durable Objects to get started, and prefer using the Durable Objects' extended WebSockets API.
// { 0: <WebSocket>, 1: <WebSocket> }
let websocketPair = new WebSocketPair();
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
:
let [client, server] = Object.values(new WebSocketPair());
accept()
addEventListener(eventWebSocketEvent, callbackFunctionFunction)
event
WebSocketEvent
callbackFunction(messageMessage)
Function
close(codenumber, reasonstring)
codeinteger
optional
reasonstring
optional
send(messagestring | ArrayBuffer | ArrayBufferView)
messagestring
JSON.stringify
, and parsed in the client.close
error
message
Note
WebSocket messages received by a Worker have a size limit of 1 MiB (1048576). If a larger message is sent, the WebSocket will be automatically closed with a 1009
"Message is too large" response.
data
any - The data passed back from the other WebSocket in your pair.type
string - Defaults to message
.RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4