72 lines
2.0 KiB
Plaintext
72 lines
2.0 KiB
Plaintext
/**长连接*/
|
|
export default class SocketUnit {
|
|
private socket: WebSocket | null = null;
|
|
private isConnected: boolean = false;
|
|
|
|
private dataReceivedCallback: (data: any) => void = () => {};
|
|
|
|
// 连接到服务器
|
|
public connect(url: string): void {
|
|
if (this.isConnected) {
|
|
console.log("SocketUnit: Already connected.");
|
|
return;
|
|
}
|
|
|
|
this.socket = new WebSocket(url);
|
|
console.log("SocketUnit: Connecting to -> " + url);
|
|
|
|
// 连接成功
|
|
this.socket.onopen = () => {
|
|
this.isConnected = true;
|
|
console.log("SocketUnit: Connection succ.");
|
|
};
|
|
|
|
// 接收到消息
|
|
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();
|
|
}
|
|
}
|
|
|
|
// 发送数据
|
|
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.");
|
|
}
|
|
}
|
|
|
|
// 设置数据接收回调
|
|
public onDataReceived(callback: (data: string) => void): void {
|
|
this.dataReceivedCallback = callback;
|
|
}
|
|
|
|
// 获取连接状态
|
|
public get isConnectedStatus(): boolean {
|
|
return this.isConnected;
|
|
}
|
|
}
|
|
|