0Pricing
WebSockets & Realtime Systems Programming · 课时

客户端事件处理

在浏览器中有效管理 `open`、`message`、`error` 和 `close` 等连接事件。

客户端事件处理 是 CoddyKit 上的免费 WebSockets & Realtime Systems Programming 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 WebSockets & Realtime Systems Programming 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 WebSockets & Realtime Systems Programming 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

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!

常见问题解答

「客户端事件处理」课时是免费的吗?

是的 — 「客户端事件处理」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 WebSockets & Realtime Systems Programming 课程的其余内容,请升级到 CoddyKit PRO。 WebSockets & Realtime Systems Programming 课程共包含 4 节课。

「客户端事件处理」这节课中我会学到什么?

在浏览器中有效管理 `open`、`message`、`error` 和 `close` 等连接事件。 你通过在浏览器中直接运行的动手代码来练习 WebSockets & Realtime Systems Programming,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 WebSockets & Realtime Systems Programming 需要有经验吗?

无需任何先前经验。CoddyKit 上的 WebSockets & Realtime Systems Programming 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「客户端事件处理」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 WebSockets & Realtime Systems Programming 课中编写并运行代码吗?

能。每节 WebSockets & Realtime Systems Programming 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 浏览器 WebSocket API 基础
  2. 发送与接收数据
  3. 客户端事件处理
  4. 客户端自动重新连接
← 返回 WebSockets & Realtime Systems Programming