258 lines
		
	
	
		
			7.6 KiB
		
	
	
	
		
			TypeScript
		
	
	
	
	
	
			
		
		
	
	
			258 lines
		
	
	
		
			7.6 KiB
		
	
	
	
		
			TypeScript
		
	
	
	
	
	
| import socket from '@ohos.net.socket';
 | |
| import hilog from '@ohos.hilog';
 | |
| import { getTCP } from './GlobalTcp';
 | |
| import prompt from '@ohos.prompt';
 | |
| import FileUtil from './File';
 | |
| import { dateFormat } from './tools';
 | |
| 
 | |
| const TAG = 'socketTag[TcpDemo.TcpClient]'
 | |
| 
 | |
| export default class TcpClient {
 | |
|   private localIp: string = ''
 | |
|   private localIpPort: string = ''
 | |
|   private oppositeIp: string = ''
 | |
|   private oppositeIpPort: string = ''
 | |
|   private num: number = 0//重连次数
 | |
|   private tcpSendNum: number = 0//重连次数
 | |
|   private folderPath
 | |
| 
 | |
|   private tcp: any = null
 | |
| 
 | |
|   constructor(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();
 | |
|     this.initPath()
 | |
|   }
 | |
| 
 | |
|   onError(callback?) {
 | |
|     this.tcp.on('error', err => {
 | |
|       // this.writeLog({
 | |
|       //   time:dateFormat(new Date()),
 | |
|       //   PLC:`${TAG} tcpOnerror  ${JSON.stringify(err)}`,
 | |
|       // })
 | |
|       console.log(TAG, 'getCloseTtcpOnerror0000', JSON.stringify(err))
 | |
| 
 | |
|       globalThis.getCloseTcp = true
 | |
| 
 | |
| 
 | |
|       console.log(TAG, 'getCloseTtcpOnerror', JSON.stringify(err))
 | |
|       setTimeout(async () => {
 | |
|         getTCP()
 | |
|       }, 2000)
 | |
|       // this.closeUdp(()=>{
 | |
|       //   this.bindUdp()
 | |
|       // })
 | |
|     });
 | |
|   }
 | |
| 
 | |
| 
 | |
| 
 | |
|   bindTcp() {
 | |
|     this.writeLog({
 | |
|       time:dateFormat(new Date()),
 | |
|       message: `${TAG} tcpbind localIp${this.localIp} ${this.localIpPort}`,
 | |
|     })
 | |
|     console.log(TAG, 'tcpbind', this.localIp, 'localIp', this.localIpPort)
 | |
|     return new Promise((resolve, reject) => {
 | |
|       let promise = this.tcp.bind({
 | |
|         address: this.localIp, port: parseInt(this.localIpPort), family: 1
 | |
|       }, err => {
 | |
|         if (err) {
 | |
|           this.writeLog({
 | |
|             time:dateFormat(new Date()),
 | |
|             message: `${TAG} tcpbind error ${JSON.stringify(err)}`,
 | |
|           })
 | |
|           setTimeout(async () => {
 | |
|             getTCP()
 | |
|           }, 2000)
 | |
|           console.log('getCloseTBinderror');
 | |
|           hilog.info(0x0000, 'testTag', "tcpBinderror:" + JSON.stringify(err));
 | |
|           resolve(true)
 | |
|           return
 | |
|         }
 | |
|         console.log('getCloseTBindsuccess');
 | |
| 
 | |
|         // console.log('testTag tcp bind success');
 | |
|         // this.writeLog({
 | |
|         //   time:dateFormat(new Date()),
 | |
|         //   PLC:`${TAG} testTag tcp bind success`,
 | |
|         // })
 | |
|         resolve(false)
 | |
|       })
 | |
|     })
 | |
| 
 | |
|   }
 | |
| 
 | |
|   connectTcp() {
 | |
|     this.writeLog({
 | |
|       time:dateFormat(new Date()),
 | |
|       message: `${TAG} tcpConnect oppositeIp ${ this.oppositeIp} ${this.oppositeIpPort}`,
 | |
|     })
 | |
|     console.log(TAG, 'tcpConnect', this.oppositeIp, 'localIp', this.oppositeIpPort)
 | |
|     return new Promise((resolve, reject) => {
 | |
|       let promise = this.tcp.connect({
 | |
|         address: {
 | |
|           address: this.oppositeIp, port: parseInt(this.oppositeIpPort), family: 1
 | |
|         }, timeout: 6000
 | |
|       });
 | |
|       promise.then(() => {
 | |
|         console.log('testTagtestTag000',)
 | |
|         this.tcp.setExtraOptions({
 | |
|           keepAlive: true,
 | |
|         }, err => {
 | |
|           if (err) {
 | |
|             console.log('getCloseTconnectsuccess','error',globalThis.getCloseTcp)
 | |
|             this.writeLog({
 | |
|               time:dateFormat(new Date()),
 | |
|               message: `${TAG} TCPconnect error ${JSON.stringify(err)}`,
 | |
|             })
 | |
|             setTimeout(() => {
 | |
|               getTCP()
 | |
|               resolve(false)
 | |
|             }, 9000)
 | |
|             return;
 | |
|           }
 | |
|         });
 | |
|         console.log('getCloseTconnectsuccess');
 | |
| 
 | |
|         console.log('getCloseTcpsocketTagconnect','success',globalThis.getCloseTcp)
 | |
|         globalThis.getCloseTcp = false
 | |
|         resolve(true)
 | |
|       }).catch(err => {
 | |
|         console.log('socketTag','error')
 | |
|         this.writeLog({
 | |
|           time:dateFormat(new Date()),
 | |
|           message: `${TAG} TCPconnect error2 ${JSON.stringify(err)}`,
 | |
|         })
 | |
|         // globalThis.getCloseTcp = true
 | |
| 
 | |
|         setTimeout(() => {
 | |
|           getTCP()
 | |
|           resolve(false)
 | |
|         }, 9000)
 | |
|         // this.writeLog({
 | |
|         //   time:dateFormat(new Date()),
 | |
|         //   PLC:`${TAG} tcp connect  error`,
 | |
|         // })
 | |
|       });
 | |
|     })
 | |
|   }
 | |
| 
 | |
|   sendMsg(msg: string) {
 | |
|     console.log(TAG, 'tcpSend', msg.length, msg)
 | |
|     return new Promise((reslove, reject) => {
 | |
|       let promise = this.tcp.send({
 | |
|         data: msg
 | |
|       });
 | |
|       promise.then(() => {
 | |
|         reslove(true)
 | |
|       }).catch(err => {
 | |
|         this.tcpSendNum++
 | |
|         if(!globalThis.getCloseTcp&&this.tcpSendNum>10){
 | |
|           setTimeout(async () => {
 | |
|             getTCP(true)
 | |
|           }, 3000)
 | |
|           this.tcpSendNum=0
 | |
|           return
 | |
|         }
 | |
|         globalThis.getCloseTcp=true
 | |
|         console.log(`${TAG} TCPsend error ${JSON.stringify(err)}`)
 | |
|         // this.writeLog({
 | |
|         //   time:dateFormat(new Date()),
 | |
|         //   message: `${TAG} TCPsend error ${JSON.stringify(err)}`,
 | |
|         // })
 | |
|         reslove(false)
 | |
|       });
 | |
|     })
 | |
|   }
 | |
| 
 | |
|   onMessage(callback?) {
 | |
|     this.tcp.on('message', value => {
 | |
|       // this.writeLog({
 | |
|       //   time:dateFormat(new Date()),
 | |
|       //   PLC:`${TAG} Tcponmessage`,
 | |
|       // })
 | |
|       console.log(TAG, 'Tcponmessage', value)
 | |
|       globalThis.tcpUdpError = false
 | |
| 
 | |
|       // console.log('messageLengt',,value.message.length))
 | |
|       console.log('testTagtcpmsg')
 | |
|       // console.log("on message, message:" + value.message+ ", remoteInfo:" )
 | |
|       if (value) {
 | |
|         let dataView = new DataView(value.message)
 | |
|         // const Arraybuffer=buffer.from(value.message, 5, dataView?.byteLength);
 | |
|         const Arraybuffer = value.message.slice(5, dataView?.byteLength);
 | |
| 
 | |
|         callback && callback(Arraybuffer)
 | |
|       } else {
 | |
|         callback && callback('')
 | |
|       }
 | |
|       clearInterval(globalThis.intervaltcp)
 | |
|       globalThis.intervaltcp=setInterval(()=>{
 | |
|         //程序断开
 | |
|         if (globalThis.tcpUdpError) {
 | |
|           console.log(TAG,'tcp信号丢失')
 | |
|           // getTCP()
 | |
|           prompt.showToast({
 | |
|             message: 'tcp信号丢失',
 | |
|             duration: 2000
 | |
|           });
 | |
|         }
 | |
|         this.writeLog({
 | |
|           time:dateFormat(new Date()),
 | |
|           message: `${TAG} tcp信号丢失`,
 | |
|         })
 | |
|         globalThis.tcpUdpError = true;
 | |
|       },3000)
 | |
|       // callback(value.message)
 | |
|     });
 | |
|   }
 | |
|   async writeLog(param){
 | |
|     // const fileUtil = new FileUtil(globalThis.context)
 | |
|     // fileUtil.editFile(`${this.folderPath}/plcLog.txt`, JSON.stringify(param)+`\n`)
 | |
|   }
 | |
|   async initPath(){
 | |
|     return
 | |
|     const fileUtil = new FileUtil(globalThis.context)
 | |
|     const date=dateFormat(new Date).split(' ')[0]
 | |
|     this.folderPath = await fileUtil.initFolder(`/PLC/${date}`);
 | |
|   }
 | |
|   offTcp(callback) {
 | |
|     console.log(TAG, 'tcpofff')
 | |
|     this.tcp.off('testTagofmessg', callback);
 | |
|   }
 | |
| 
 | |
|   closeTcp(callback) {
 | |
|     return new Promise((reslove, reject) => {
 | |
|       console.log(TAG, 'tcpClose')
 | |
|       let promise = this.tcp.close();
 | |
|       promise.then(() => {
 | |
|         globalThis.getCloseTcp = true
 | |
|         this.writeLog({
 | |
|           time:dateFormat(new Date()),
 | |
|           message: `${TAG} tcp closeSuccess`,
 | |
|         })
 | |
|         console.log('getCloseTcpsocketTagclose','success',globalThis.getCloseTcp)
 | |
| 
 | |
|         console.log(TAG, 'tcpCloseSuccess')
 | |
|         callback()
 | |
|         reslove(true)
 | |
|       }).catch(err => {
 | |
|         setTimeout(async () => {
 | |
|           getTCP(true)
 | |
|         }, 9000)
 | |
|         this.writeLog({
 | |
|           time:dateFormat(new Date()),
 | |
|           message: `${TAG} tcpclose error ${JSON.stringify(err)}`,
 | |
|         })
 | |
|         console.log('getCloseTcpsocketTagclose','error',globalThis.getCloseTcp)
 | |
| 
 | |
|         reslove(false)
 | |
|       });
 | |
|     })
 | |
|   }
 | |
| } |