diff --git a/entry/src/main/ets/utils/TcpUtils.ets b/entry/src/main/ets/utils/TcpUtils.ets new file mode 100644 index 00000000..4d060e06 --- /dev/null +++ b/entry/src/main/ets/utils/TcpUtils.ets @@ -0,0 +1,80 @@ +import socket from '@ohos.net.socket' +import { BusinessError } from '@ohos.base' + +const TAG = '[TcpClient]' + + +class 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 = [] + private static instance: TcpClient + + 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(TAG, 'new Tcp', this.localIp, this.localIpPort, this.oppositeIp, this.oppositeIpPort) + this.tcp = socket.constructTCPSocketInstance(); + } + + 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() + } + + onMessage(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) + }) + } +} + +export const tcpClient = new TcpClient() \ No newline at end of file