Files
18xchat/assets/Scripts/Main/Common/SocketUnit.ts
T
2025-07-17 17:18:21 +08:00

129 lines
3.9 KiB
TypeScript

import { InnerMsgCode } from "../Config/InnerMsgCode";
import Utils from "./Utils";
/**长连接*/
export default class SocketUnit {
private socket: WebSocket | null = null;
private isConnected: boolean = false;
private reconnetSwt: boolean = false; //重连开关
private reconnectCount: number = 0; //重连次数
private reconnectMaxCount: number = 3; //最大重连次数
private reconnectInterval: number = 1500; //重连间隔时间 ms
private reconnectTimer : number = null; //重连定时器
private reSendData : any = null; //重连时需要重发的数据
private url: string = ""; //连接地址
private dataReceivedCallback: (data: any) => void = () => { };
// 连接到服务器
public connect(url: string): void {
if (this.isConnected) {
console.log("SocketUnit: Already connected.");
return;
}
this.url = url;
this.socket = new WebSocket(url);
console.log("SocketUnit: Connecting to -> " + url);
// 连接成功
this.socket.onopen = () => {
this.isConnected = true;
console.log("SocketUnit: Connection succ.");
if (this.reconnetSwt) {
console.log("SocketUnit: socket重连成功.");
this.stopReconnect();
if (this.reSendData) {
this.sendData(this.reSendData);
this.reSendData = null;
}
}
};
// 接收到消息
this.socket.onmessage = (event) => {
// console.log("SocketUnit: Received data: ", event);
if (this.dataReceivedCallback) {
this.dataReceivedCallback(event);
}
};
// 连接关闭
this.socket.onclose = () => {
this.isConnected = false;
console.log("SocketUnit: Connection closed.");
};
// 发生错误
this.socket.onerror = (error) => {
console.error("SocketUnit: WebSocket error:", error);
this.isConnected = false;
};
}
// 断开连接
public disconnect(): void {
if (this.socket && this.isConnected) {
this.socket.close();
this.isConnected = false;
}
this.stopReconnect()
}
// 发送数据
public sendData(data: string): void {
// console.log("SocketUnit: sendData", data);
if (this.socket && this.isConnected) {
this.socket.send(data);
} else {
console.error("SocketUnit: Socket is not connected.");
this.reSendData = data;
this.beginReconnect()
}
}
// 设置数据接收回调
public onDataReceived(callback: (data: string) => void): void {
this.dataReceivedCallback = callback;
}
// 获取连接状态
public get isConnectedStatus(): boolean {
return this.isConnected;
}
//断线重连
private beginReconnect(): void {
if (this.reconnetSwt) {
return
}
this.reconnetSwt = true;
this.reconnectCount = 0;
if (this.reconnectTimer == null) {
this.reconnectTimer = setInterval(() => {
if (this.reconnectCount > this.reconnectMaxCount) {
this.reconnectCount = 0;
this.stopReconnect();
Utils.sendInnerMsg(InnerMsgCode.UI_Socket_Timeout)
return;
}
this._doReconnect();
}, this.reconnectInterval);
}
}
private _doReconnect(): void {
this.reconnectCount++
this.connect(this.url);
}
// 停止重连
private stopReconnect(): void {
if (this.reconnectTimer != null) {
clearInterval(this.reconnectTimer);
this.reconnectTimer = null;
}
this.reconnetSwt = false;
}
}