import socket from '@ohos.net.socket' import { BusinessError } from '@ohos.base' import { TCPTag } from '../config' export default class TcpClient { private static instance: TcpClient private localIp: string = '' private localIpPort: string = '' private oppositeIp: string = '' private oppositeIpPort: string = '' private tcpSendNum: number = 0 private tcp: socket.TCPSocket = null private events: Array = [] constructor() { if (!TcpClient.instance) { TcpClient.instance = this } return TcpClient.instance } init(tcpLocalIp: string, tcpLocalIpPort: string, tcpOppositeIp: string, tcpOppositePort: string) { this.localIp = tcpLocalIp this.oppositeIp = tcpOppositeIp this.localIpPort = tcpLocalIpPort this.oppositeIpPort = tcpOppositePort console.log(TCPTag, 'new Tcp', this.localIp, this.localIpPort, this.oppositeIp, this.oppositeIpPort) this.tcp = socket.constructTCPSocketInstance(); this.bindTcp() } bindTcp(): Promise { return this.tcp.bind({ address: this.localIp, port: parseInt(this.localIpPort), family: 1 }).then(() => { return this.tcp.connect({ address: { address: this.oppositeIp, port: parseInt(this.oppositeIpPort) }, timeout: 6000 }) }).then(() => { try { this.tcp.on("message", value => { let data = new DataView(value.message) this.events.forEach(cb => { cb(value.message.slice(5, data.byteLength)) }) }) return Promise.resolve() } catch (e) { return Promise.reject(e) } }) } async reBind() { await this.close() this.tcp = socket.constructTCPSocketInstance(); await this.bindTcp() } close(): Promise { return this.tcp?.close() } onMsg(callback: Function) { this.events.push(callback) } sendMsg(data: string): Promise { return this.tcp?.send({ data }).catch(async (err: BusinessError) => { this.tcpSendNum++ if (this.tcpSendNum > 10) { this.tcpSendNum = 0 await this.reBind() } return Promise.reject(err) }) } offMsg(callback: Function) { this.events = this.events.filter(cb => cb !== callback) } }