优化tcp
This commit is contained in:
parent
58d44fbe45
commit
3548124f9f
80
entry/src/main/ets/utils/TcpUtils.ets
Normal file
80
entry/src/main/ets/utils/TcpUtils.ets
Normal file
@ -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<Function> = []
|
||||
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<void> {
|
||||
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<void> {
|
||||
return this.tcp?.close()
|
||||
}
|
||||
|
||||
onMessage(callback: Function) {
|
||||
this.events.push(callback)
|
||||
}
|
||||
|
||||
sendMsg(data: string): Promise<void> {
|
||||
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()
|
||||
Loading…
x
Reference in New Issue
Block a user