Nodejs WebSocket通信插件node-ws的使用

Nodejs WebSocket通信插件node-ws的使用
node-ws 是一个流行的 Node.js WebSocket 库,用于创建 WebSocket 服务器和客户端。以下是如何使用 node-ws 创建 WebSocket 服务器和客户端的基本示例。

安装

首先,你需要安装 ws 包。可以通过 npm 安装:

npm install ws

创建 WebSocket 服务器

下面是一个简单的 WebSocket 服务器示例:

const WebSocket = require('ws');

// 创建一个 WebSocket 服务器实例,监听 8080 端口
const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function connection(ws) {
    console.log("新客户端连接");

    // 当接收到消息时触发
    ws.on('message', function incoming(message) {
        console.log('接收到消息:', message);

        // 可以向所有连接的客户端广播消息
        wss.clients.forEach(function each(client) {
            if (client !== ws && client.readyState === WebSocket.OPEN) {
                client.send(message);
            }
        });
    });

    // 当客户端断开连接时触发
    ws.on('close', function close() {
        console.log("客户端断开连接");
    });
});

console.log("WebSocket 服务器运行在 ws://localhost:8080");

创建 WebSocket 客户端

接下来是一个简单的 WebSocket 客户端示例:

const WebSocket = require('ws');

// 连接到 WebSocket 服务器
const ws = new WebSocket('ws://localhost:8080');

ws.on('open', function open() {
    console.log('已连接到 WebSocket 服务器');
    // 发送消息到服务器
    ws.send('Hello, Server!');
});

ws.on('message', function incoming(data) {
    console.log('从服务器接收到消息:', data);
});

ws.on('close', function close() {
    console.log('与 WebSocket 服务器的连接已关闭');
});

总结

  • 使用 new WebSocket.Server({ port: 8080 }) 创建一个 WebSocket 服务器。
  • 使用 new WebSocket('ws://localhost:8080') 创建一个 WebSocket 客户端。
  • 监听 'connection' 事件来处理客户端连接。
  • 监听 'message' 事件来处理接收到的消息。
  • 监听 'close' 事件来处理连接断开的情况。

你可以根据具体需求扩展这些基本功能,例如添加身份验证、处理不同类型的消息等。希望这能帮助你开始使用 node-ws


3 回复

当然!node-ws 是一个非常流行的 Node.js WebSocket 库。下面是如何开始使用它的简单步骤:

  1. 安装: 首先,你需要安装 ws 模块。打开终端,运行:

    npm install ws
    
  2. 创建服务器: 创建一个新的 JavaScript 文件(比如 server.js),然后添加以下代码来设置 WebSocket 服务器:

    const WebSocket = require('ws');
    
    const wss = new WebSocket.Server({ port: 8080 });
    
    wss.on('connection', function connection(ws) {
      ws.on('message', function incoming(message) {
        console.log('received: %s', message);
      });
    
      ws.send('Hello, Client!');
    });
    
  3. 客户端连接: 创建另一个文件(比如 client.html)来测试连接:

    <!DOCTYPE html>
    <html>
    <head>
      <title>WebSocket Test</title>
    </head>
    <body>
      <script>
        const ws = new WebSocket('ws://localhost:8080');
        ws.onopen = () => {
          console.log("Connected to server!");
          ws.send("Hello, Server!");
        };
        ws.onmessage = (event) => {
          console.log("Message from server ", event.data);
        };
      </script>
    </body>
    </html>
    
  4. 启动服务器: 在终端中运行你的服务器脚本:

    node server.js
    
  5. 打开客户端: 使用浏览器打开 client.html 文件,你应该能在控制台看到消息交换。

这样,你就有了一个基本的 WebSocket 服务器和客户端的交互。试试看吧!


node-ws 是一个非常流行的 Node.js WebSocket 库。它允许你在 Node.js 项目中轻松地创建 WebSocket 服务器和客户端。下面我将分别介绍如何使用 node-ws 创建 WebSocket 服务器和客户端。

安装

首先,你需要安装 ws 包。可以通过 npm 来安装:

npm install ws

WebSocket 服务器

以下是一个简单的 WebSocket 服务器示例,它监听端口8080,并向连接的每个客户端广播消息:

const WebSocket = require('ws');

// 创建WebSocket服务器,监听8080端口
const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function connection(ws) {
    console.log('A client connected.');

    // 当接收到消息时
    ws.on('message', function incoming(message) {
        console.log('received: %s', message);
        
        // 向所有连接的客户端广播消息
        wss.clients.forEach(function each(client) {
            if (client !== ws && client.readyState === WebSocket.OPEN) {
                client.send(message);
            }
        });
    });

    // 当客户端断开连接时
    ws.on('close', function close() {
        console.log('A client disconnected.');
    });
});

console.log("WebSocket server is running on ws://localhost:8080");

WebSocket 客户端

接下来,我们来看如何创建一个 WebSocket 客户端,该客户端连接到上述服务器并发送接收消息:

const WebSocket = require('ws');

// 连接到 WebSocket 服务器
const ws = new WebSocket('ws://localhost:8080');

ws.on('open', function open() {
    console.log('Connected to the server');
    
    // 发送消息给服务器
    ws.send('Hello Server!');
});

ws.on('message', function incoming(data) {
    console.log('Received from server: ', data);
});

这个例子展示了如何创建一个基本的 WebSocket 服务器和客户端。你可以根据需要扩展这些功能,比如添加错误处理、身份验证等。希望这对你有所帮助!

node-ws 是一个流行的 Node.js WebSocket 实现。首先安装它:npm install ws。创建服务器示例:

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
  });

  ws.send('Hello! Message from server.');
});

客户端示例:

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

ws.on('open', function open() {
  ws.send('Hello Server!');
});

ws.on('message', function incoming(message) {
  console.log('received: %s', message);
});

以上代码演示了基本的通信过程。

回到顶部