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

本文介绍了如何在项目中创建一个名为SocketService的类,用于处理WebSocket连接,包括单例模式的实现、连接状态管理、回调函数注册与数据发送,以及使用示例。
最低0.47元/天 解锁文章
1079

被折叠的 条评论
为什么被折叠?



