Skip to content
The Chat Archive
minimax-m1 LMArena Human Preference 140K

使用vue写一个websocket的入门演示代码,包含服务端和客户端,详细介绍整个流程

  1. User

    使用vue写一个websocket的入门演示代码,包含服务端和客户端,详细介绍整个流程

  2. Assistant

    以下是使用 Vue 3 编写的 WebSocket 入门演示代码,包含详细流程说明:


    完整代码实现

    1. 服务端代码(Node.js + ws 库)

    // server.js
    const WebSocket = require('ws');
    
    // 创建 WebSocket 服务器,监听 3000 端口
    const wss = new WebSocket.Server({ 
      port: 3000,
      // 允许跨域(关键配置)
      verifyClient: (info) => {
        info.req.headers.origin = '*'; // 允许所有来源
        return true;
      }
    });
    
    // 监听连接事件
    wss.on('connection', (ws) => {
      console.log('客户端已连接');
      connectionStatus.value = '已连接'; // 需 Vue 响应式变量配合
    
      // 接收消息
      ws.on('message', (message) => {
        console.log('收到消息:', message.toString());
        
        // 广播消息给所有客户端
        wss.clients.forEach(client => {
          if (client.readyState === WebSocket.OPEN) {
            client.send(`广播: ${message}`);
          }
        });
      });
    
      // 监听断开连接
      ws.on('close', () => {
        console.log('客户端已断开');
        connectionStatus.value = '已断开';
      });
    });
    
    console.log('WebSocket 服务端已启动,端口: 3000');
    

    2. 客户端代码(Vue 3 单文件)

    <!DOCTYPE html>
    <html>
    <head>
      <title>Vue WebSocket 客户端</title>
      <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    </head>
    <body>
      <div id="app">
        <h1>WebSocket 客户端 (Vue 3)</h1>
        <div>连接状态: {{ connectionStatus }}</div>
        
        <div v-for="(msg, index) in messages" :key="index">
          {{ msg }}
        </div>
        
        <input v-model="messageInput" placeholder="输入消息...">
        <button @click="sendMessage">发送</button>
      </div>
    
      <script>
        const { createApp, ref, onMounted, onBeforeUnmount } = Vue;
    
        createApp({
          setup() {
            // 响应式数据
            const messages = ref([]);
            const messageInput = ref('');
            const connectionStatus = ref('未连接');
            let ws = null;
    
            // WebSocket 连接逻辑
            const connectWebSocket = () => {
              ws = new WebSocket('ws://localhost:3000');
    
              // 连接成功
              ws.onopen = () => {
                connectionStatus.value = '已连接';
              };
    
              // 接收消息
              ws.onmessage = (event) => {
                messages.value.push(event.data);
              };
    
              // 连接关闭
              ws.onclose = () => {
                connectionStatus.value = '已断开';
              };
    
              // 错误处理
              ws.onerror = (error) => {
                console.error('WebSocket 错误:', error);
                connectionStatus.value = '连接失败';
              };
            };
    
            // 组件挂载时连接
            onMounted(() => {
              connectWebSocket();
            });
    
            // 组件卸载前关闭连接
            onBeforeUnmount(() => {
              if (ws) ws.close();
            });
    
            // 发送消息
            const sendMessage = () => {
              const message = messageInput.value.trim();
              if (message && ws?.readyState === WebSocket.OPEN) {
                ws.send(message);
                messageInput.value = '';
              }
            };
    
            return {
              messages,
              messageInput,
              connectionStatus,
              sendMessage
            };
          }
        }).mount('#app');
      </script>
    </body>
    </html>
    

    运行流程详解

    1. 启动服务端

    # 初始化 Node.js 项目(如果尚未初始化)
    npm init -y
    
    # 安装依赖
    npm install ws
    
    # 启动服务端
    node server.js
    

    输出:

    WebSocket 服务端已启动,端口: 3000
    

    2. 运行客户端

    • 将客户端代码保存为 client.html

    • 方法1(推荐):用 HTTP 服务器启动(避免 CORS 问题)

      # 使用 Python 启动 HTTP 服务器(需 Python 环境)
      python -m http.server 8080
      

      访问 http://localhost:8080/client.html

    • 方法2:直接用浏览器打开文件(可能遇到 CORS 限制)

    3. 测试功能

    1. 打开两个浏览器标签页访问 http://localhost:8080/client.html
    2. 在任意标签页输入消息并点击发送
    3. 所有连接的客户端会实时收到广播消息

    代码核心逻辑说明

    服务端

    • 使用 ws 库创建 WebSocket 服务器
    • 通过 verifyClient 配置允许跨域
    • 广播机制:wss.clients 遍历所有连接客户端
    • 事件监听:connection, message, close

    客户端(Vue 3)

    • 响应式数据:使用 ref() 管理消息列表和状态
    • 生命周期:
      • onMounted 时建立 WebSocket 连接
      • onBeforeUnmount 时关闭连接(防止内存泄漏)
    • 事件处理:
      • onopen:更新连接状态
      • onmessage:将消息添加到列表(触发自动渲染)
      • onclose/onerror:处理异常状态
    • 发送消息:通过 ws.send() 发送,Vue 双向绑定输入框

    关键注意事项

    1. 跨域问题
      服务端必须配置允许跨域,否则浏览器会拦截 WebSocket 连接。示例中通过 verifyClient 允许所有来源。

    2. 端口一致性
      客户端代码中 WebSocket URL 必须与实际服务端端口一致:

      new WebSocket('ws://localhost:3000') // 与 server.js 端口一致
      
    3. 生产环境优化

      • 添加重连机制
      • 消息序列化/反序列化
      • 错误重试逻辑
      • 使用 wss:// 加密协议
    4. Vue 响应式更新
      直接修改 messages.value 会自动触发 Vue 的 DOM 更新,无需手动刷新。


    效果验证

    • 多个客户端连接后,任意客户端发送消息,其他客户端会实时显示广播消息
    • 连接状态会实时更新到页面上

    通过这个示例,您可以完整理解 WebSocket 的基础通信流程,以及如何与 Vue 3 的响应式系统结合使用。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.