0Pricing
WebSockets & Realtime Systems Programming · 课时

发送与接收数据

实现向服务器发送消息以及处理服务器传入数据的方法。

发送与接收数据 是 CoddyKit 上的免费 WebSockets & Realtime Systems Programming 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 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 Blob or ArrayBuffer).
  • 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.data will be a string.
  • If the server sent binary data, event.data will be an ArrayBuffer or a Blob, depending on the WebSocket's binaryType property (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 calling ws.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.onmessage event 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 and JSON.parse() after receiving JSON strings.

Next, we'll explore how to handle other crucial client-side events like connection errors and closures!

常见问题解答

「发送与接收数据」课时是免费的吗?

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

「发送与接收数据」这节课中我会学到什么?

实现向服务器发送消息以及处理服务器传入数据的方法。 你通过在浏览器中直接运行的动手代码来练习 WebSockets & Realtime Systems Programming,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

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

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

「发送与接收数据」课时需要多长时间?

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

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

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

此课程中的所有课时

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