Node.js 中的原生 WebSocket 客户端

¥Native WebSocket Client in Node.js

介绍

¥Introduction

Node.js v21 以来,WebSocket API 已使用 Undici 库进行了增强,引入了内置的 WebSocket 客户端。这简化了 Node.js 应用的实时通信。在 Node.js v22.4.0 版本中,WebSocket API 被标记为稳定,表明它已准备好用于生产。

¥Since Node.js v21, the WebSocket API has been enhanced using the Undici library, introducing a built-in WebSocket client. This simplifies real-time communication for Node.js applications. In Node.js v22.4.0 release, the WebSocket API was marked as stable, indicating it's ready for production use.

什么是 WebSocket

¥What is a WebSocket

WebSocket 是一种标准化通信协议,可通过单个 TCP 连接同时进行双向通信。它具有全双工或双向功能,使其有别于 HTTP。WebSocket 通过使用 HTTP Upgrade 标头来转换协议,实现 HTTP 兼容性。它允许服务器在没有初始请求的情况下将内容推送到客户端,并保持开放的连接以进行持续的消息交换,使其成为实时数据传输的理想选择,并且比 HTTP 轮询等替代方案的开销更低。WebSocket 通信通常通过 TCP 端口 443(安全)或 80(不安全)进行,有助于绕过非 Web 连接的防火墙限制。The protocol defines its own URI schemes (ws:// and wss://) for unencrypted and encrypted connections respectively and supported by all major browsers.

¥WebSocket is a standardized communication protocol that enables simultaneous two-way communication over a single TCP connection. It has full-duplex or bi-directional capabilities that distinguishes it from HTTP. WebSocket achieves HTTP compatibility by using the HTTP Upgrade header to transition protocols. It allows servers to push content to clients without initial requests and maintains open connections for continuous message exchange, making it ideal for real-time data transfer with lower overhead than alternatives like HTTP polling. WebSocket communications typically occur over TCP ports 443 (secured) or 80 (unsecured), helping bypass firewall restrictions on non-web connections. The protocol defines its own URI schemes (ws:// and wss://) for unencrypted and encrypted connections respectively and supported by all major browsers.

原生 WebSocket 客户端

¥Native WebSocket Client

Node.js 现在可以充当 WebSocket client,而无需依赖外部库(如 wssocket.io)进行客户端连接。这允许 Node.js 应用直接启动和管理传出的 WebSocket 连接,简化诸如连接到实时数据馈送或与其他 WebSocket 服务器交互等任务。用户现在可以使用标准 new WebSocket() 构造函数创建 websocket 客户端连接。

¥Node.js can now act as a WebSocket client without relying on external libraries like ws or socket.io for client connections. This allows Node.js applications to initiate and manage outgoing WebSocket connections directly, streamlining tasks such as connecting to real-time data feeds or interacting with other WebSocket servers. Users can now create a websocket client connection with the standard new WebSocket() constructor.

基于上述内容,让我们添加更多实际示例来演示演示基本用例的新 WebSocket 客户端功能。

¥Building on the above, let's add more practical examples to demonstrate the new WebSocket client functionality that demonstrates basic use-cases.

基本连接和消息处理

¥Basic Connection and Message Handling

// Creates a new WebSocket connection to the specified URL.
const socket = new WebSocket('ws://localhost:8080');

// Executes when the connection is successfully established.
socket.addEventListener('open', event => {
  console.log('WebSocket connection established!');
  // Sends a message to the WebSocket server.
  socket.send('Hello Server!');
});

// Listen for messages and executes when a message is received from the server.
socket.addEventListener('message', event => {
  console.log('Message from server: ', event.data);
});

// Executes when the connection is closed, providing the close code and reason.
socket.addEventListener('close', event => {
  console.log('WebSocket connection closed:', event.code, event.reason);
});

// Executes if an error occurs during the WebSocket communication.
socket.addEventListener('error', error => {
  console.error('WebSocket error:', error);
});

发送和接收 JSON 数据

¥Sending and Receiving JSON Data

const socket = new WebSocket('ws://localhost:8080');

socket.addEventListener('open', () => {
  const data = { type: 'message', content: 'Hello from Node.js!' };
  socket.send(JSON.stringify(data));
});

socket.addEventListener('message', event => {
  try {
    const receivedData = JSON.parse(event.data);
    console.log('Received JSON:', receivedData);
  } catch (error) {
    console.error('Error parsing JSON:', error);
    console.log('Received data was:', event.data);
  }
});

上面的 json 代码演示了发送和接收 JSON 数据,这在 WebSocket 应用中很常见。它使用 JSON.stringify() 将 JavaScript 对象转换为 JSON 字符串,然后再发送。并使用 JSON.parse() 将接收到的字符串转换回 JavaScript 对象。最后,它包括 JSON 解析的错误处理。

¥The json code above demonstrates sending and receiving JSON data, which is common in WebSocket applications. It uses JSON.stringify() to convert JavaScript objects to JSON strings before sending. And converts the received string back to a JavaScript object with JSON.parse(). Finally, it includes error handling for JSON parsing.

这减少了依赖管理并提高了兼容性。开发者可以避免安装和维护额外的 WebSocket 客户端库。内置实现符合现代 Web 标准,确保了更好的互操作性。增强功能侧重于 WebSocket 通信的客户端,使 Node.js 能够充当 WebSocket 客户端。

¥This offers reduced dependency management and improved compatibility. Developers can avoid installing and maintaining additional WebSocket client libraries. The built-in implementation aligns with modern web standards, ensuring better interoperability. The enhancement focuses on the client-side of WebSocket communication, enabling Node.js to act as a WebSocket client.

理解很重要

¥Important to Understand

Node.js v22 不提供内置的原生 WebSocket 服务器实现。要创建接受来自 Web 浏览器或其他客户端的传入连接的 WebSocket 服务器,仍然需要使用 wssocket.io 等库。这意味着虽然 Node.js 现在可以轻松连接到 WebSocket 服务器,但它仍然需要外部工具才能成为 WebSocket 服务器。

¥Node.js v22 does not provide a built-in native WebSocket server implementation. To create a WebSocket server that accepts incoming connections from web browsers or other clients, one still need to use libraries like ws or socket.io. This means that while Node.js can now easily connect to WebSocket servers, it still requires external tools to become a WebSocket server.

总结

¥In Summary

Node.js v22 使应用能够像 clients 一样无缝地与 WebSocket 服务器交互,但在 Node.js 中创建 WebSocket 服务器仍然依赖于已建立的库。开发者在 Node.js 项目中实现实时通信时,理解这一区别至关重要。

¥Node.js v22 empowers applications to seamlessly interact with WebSocket servers as clients, but the creation of WebSocket servers within Node.js remains dependent on established libraries. This distinction is crucial for developers to understand when implementing real-time communication in their Node.js projects.