WebSockets مع واجهات RESTful البرمجية
صمّموا بنيات هجينة تكمّل فيها WebSockets واجهات REST البرمجية التقليدية لتوفير تحديثات ديناميكية.
WebSockets مع واجهات RESTful البرمجية درس مجاني في WebSockets & Realtime Systems Programming على CoddyKit. هذا هو الدرس 1 من أصل 3. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في WebSockets & Realtime Systems Programming، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة WebSockets & Realtime Systems Programming 3 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
Why Hybrid Architectures?
Welcome! In this lesson, we'll explore how to combine two powerful web communication tools: RESTful APIs and WebSockets.
While both facilitate communication, they excel in different areas. A hybrid approach leverages their individual strengths to build robust, dynamic applications.
- REST for initial data loading and traditional resource management.
- WebSockets for instant, real-time data updates.
RESTful APIs: The Foundation
RESTful APIs are a cornerstone of modern web development. They follow a request-response model, typically over HTTP.
Think of them as ordering from a menu: you make a specific request (e.g., "Get me all products"), and the server responds with the data. They are great for:
- Fetching static or infrequently changing data.
- Performing one-time actions (creating, updating, deleting resources).
- Initial page loads with existing information.
WebSockets: Real-time Dynamics
WebSockets, as you've learned, provide a persistent, full-duplex connection. This means data can flow simultaneously in both directions, without constant new requests.
They are like a live chat: once connected, messages can be sent back and forth instantly. This makes them perfect for:
- Live data feeds (stock prices, sports scores).
- Real-time notifications (new messages, activity alerts).
- Collaborative applications (document editing).
Complementary, Not Competing
It's important to see REST and WebSockets as complementary tools, not competitors. They solve different problems efficiently.
Combining them allows you to handle both traditional data operations and real-time interactions within the same application, leading to a richer user experience.
A well-designed hybrid system uses each protocol where it makes the most sense.
The Hybrid Workflow
A common hybrid workflow looks like this:
- Client loads: Makes initial requests via REST to fetch existing data (e.g., a list of items).
- Client connects: Establishes a WebSocket connection for real-time updates related to that data.
- Server updates: Pushes new data or changes via WebSocket as they occur.
- Client interacts: Might use REST for specific resource actions (e.g., 'mark item as complete') and receive confirmation/updates via WebSocket.
Server: REST Endpoint for Data
First, let's set up a simple Node.js server with an Express REST endpoint. This endpoint will serve our initial list of 'items'.
This demonstrates how a client would initially fetch existing data. (Remember to npm install express)
const express = require('express');
const app = express();
const PORT = 3000;
let items = [
{ id: 1, name: 'Item A', status: 'pending' },
{ id: 2, name: 'Item B', status: 'completed' }
];
// REST endpoint to get all items
app.get('/api/items', (req, res) => {
res.json(items);
});
app.listen(PORT, () => {
console.log(`REST server listening on port ${PORT}`);
});
Server: Adding WebSocket Updates
Now, let's extend our server to include a WebSocket. This WebSocket will push real-time updates whenever an item's status changes.
We use the ws library and integrate it with our existing Express server. (Remember to npm install ws)
const express = require('express');
const WebSocket = require('ws');
const http = require('http');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
const PORT = 3000;
let items = [
{ id: 1, name: 'Item A', status: 'pending' },
{ id: 2, name: 'Item B', status: 'completed' }
];
// REST endpoint to get all items
app.get('/api/items', (req, res) => {
res.json(items);
});
// WebSocket connection handling
wss.on('connection', ws => {
console.log('Client connected via WebSocket');
// Simulate an item update every 5 seconds
const interval = setInterval(() => {
const itemToUpdate = items[Math.floor(Math.random() * items.length)];
itemToUpdate.status = itemToUpdate.status === 'pending' ? 'completed' : 'pending';
const updateMessage = JSON.stringify({ type: 'itemUpdate', item: itemToUpdate });
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(updateMessage);
}
});
}, 5000);
ws.on('close', () => {
console.log('Client disconnected');
clearInterval(interval);
});
});
server.listen(PORT, () => {
console.log(`Hybrid server listening on port ${PORT}`);
});
Client: Fetching Initial Data (JS)
On the client-side (e.g., in a web browser), you'd first use fetch or XMLHttpRequest to get the initial list of items from the REST API.
This ensures the user sees existing data immediately.
async function getInitialItems() {
try {
const response = await fetch('http://localhost:3000/api/items');
const data = await response.json();
console.log('Initial items (REST):', data);
// Render initial items on the UI
} catch (error) {
console.error('Error fetching items:', error);
}
}
getInitialItems();
Client: Subscribing to Live Updates (JS)
After fetching initial data, the client opens a WebSocket connection to receive real-time updates. When a message arrives, it can update the UI dynamically.
This keeps the displayed data fresh without constant page refreshes.
const ws = new WebSocket('ws://localhost:3000');
ws.onopen = () => {
console.log('WebSocket connected!');
};
ws.onmessage = event => {
const message = JSON.parse(event.data);
if (message.type === 'itemUpdate') {
console.log('Real-time item update:', message.item);
// Update the specific item on the UI
}
};
ws.onclose = () => {
console.log('WebSocket disconnected.');
};
ws.onerror = error => {
console.error('WebSocket error:', error);
};
Hybrid Use Cases
Which communication method is best for each scenario in a hybrid application?
Recap: Best of Both Worlds
You've learned how to design hybrid architectures that combine RESTful APIs and WebSockets.
- REST excels for initial data loading and traditional CRUD operations due to its stateless, request-response nature.
- WebSockets are perfect for instant, bidirectional communication, providing dynamic updates and real-time interactions.
By strategically using both, you can build performant and highly interactive applications. Next, we'll look at bridging WebSockets to message queues.
تعلم WebSockets & Realtime Systems Programming مع معلم ذكاء اصطناعي — مجانًا
اكتب وقم بتشغيل أكوادك الفعلية في المتصفح، واحصل على مساعدة فورية من معلم ذكاء اصطناعي متاح 24/7، واستمر من حيث توقفت على الويب أو في التطبيق.
- الدورات
- 12
- الدروس
- 47
الأسئلة الشائعة
هل درس «WebSockets مع واجهات RESTful البرمجية» مجاني؟
نعم — نص درس «WebSockets مع واجهات RESTful البرمجية» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة WebSockets & Realtime Systems Programming، انتقل إلى CoddyKit PRO. تتضمن دورة WebSockets & Realtime Systems Programming 3 دروس في المجموع.
ماذا ستتعلم في «WebSockets مع واجهات RESTful البرمجية»؟
صمّموا بنيات هجينة تكمّل فيها WebSockets واجهات REST البرمجية التقليدية لتوفير تحديثات ديناميكية. تتمرن على WebSockets & Realtime Systems Programming مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ WebSockets & Realtime Systems Programming؟
لا تُشترط خبرة سابقة. WebSockets & Realtime Systems Programming على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 1 من أصل 3.
كم من الوقت يستغرق درس «WebSockets مع واجهات RESTful البرمجية»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس WebSockets & Realtime Systems Programming هذا؟
نعم. كل درس في WebSockets & Realtime Systems Programming يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- WebSockets مع واجهات RESTful البرمجية
- الربط مع قوائم انتظار الرسائل
- بث تغييرات قاعدة البيانات إلى العملاء