WebSockets والتحديث الفوري
نفّذ تطبيقات فورية باستخدام Cloudflare Workers وWebSockets لتوفير تجارب تفاعلية
WebSockets والتحديث الفوري درس مجاني في Edge Computing with Cloudflare Workers & Deno على CoddyKit. هذا هو الدرس 1 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في 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 والتحديث الفوري» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة 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 مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ Edge Computing with Cloudflare Workers & Deno؟
لا تُشترط خبرة سابقة. Edge Computing with Cloudflare Workers & Deno على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 1 من أصل 4.
كم من الوقت يستغرق درس «WebSockets والتحديث الفوري»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس Edge Computing with Cloudflare Workers & Deno هذا؟
نعم. كل درس في Edge Computing with Cloudflare Workers & Deno يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- WebSockets والتحديث الفوري
- قوائم الانتظار والمهام غير المتزامنة
- ارتباطات الخدمات والتكاملات
- مشغلات Cron وWorkers المجدولة