إرسال البيانات واستقبالها
نفّذوا أساليب لإرسال الرسائل إلى الخادم ومعالجة البيانات الواردة منه.
إرسال البيانات واستقبالها درس مجاني في WebSockets & Realtime Systems Programming على CoddyKit. هذا هو الدرس 2 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في WebSockets & Realtime Systems Programming، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة WebSockets & Realtime Systems Programming 4 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
Client Data Exchange Intro
Welcome back! In the previous lessons, we learned about establishing WebSocket connections. Now, let's dive into the core of realtime communication: sending and receiving data.
This lesson will show you how to implement methods for clients to send messages to a WebSocket server and how to handle incoming data from that server.
Sending Data with `send()`
To send data from your client to the WebSocket server, you'll use the WebSocket.send() method. It's quite straightforward!
- You can send various data types: plain text (strings), binary data (like
BloborArrayBuffer). - The server will receive this data and can then process it or even broadcast it to other connected clients.
Basic `send()` Example
Here's a simple JavaScript example demonstrating how to send a text message once the WebSocket connection is open. Remember, ws://localhost:8080 is a common address for a local test server.
const ws = new WebSocket('ws://localhost:8080');
ws.onopen = () => {
console.log('Connected to server');
ws.send('Hello from the client!');
};
ws.onerror = (error) => {
console.error('WS Error:', error);
};
// This example only sends; we'll cover receiving next.Data Types for `send()`
While sending simple strings is common, WebSockets also support binary data. This is crucial for applications needing to transfer images, audio, or other non-textual information efficiently.
- String: Most common for text messages, JSON.
- ArrayBuffer: Raw binary data buffer.
- Blob: File-like object representing raw data.
The send() method automatically handles the framing for these types.
Receiving Data: `onmessage`
Receiving data from the server is just as important. The WebSocket API provides an event handler called onmessage for this purpose.
When the server sends a message, your client's onmessage function will be triggered. It receives a MessageEvent object, which contains the actual data.
Processing Received Data
Inside the onmessage handler, you access the message content through event.data. The type of event.data depends on what the server sent:
- If the server sent text,
event.datawill be a string. - If the server sent binary data,
event.datawill be an ArrayBuffer or a Blob, depending on the WebSocket'sbinaryTypeproperty (default is'blob').
Basic `onmessage` Example
Let's combine sending and receiving! This client code connects, sends a message, and then listens for any incoming messages, logging them to the console. You'd need a server sending messages back for this to fully demonstrate.
const ws = new WebSocket('ws://localhost:8080');
ws.onopen = () => {
console.log('Connected to server');
ws.send('Requesting data...');
};
ws.onmessage = (event) => {
console.log('Received from server:', event.data);
// event.data could be string, Blob, or ArrayBuffer
};
ws.onerror = (error) => {
console.error('WS Error:', error);
};
ws.onclose = () => {
console.log('Disconnected');
};Structured Data with JSON
For most modern web applications, sending and receiving structured data is crucial. JSON (JavaScript Object Notation) is the de-facto standard for this.
- Sending JSON: Use
JSON.stringify()to convert your JavaScript object into a JSON string before callingws.send(). - Receiving JSON: Use
JSON.parse()to convert the incoming JSON string (event.data) back into a JavaScript object.
JSON Communication Example
This example shows how a client can send a structured JSON object to the server and process a JSON response. This pattern is very common for building interactive applications.
const ws = new WebSocket('ws://localhost:8080');
ws.onopen = () => {
console.log('Connected to server');
const message = { type: 'greeting', payload: 'Hello Server!' };
ws.send(JSON.stringify(message));
};
ws.onmessage = (event) => {
console.log('Raw message:', event.data);
try {
const data = JSON.parse(event.data);
console.log('Parsed JSON:', data);
if (data.type === 'response') {
console.log('Server replied:', data.payload);
}
} catch (e) {
console.error('Failed to parse JSON:', e);
}
};
ws.onerror = (error) => {
console.error('WS Error:', error);
};Client Data Handling Quiz
Consider the following client-side WebSocket code snippet:
const ws = new WebSocket('ws://localhost:8080');
ws.onopen = () => {
ws.send(JSON.stringify({ action: 'subscribe', topic: 'news' }));
};
ws.onmessage = (event) => {
let msg = event.data;
if (typeof msg === 'string') {
msg = JSON.parse(msg);
}
console.log(msg.action);
};If the server sends the string '{"action":"update","data":"new article"}', what will be logged to the console?
Recap: Send & Receive Data
Great job! You've learned the fundamental methods for exchanging data over WebSockets from the client side.
- Use
ws.send()to send text (strings) or binary data (Blob, ArrayBuffer) to the server. - Listen for incoming messages using the
ws.onmessageevent handler. - Access the message content via
event.data, which can be a string, Blob, or ArrayBuffer. - For structured communication, always use
JSON.stringify()before sending andJSON.parse()after receiving JSON strings.
Next, we'll explore how to handle other crucial client-side events like connection errors and closures!
الأسئلة الشائعة
هل درس «إرسال البيانات واستقبالها» مجاني؟
نعم — نص درس «إرسال البيانات واستقبالها» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة WebSockets & Realtime Systems Programming، انتقل إلى CoddyKit PRO. تتضمن دورة WebSockets & Realtime Systems Programming 4 دروس في المجموع.
ماذا ستتعلم في «إرسال البيانات واستقبالها»؟
نفّذوا أساليب لإرسال الرسائل إلى الخادم ومعالجة البيانات الواردة منه. تتمرن على WebSockets & Realtime Systems Programming مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ WebSockets & Realtime Systems Programming؟
لا تُشترط خبرة سابقة. WebSockets & Realtime Systems Programming على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 2 من أصل 4.
كم من الوقت يستغرق درس «إرسال البيانات واستقبالها»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس WebSockets & Realtime Systems Programming هذا؟
نعم. كل درس في WebSockets & Realtime Systems Programming يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- أساسيات WebSocket API في المتصفح
- إرسال البيانات واستقبالها
- معالجة الأحداث من جهة العميل
- إعادة الاتصال التلقائية على العميل