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);
}
连接成功后点开控制台后,选择该标签,会出现类似信息