vue3中使用webstocket

本文介绍了如何在项目中创建一个名为SocketService的类,用于处理WebSocket连接,包括单例模式的实现、连接状态管理、回调函数注册与数据发送,以及使用示例。
摘要由CSDN通过智能技术生成

1.在项目中创建webstocket.ts文件

export default class SocketService {
  // 单例
  static instance = null;
  static get Instance() {
    if (!this.instance) {
      this.instance = new SocketService();
    }
    return this.instance;
  }

  // 和服务端连接的socket对象
  ws = null;

  // 存储回调函数
  callBackMapping = {};

  // 标识是否连接成功
  connected = false;

  // 记录重试的次数
  sendRetryCount = 0;

  // 重新连接尝试的次数
  connectRetryCount = 0;

  //  定义连接服务器的方法
  connect(data) {
    // 连接服务器
    if (!window.WebSocket) {
      return console.log("您的浏览器不支持WebSocket");
    }
    if (!data) return;
    this.ws = new WebSocket(data);

    // 连接成功的事件
    this.ws.onopen = () => {
      console.log("连接服务端成功了");
      this.connected = true;
      // 重置重新连接的次数
      this.connectRetryCount = 0;
    };
    // 1.连接服务端失败
    // 2.当连接成功之后, 服务器关闭的情况
    this.ws.onclose = () => {
      console.log("连接服务端失败");
      this.connected = false;
      this.connectRetryCount++;
      setTimeout(() => {
        this.connect(data);
      }, 500 * this.connectRetryCount);
    };
    // 得到服务端发送过来的数据
    this.ws.onmessage = (msg) => {
      console.log(JSON.parse(msg.data), "------从服务端获取到了数据");
      if (msg.data.code === 0) {
        console.log(JSON.parse(msg.data), "------从服务端获取到了数据");
      } else if (msg.data.code === 403) {
        console.log(msg.data, "从服务端获取到了【不正常】数据");
      }
    };
  }

  // 回调函数的注册
  registerCallBack(socketType, callBack) {
    this.callBackMapping[socketType] = callBack;
  }

  // 取消某一个回调函数
  unRegisterCallBack(socketType) {
    this.callBackMapping[socketType] = null;
  }

  // 发送数据的方法
  send(data) {
    console.log(data, "---data");
    // 判断此时此刻有没有连接成功
    if (this.connected) {
      this.sendRetryCount = 0;
      try {
        this.ws.send(JSON.stringify(data));
      } catch (e) {
        this.ws.send(data);
      }
    } else {
      this.sendRetryCount++;
      setTimeout(() => {
        this.send(data);
      }, this.sendRetryCount * 500);
    }
    console.log(this.sendRetryCount, '---sendRetryCount');
  }
}

使用方法

先建立连接,

import { Socket } from "./socket";


//在onMounted中执行
const initWS = (e: any) => {
     Socket.Instance.connect(e);
}

const sendWS = (e: any) => {
     Socket.send(e);
}

连接成功后点开控制台后,选择该标签,会出现类似信息

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于Vue 3和TypeScript的Websocket单点登录,你可以按照以下步骤进行实现: 1. 安装`websocket`库 ```bash npm install websocket ``` 2. 在Vue 3项目创建一个`websocket.ts`文件,用于连接websocket并发送和接收消息。 ```typescript import WebSocket from 'websocket'; const socket = new WebSocket.client(); // 连接websocket socket.connect('ws://localhost:8080'); // 发送消息 const send = (data: any) => { socket.send(JSON.stringify(data)); }; // 接收消息 socket.on('message', (message) => { const data = JSON.parse(message.utf8Data); console.log(data); }); export default { send, }; ``` 3. 在Vue 3组件使用`websocket.ts`文件的`send`方法发送消息,并接收消息。 ```typescript <template> <div> <input v-model="message" /> <button @click="sendMessage">发送</button> </div> </template> <script lang="ts"> import { defineComponent } from 'vue'; import websocket from './websocket'; export default defineComponent({ data() { return { message: '', }; }, methods: { sendMessage() { websocket.send(this.message); }, }, }); </script> ``` 4. 在服务端使用Node.js,并使用`websocket`库创建一个websocket服务器,用于接收和发送消息。 ```typescript import WebSocket from 'websocket'; const server = new WebSocket.server({ httpServer: httpServer, }); // 存储连接的客户端信息 const clients = new Map<string, any>(); server.on('request', (request) => { const connection = request.accept(null, request.origin); // 客户端连接时保存客户端信息 clients.set(connection.remoteAddress, connection); // 接收消息并广播 connection.on('message', (message) => { clients.forEach((client) => { if (client !== connection && client.readyState === WebSocket.OPEN) { client.send(JSON.stringify(message)); } }); }); // 客户端断开连接时删除客户端信息 connection.on('close', () => { clients.delete(connection.remoteAddress); }); }); ``` 通过以上步骤,你就可以在Vue 3和TypeScript项目实现Websocket单点登录了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值