WebSockets & Realtime Systems Programming · Pelajaran

Penanganan Peristiwa Sisi Klien

Kelola peristiwa koneksi seperti `open`, `message`, `error`, dan `close` secara efektif di peramban.

Pelajaran 3 dari 411 langkah

Penanganan Peristiwa Sisi Klien adalah pelajaran WebSockets & Realtime Systems Programming gratis di CoddyKit. Ini adalah pelajaran 3 dari 4. Kamu bisa membaca pelajaran lengkapnya di bawah secara gratis — lalu praktikkan langsung di browser dengan editor kode bawaan dan tutor AI 24/7. Ini adalah bagian dari jalur belajar WebSockets & Realtime Systems Programming, dan progresmu tersinkronisasi di web dan aplikasi CoddyKit. Kursus WebSockets & Realtime Systems Programming mencakup 4 pelajaran total.

Bagian dari pelajaran ini belum diterjemahkan dan ditampilkan dalam bahasa Inggris.

Intro: Why Events Matter

WebSockets are dynamic! Unlike simple HTTP requests, a WebSocket connection stays open. This means you need a way to know when things happen on that connection.

That's where event handling comes in. It allows your browser application to react to the connection opening, messages arriving, errors, or the connection closing.

Connection Established: `onopen`

The first important event is open. This fires as soon as your WebSocket connection has been successfully established and is ready to send and receive data.

It's your green light to start communicating!

Handling Connection Open

Let's see how to handle the open event. When the connection is ready, a message is logged, and then we send a 'Hello' message.

const ws = new WebSocket('wss://echo.websocket.events');

ws.onopen = (event) => {
  console.log('Connection established!');
  ws.send('Hello WebSocket Server!');
};

// Other event handlers will be added later

Receiving Data: `onmessage`

Once connected, your server will send data. The message event is triggered every time your client receives data from the server.

The received data is in event.data. This can be text or binary data, which you might need to parse (e.g., JSON).

Processing Incoming Messages

Now, let's add an event listener for incoming messages. We'll log the data we receive back from the server.

const ws = new WebSocket('wss://echo.websocket.events');

ws.onopen = (event) => {
  console.log('Connection established!');
  ws.send('Hello WebSocket Server!');
};

ws.onmessage = (event) => {
  console.log(`Server says: ${event.data}`);
};

// Other event handlers will be added later

Catching Errors: `onerror`

Things can go wrong! Network issues, server problems, or invalid protocols can trigger the error event. This event signals a problem but doesn't always provide specific error details directly.

Always include an error handler for robust applications.

Handling Connection Errors

Here's how to set up an onerror handler. This will catch general errors during the WebSocket connection's lifetime.

const ws = new WebSocket('wss://echo.websocket.events');

ws.onopen = (event) => {
  console.log('Connection established!');
  ws.send('Hello WebSocket Server!');
};

ws.onmessage = (event) => {
  console.log(`Server says: ${event.data}`);
};

ws.onerror = (error) => {
  console.error('WebSocket encountered an error!');
  // More specific error details might be in the browser console
};

// Other event handlers will be added later

Connection Closed: `onclose`

When a WebSocket connection is deliberately closed by either the client or the server, the close event fires. It provides a code and a reason in the event object.

These details help you understand why the connection ended, which is crucial for debugging or attempting reconnections.

Responding to Connection Close

Let's add the onclose handler. It logs the closure code and reason, which are useful for understanding the connection's end.

const ws = new WebSocket('wss://echo.websocket.events');

ws.onopen = (event) => {
  console.log('Connection established!');
  ws.send('Hello WebSocket Server!');
};

ws.onmessage = (event) => {
  console.log(`Server says: ${event.data}`);
};

ws.onerror = (error) => {
  console.error('WebSocket encountered an error!');
};

ws.onclose = (event) => {
  console.log(`Connection closed! Code: ${event.code}, Reason: ${event.reason || 'No reason provided'}`);
  // Common codes: 1000 (normal), 1001 (going away), 1006 (abnormal closure)
};

Event Handling Check

You've learned about the main WebSocket events. Now, let's test your understanding!

Recap: Mastering WebSocket Events

Great job! You've explored the essential client-side WebSocket events:

  • onopen: Fired when the connection is ready.
  • onmessage: Handles incoming data from the server.
  • onerror: Catches connection-related issues.
  • onclose: Indicates the connection has terminated, providing a code and reason.

Understanding these events is key to building robust and interactive realtime applications!

Gratis untuk memulai

Belajar WebSockets & Realtime Systems Programming dengan tutor AI — gratis

Tulis dan jalankan kode asli di browser kamu, dapatkan bantuan instan dari tutor AI 24/7, dan lanjutkan di mana kamu tinggalkan di web atau aplikasi.

Kursus
12
Pelajaran
47

Pertanyaan yang Sering Diajukan

Apakah pelajaran “Penanganan Peristiwa Sisi Klien” gratis?

Ya — teks lengkap “Penanganan Peristiwa Sisi Klien” gratis dibaca di sini di web. Untuk praktiknya secara interaktif (editor kode bawaan dan tutor AI 24/7) dan buka sisa kursus WebSockets & Realtime Systems Programming, upgrade ke CoddyKit PRO. Kursus WebSockets & Realtime Systems Programming mencakup 4 pelajaran total.

Apa yang akan aku pelajari di “Penanganan Peristiwa Sisi Klien”?

Kelola peristiwa koneksi seperti `open`, `message`, `error`, dan `close` secara efektif di peramban. Kamu berlatih WebSockets & Realtime Systems Programming dengan kode praktik yang langsung kamu jalankan di browser, dan tutor AI 24/7 menjawab pertanyaanmu saat kamu mengerjakan pelajaran ini.

Apakah aku perlu pengalaman untuk memulai WebSockets & Realtime Systems Programming?

Tidak diperlukan pengalaman sebelumnya. WebSockets & Realtime Systems Programming di CoddyKit dirancang untuk pemula hingga pelajar tingkat lanjut, jadi kamu bisa memulai di sini atau dari awal dan belajar sesuai kecepatan kamu sendiri. Ini adalah pelajaran 3 dari 4.

Berapa lama pelajaran “Penanganan Peristiwa Sisi Klien” memakan waktu?

Sebagian besar pelajaran CoddyKit memakan waktu sekitar 5–10 menit. Setiap pelajaran ringkas dan interaktif, jadi kamu membuat kemajuan stabil dan melanjutkan dari tempat kamu tinggalkan di web dan aplikasi.

Bisakah aku menulis dan menjalankan kode dalam pelajaran WebSockets & Realtime Systems Programming ini?

Ya. Setiap pelajaran WebSockets & Realtime Systems Programming menyertakan editor kode bawaan, jadi kamu menulis dan menjalankan kode nyata langsung di browser dan mendapatkan umpan balik AI instan — tidak diperlukan penyiapan lokal.

Semua pelajaran dalam kursus ini

  1. Dasar-Dasar API WebSocket di Peramban
  2. Mengirim dan Menerima Data
  3. Penanganan Peristiwa Sisi Klien
  4. Penyambungan Kembali Otomatis pada Klien
← Kembali ke WebSockets & Realtime Systems Programming