Obsługa zdarzeń po stronie klienta
Nauczą się Państwo skutecznie zarządzać w przeglądarce zdarzeniami połączenia, takimi jak `open`, `message`, `error` i `close`.
Obsługa zdarzeń po stronie klienta to bezpłatna lekcja WebSockets & Realtime Systems Programming na CoddyKit. To lekcja 3 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej WebSockets & Realtime Systems Programming, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs WebSockets & Realtime Systems Programming zawiera 4 lekcji w sumie.
Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.
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 laterReceiving 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 laterCatching 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 laterConnection 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!
Często zadawane pytania
Czy lekcja „Obsługa zdarzeń po stronie klienta” jest bezpłatna?
Tak — pełny tekst „Obsługa zdarzeń po stronie klienta” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu WebSockets & Realtime Systems Programming, przejdź na CoddyKit PRO. Kurs WebSockets & Realtime Systems Programming zawiera 4 lekcji w sumie.
Co nauczysz się w „Obsługa zdarzeń po stronie klienta”?
Nauczą się Państwo skutecznie zarządzać w przeglądarce zdarzeniami połączenia, takimi jak `open`, `message`, `error` i `close`. Ćwiczysz WebSockets & Realtime Systems Programming z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.
Czy potrzebuję doświadczenia, aby zacząć WebSockets & Realtime Systems Programming?
Nie wymagamy żadnego doświadczenia. WebSockets & Realtime Systems Programming w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 3 z 4.
Ile czasu zajmuje lekcja „Obsługa zdarzeń po stronie klienta”?
Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.
Czy mogę pisać i uruchamiać kod w tej lekcji WebSockets & Realtime Systems Programming?
Tak. Każda lekcja WebSockets & Realtime Systems Programming zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.
Wszystkie lekcje w tym kursie
- Podstawy przeglądarkowego API WebSocket
- Wysyłanie i odbieranie danych
- Obsługa zdarzeń po stronie klienta
- Automatyczne ponowne łączenie po stronie klienta