websocket 服务 pinia 全局配置

websocket 方法类

javascript 复制代码
// stores/webSocketStore.ts
import { defineStore } from "pinia";

interface WebSocketStoreState {
  ws: WebSocket | null; // WebSocket 实例
  callbacks: ((message: string) => void)[]; // 消息回调函数列表
  connected: boolean; // 连接状态
}

export const useWebSocketStore = defineStore("webSocket", {
  state: (): WebSocketStoreState => ({
    ws: null,
    callbacks: [],
    connected: false,
  }),

  actions: {
    // 连接 WebSocket
    connect(url: string): void {
      if (this.ws) {
        console.warn("WebSocket already connected");
        return;
      }

      // 创建 WebSocket 实例
      this.ws = new WebSocket(url);

      // 监听连接打开事件
      this.ws.onopen = () => {
        console.log("WebSocket connected");
        this.connected = true;
      };

      // 监听消息事件
      this.ws.onmessage = (event: MessageEvent) => {
        // console.log("Received message:", event.data);
        this.callbacks.forEach((callback) => callback(event.data)); // 执行回调
      };

      // 监听错误事件
      this.ws.onerror = (error) => {
        console.error("WebSocket error:", error);
      };

      // 监听连接关闭事件
      this.ws.onclose = () => {
        console.log("WebSocket connection closed");
        this.connected = false;
      };
    },

    // 发送消息
    send(message: string): void {
      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        this.ws.send(message);
      } else {
        console.error("WebSocket is not open");
      }
    },

    // 注册接收消息的回调函数
    onMessage(callback: (message: string) => void): void {
      this.callbacks.push(callback);
    },

    // 重新连接 WebSocket
    reconnect(url: string): void {
      if (url) {
        console.log("Reconnecting WebSocket...");
        // 创建 WebSocket 实例
        this.ws = new WebSocket(url);

        // 监听连接打开事件
        this.ws.onopen = () => {
          console.log("WebSocket connected");
          this.connected = true;
        };

        // 监听消息事件
        this.ws.onmessage = (event: MessageEvent) => {
          // console.log("Received message:", event.data);
          this.callbacks.forEach((callback) => callback(event.data)); // 执行回调
        };

        // 监听错误事件
        this.ws.onerror = (error) => {
          console.error("WebSocket error:", error);
        };

        // 监听连接关闭事件
        this.ws.onclose = () => {
          console.log("WebSocket connection closed");
          this.connected = false;
        };
      } else {
        console.error("No URL available to reconnect");
      }
    },

    // 关闭 WebSocket 连接
    close(): void {
      if (this.ws) {
        this.ws.close();
      }
    },
  },
});

页面中使用例子

javascript 复制代码
<template>
  <div>
    <el-button @click="connectWebSocket">Connect WebSocket</el-button>
    <el-button @click="sendMessage">Send Message</el-button>
    <el-button @click="closeWebSocket">Close WebSocket</el-button>
    <el-button @click="reconnect('ws://localhost:3030')"
      >Reset Connection</el-button
    >

    <div v-if="webSocketStore.connected">WebSocket is connected</div>
    <div v-else>WebSocket is disconnected</div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { useWebSocketStore } from "@/store/webSocketStore"; // 根据实际路径调整

export default defineComponent({
  setup() {
    // 获取 Pinia store
    const webSocketStore = useWebSocketStore();

    // 连接 WebSocket
    const connectWebSocket = () => {
      const url = "ws://localhost:3030"; // 替换为实际的 WebSocket URL
      debugger;
      if (!webSocketStore.connected) {
        webSocketStore.connect(url);
      }
      // if (webSocketStore.ws?.readyState != 1) {
      //   webSocketStore.ws?.onopen;
      // }
    };

    // 发送消息
    const sendMessage = () => {
      const message = "Hello, WebSocket!";
      webSocketStore.send(message);
    };

    // 关闭 WebSocket
    const closeWebSocket = () => {
      webSocketStore.close();
    };

    const reconnect = (url: string) => {
      webSocketStore.reconnect(url);
    };

    // 注册接收到消息的回调函数
    webSocketStore.onMessage((message) => {
      console.log("Received message in component:", message);
    });

    return {
      connectWebSocket,
      sendMessage,
      closeWebSocket,
      reconnect,
      webSocketStore,
      connected: webSocketStore.connected, // 从 store 中获取连接状态
    };
  },
});
</script>

websocket 服务端 测试实例

1.项目中安装 websocket 模块
javascript 复制代码
npm install ws
2.添加如下服务代码
javascript 复制代码
// 导入必要的模块
const express = require('express');
const http = require('http');
const WebSocket = require('ws');

// 创建一个 Express 应用
const app = express();

// 创建一个 HTTP 服务器
const server = http.createServer(app);

// 创建 WebSocket 服务器,传入 HTTP 服务器对象
const wss = new WebSocket.Server({ server });

// WebSocket 连接事件处理
wss.on('connection', (ws) => {
  console.log('A new client connected.');

  // 监听客户端发送的消息
  ws.on('message', (message) => {
    console.log(`Received message: ${message}`);
    
    // 发送消息回客户端
    ws.send(`${message}`);
  });

  // 连接关闭时的处理
  ws.on('close', () => {
    console.log('Client disconnected.');
  });


      const jsonData = {
         SendName: "server",
          ReceiveName: "connectionning client",
          SendDataInfo: { msg: "welcome connection success", type: "tips" },
	  };

        const plainData = { ...jsonData };


  // 发送欢迎消息给客户端
  ws.send(JSON.stringify(plainData));
});

// 设置一个基本的 HTTP 路由
app.get('/', (req, res) => {
  res.send('Hello, Node.js with WebSocket!');
});

// 设置端口并启动服务器
const PORT = process.env.PORT || 3030;
server.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});
3. 启动websocket 测试服务端
javascript 复制代码
node server.js
相关推荐
ROCKY_8175 小时前
计算机网络考试考点——应用层
服务器·网络·计算机网络
这个人需要休息6 小时前
xss的漏洞类型+dvwa DOM xss各难度的小总结
网络·安全
q***61416 小时前
详解 为什么 tcp 会出现 粘包 拆包 问题
网络·tcp/ip·php
HONG````6 小时前
鸿蒙应用HTTP网络请求实战指南:从基础到进阶优化
网络·http·harmonyos
v***44676 小时前
PLC(电力载波通信)网络机制介绍
开发语言·网络·php
世界尽头与你6 小时前
CVE-2014-3566: OpenSSL 加密问题漏洞
网络·安全·网络安全·渗透测试
L***B5686 小时前
SQL 注入漏洞原理以及修复方法
网络·数据库·sql
by__csdn6 小时前
Vue 2 与 Vue 3:深度解析与对比
前端·javascript·vue.js·typescript·vue·css3·html5
ZeroNews内网穿透6 小时前
ZeroNews IP 访问控制能力
服务器·网络·网络协议·tcp/ip·安全·web安全·小程序
车载测试工程师6 小时前
CAPL学习-DoIP测试仪配置函数
网络协议·以太网·capl·canoe·doip