WebSockets 与实时通信
使用 Cloudflare Workers 和 WebSockets 实现实时应用,打造交互式体验
WebSockets 与实时通信 是 CoddyKit 上的免费 Edge Computing with Cloudflare Workers & Deno 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Edge Computing with Cloudflare Workers & Deno 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Edge Computing with Cloudflare Workers & Deno 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Real-time Apps with WebSockets
What are WebSockets? They enable real-time, two-way communication between a client (like your browser) and a server. Unlike traditional HTTP requests, WebSockets keep a persistent connection open.
This is perfect for applications needing instant updates, like chat apps, live dashboards, or online games.
HTTP vs. WebSocket Connection
Traditional HTTP is stateless and request-response based. Each action needs a new request from the client.
WebSockets, however, establish a single, long-lived connection. Once open, both client and server can send messages anytime without waiting for a request.
- HTTP: Client requests, server responds, connection closes.
- WebSocket: Client requests upgrade, server approves, connection stays open.
The WebSocket Upgrade
Before a WebSocket connection is established, an initial HTTP request is made. The client sends an "Upgrade" header, indicating its desire to switch protocols.
If the server supports WebSockets, it responds with an "101 Switching Protocols" status code, upgrading the connection from HTTP to WebSocket protocol. This is known as the WebSocket Handshake.
Cloudflare Workers & WebSockets
Cloudflare Workers are ideal for handling WebSockets at the edge. They can act as the server endpoint, managing connections and processing real-time messages directly where your users are.
Workers provide a WebSocketPair API to easily upgrade an incoming HTTP request into a WebSocket connection, simplifying the handshake process.
Worker WebSocket Upgrade
Let's create a Worker that accepts an incoming WebSocket connection. We'll use new WebSocketPair() to manage the connection.
Try running this example. To test, you'd typically connect using a WebSocket client (e.g., a browser's developer console or a dedicated tool).
export default {
async fetch(request) {
const upgradeHeader = request.headers.get('Upgrade');
if (!upgradeHeader || upgradeHeader !== 'websocket') {
return new Response('Expected Upgrade: websocket', { status: 426 });
}
const { 0: client, 1: server } = new WebSocketPair();
server.accept(); // Accept the WebSocket connection
server.addEventListener('message', event => {
console.log('Received message:', event.data);
// We'll add logic to send messages back soon!
});
server.addEventListener('close', event => {
console.log('WebSocket closed:', event.code, event.reason);
});
server.addEventListener('error', event => {
console.error('WebSocket error:', event.message);
});
return new Response(null, {
status: 101,
webSocket: client,
});
},
};WebSocket Event Listeners
Once a WebSocket connection is established, you can listen for various events on the server-side WebSocket object:
'open': Connection successfully established.'message': A message is received from the client. The message data is inevent.data.'close': The connection is closed by either side.'error': An error occurred on the connection.
These allow your Worker to react dynamically to client interactions.
Echoing Messages
In the previous code, we added an event listener for 'message'. Let's extend it to ensure the Worker echoes back any message it receives.
The server.send(message) method allows the Worker to send data back to the connected client. This creates a simple "echo" server.
export default {
async fetch(request) {
const upgradeHeader = request.headers.get('Upgrade');
if (!upgradeHeader || upgradeHeader !== 'websocket') {
return new Response('Expected Upgrade: websocket', { status: 426 });
}
const { 0: client, 1: server } = new WebSocketPair();
server.accept();
server.addEventListener('message', event => {
const message = event.data;
console.log('Received message:', message);
// Echo the message back to the client
server.send(`Echo from Worker: ${message}`);
});
server.addEventListener('close', event => {
console.log('WebSocket closed');
});
server.addEventListener('error', event => {
console.error('WebSocket error:', event);
});
return new Response(null, {
status: 101,
webSocket: client,
});
},
};Real-time Broadcasting
An echo server is a good start, but many real-time apps need to send messages to multiple connected clients (broadcasting).
For example, in a chat application, when one user sends a message, all other users in the chat room should receive it.
Cloudflare Workers, being stateless by default, need a mechanism to manage these connections across requests. This is where Durable Objects become incredibly useful for maintaining state and managing multiple WebSocket connections for a shared resource.
(We'll explore Durable Objects in a later lesson!)
Securing WebSockets
Just like HTTP, WebSocket connections should be secured. Always use wss:// (WebSocket Secure) instead of ws://.
wss:// connections are encrypted using TLS/SSL, preventing eavesdropping and tampering. Cloudflare Workers handle TLS termination automatically, so your connections are secured by default when deployed.
- Use
wss://for production. - Implement authentication/authorization.
- Validate all incoming messages.
Check Your Understanding
Consider a Cloudflare Worker that aims to establish a WebSocket connection with a client.
Recap: WebSockets at the Edge
Great job! You've learned how to implement real-time communication with WebSockets using Cloudflare Workers.
- WebSockets enable persistent, two-way communication.
- Workers use
WebSocketPairand101 Switching Protocolsfor the handshake. - Event listeners (
'message','close','error') manage connection lifecycle. - Always use
wss://for secure connections.
In future lessons, we'll dive into Durable Objects to manage state across multiple WebSocket connections for advanced real-time applications.
常见问题解答
「WebSockets 与实时通信」课时是免费的吗?
是的 — 「WebSockets 与实时通信」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Edge Computing with Cloudflare Workers & Deno 课程的其余内容,请升级到 CoddyKit PRO。 Edge Computing with Cloudflare Workers & Deno 课程共包含 4 节课。
「WebSockets 与实时通信」这节课中我会学到什么?
使用 Cloudflare Workers 和 WebSockets 实现实时应用,打造交互式体验 你通过在浏览器中直接运行的动手代码来练习 Edge Computing with Cloudflare Workers & Deno,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Edge Computing with Cloudflare Workers & Deno 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Edge Computing with Cloudflare Workers & Deno 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「WebSockets 与实时通信」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Edge Computing with Cloudflare Workers & Deno 课中编写并运行代码吗?
能。每节 Edge Computing with Cloudflare Workers & Deno 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- WebSockets 与实时通信
- 队列与异步任务
- 服务绑定与集成
- Cron 触发器与定时 Workers