diff --git a/NetworkReconnection/entry/src/main/ets/pages/HTTPReconnection.ets b/NetworkReconnection/entry/src/main/ets/pages/HTTPReconnection.ets index 7dfcd942f47f3f7f6256168f712dcf19dd7faf7a..f1c6d2992948b618f303139450fb0ba9a36ef045 100644 --- a/NetworkReconnection/entry/src/main/ets/pages/HTTPReconnection.ets +++ b/NetworkReconnection/entry/src/main/ets/pages/HTTPReconnection.ets @@ -19,6 +19,8 @@ import { common } from "@kit.AbilityKit"; import { promptAction } from '@kit.ArkUI'; import { photoAccessHelper } from '@kit.MediaLibraryKit'; import { CommonConstants } from "../constants/CommonConstants"; +import { BusinessError } from "@kit.BasicServicesKit"; +import { hilog } from "@kit.PerformanceAnalysisKit"; @Component export struct HTTPReconnection { @@ -88,32 +90,39 @@ export struct HTTPReconnection { async httpDownloadFile() { const helper = photoAccessHelper.getPhotoAccessHelper(this.context); - const uri = await helper.createAsset(photoAccessHelper.PhotoType.VIDEO, 'mp4', { title: 'HTTPVideo' }); - const file = fs.openSync(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); - try { - this.httpRequest.on('headersReceive', (header: Object) => { - this.downloadSize = 0; - this.contentLength = new Map(Object.entries(header)).get('content-length') as number; - }); - this.httpRequest.on('dataReceive', (data: ArrayBuffer) => { - fs.writeSync(file.fd, data); - this.downloadSize += data.byteLength; - this.process = Math.floor(this.downloadSize / this.contentLength * 100); - }); + let uri = await helper.createAsset(photoAccessHelper.PhotoType.VIDEO, 'mp4', { title: 'HTTPVideo' }); + fs.open(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE).then((file) => { + try { + this.httpRequest.on('headersReceive', (header: Object) => { + this.downloadSize = 0; + this.contentLength = new Map(Object.entries(header)).get('content-length') as number; + }); + this.httpRequest.on('dataReceive', (data: ArrayBuffer) => { + fs.writeSync(file.fd, data); + this.downloadSize += data.byteLength; + this.process = Math.floor(this.downloadSize / this.contentLength * 100); + }); - this.httpRequest.on('dataEnd', () => { - this.getUIContext().getPromptAction().showToast({ message: $r('app.string.download_success') }); - this.downloadSize = 0; - this.contentLength = 0; - fs.closeSync(file); - this.isDownload = false; - }); + this.httpRequest.on('dataEnd', () => { + this.getUIContext().getPromptAction().showToast({ message: $r('app.string.download_success') }); + this.downloadSize = 0; + this.contentLength = 0; + fs.closeSync(file); + this.isDownload = false; + }); - this.getHttpRequest(CommonConstants.VIDEO_SRC, 3); - } catch (err) { - fs.closeSync(file); - this.isDownload = false; + this.getHttpRequest(CommonConstants.VIDEO_SRC, 3); + } catch (err) { + fs.close(file).catch((err: BusinessError) => { + hilog.error(0xFF00, 'NetworkReconnection', `httpDownloadFile fail, code = ${err.code}, message = ${err.message}`); + }); + this.isDownload = false; + } + }); + } catch (error) { + let err = error as BusinessError; + hilog.error(0xFF00, 'NetworkReconnection', `httpDownloadFile fail, code = ${err.code}, message = ${err.message}`); } } @@ -135,8 +144,12 @@ export struct HTTPReconnection { }); } catch (err) { this.isDownload = false; - this.getUIContext().getPromptAction().showToast({ message: $r('app.string.download_error') }); - this.getUIContext().getPromptAction().showToast({ message: "Download Error" }); + try { + this.getUIContext().getPromptAction().showToast({ message: $r('app.string.download_error') }); + } catch (error) { + let err = error as BusinessError; + hilog.error(0xFF00, 'NetworkReconnection', `showToast fail, code = ${err.code}, message = ${err.message}`); + } return; } } diff --git a/NetworkReconnection/entry/src/main/ets/pages/RCPReconnection.ets b/NetworkReconnection/entry/src/main/ets/pages/RCPReconnection.ets index d53c9c76e7e1d9dae125108d60682b08a9ccc7be..333b3cb4324c132d5f1ce43d12e202575bef41ef 100644 --- a/NetworkReconnection/entry/src/main/ets/pages/RCPReconnection.ets +++ b/NetworkReconnection/entry/src/main/ets/pages/RCPReconnection.ets @@ -20,6 +20,7 @@ import { common } from "@kit.AbilityKit"; import { photoAccessHelper } from '@kit.MediaLibraryKit'; import Logger from '../utils/Logger'; import { CommonConstants } from '../constants/CommonConstants'; +import { BusinessError } from '@kit.BasicServicesKit'; @Component export struct RCPReconnection { @@ -31,7 +32,9 @@ export struct RCPReconnection { private context = this.getUIContext().getHostContext() as common.UIAbilityContext; aboutToDisappear(): void { - this.session.close(); + if (this.session !== null) { + this.session.close(); + } } build() { @@ -88,77 +91,93 @@ export struct RCPReconnection { } // [Start create_rcp_session] - createRCPSession(): rcp.Session { - const customHttpEventsHandler: rcp.HttpEventsHandler = { - onDownloadProgress: (totalSize: number, transferredSize: number) => { - this.contentLength = totalSize; - this.downloadSize = transferredSize; - this.process = this.contentLength === 0 ? 0 : Math.floor(this.downloadSize / this.contentLength * 100); - }, - - onDataEnd: () => { - this.contentLength = -1; - this.downloadSize = 0; - }, - }; - const sessionConfig: rcp.SessionConfiguration = { - requestConfiguration: { - transfer: { - timeout: { - connectMs: 6000, - transferMs: 60000 - } + createRCPSession(): rcp.Session | null { + try { + const customHttpEventsHandler: rcp.HttpEventsHandler = { + onDownloadProgress: (totalSize: number, transferredSize: number) => { + this.contentLength = totalSize; + this.downloadSize = transferredSize; + this.process = this.contentLength === 0 ? 0 : Math.floor(this.downloadSize / this.contentLength * 100); + }, + onDataEnd: () => { + this.contentLength = -1; + this.downloadSize = 0; }, - tracing: { httpEventsHandler: customHttpEventsHandler } + }; + const sessionConfig: rcp.SessionConfiguration = { + requestConfiguration: { + transfer: { + timeout: { + connectMs: 6000, + transferMs: 60000 + } + }, + tracing: { httpEventsHandler: customHttpEventsHandler } + } } + return rcp.createSession(sessionConfig); + } catch (error) { + return null; } - return rcp.createSession(sessionConfig); } // [StartExclude create_rcp_session] rcpDownloadFile() { - this.process = Math.floor(this.downloadSize / this.contentLength * 100); - const helper = photoAccessHelper.getPhotoAccessHelper(this.context); - helper.createAsset(photoAccessHelper.PhotoType.VIDEO, 'mp4', { title: 'RCPVideo' }) - .then((uri) => { - this.getRcpRequest(CommonConstants.VIDEO_SRC, 3) - .then((response) => { - if (response) { - try { - const file = fs.openSync(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); - fs.writeSync(file.fd, response.body); - fs.closeSync(file); - this.isDownload = false; - this.getUIContext().getPromptAction().showToast({ message: $r('app.string.download_success') }); - } catch (err) { - Logger.info(JSON.stringify(err)); - } finally { - this.isDownload = false; + try { + this.process = Math.floor(this.downloadSize / this.contentLength * 100); + const helper = photoAccessHelper.getPhotoAccessHelper(this.context); + helper.createAsset(photoAccessHelper.PhotoType.VIDEO, 'mp4', { title: 'RCPVideo' }) + .then((uri) => { + this.getRcpRequest(CommonConstants.VIDEO_SRC, 3) + .then((response) => { + if (response) { + try { + const file = fs.openSync(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); + fs.writeSync(file.fd, response.body); + fs.closeSync(file); + this.isDownload = false; + this.getUIContext().getPromptAction().showToast({ message: $r('app.string.download_success') }); + } catch (err) { + Logger.info(JSON.stringify(err)); + } finally { + this.isDownload = false; + } } - } - }); - }); + }); + }); + } catch (error) { + let err = error as BusinessError; + Logger.info(JSON.stringify(err)); + } } // [EndExclude create_rcp_session] async getRcpRequest(url: string, retry: number): Promise { try { - return await this.session.get(url) - .then((response) => { - if ((response.statusCode === 408 || response.statusCode === 500) && retry > 0) { - return new Promise((resolve: Function) => { - setTimeout(() => { - resolve(this.getRcpRequest(url, retry - 1)); - }, 2000) - }) - } else { - return response; - } - }) + if (this.session !== null) { + return await this.session.get(url) + .then((response) => { + if ((response.statusCode === 408 || response.statusCode === 500) && retry > 0) { + return new Promise((resolve: Function) => { + setTimeout(() => { + resolve(this.getRcpRequest(url, retry - 1)); + }, 2000) + }) + } else { + return response; + } + }) + } else { + return; + } } catch (err) { - this.getUIContext().getPromptAction().showToast({ message: $r('app.string.download_error') }); - this.getUIContext().getPromptAction().showToast({ message: "Download Error" }); - this.isDownload = false; + try { + this.getUIContext().getPromptAction().showToast({ message: $r('app.string.download_error') }); + this.isDownload = false; + } catch (error) { + let err = error as BusinessError; + Logger.error('NetworkReconnection', `showToast fail, code = ${err.code}, message = ${err.message}`); + } return; } } diff --git a/NetworkReconnection/entry/src/main/ets/pages/SocketReconnection.ets b/NetworkReconnection/entry/src/main/ets/pages/SocketReconnection.ets index 330d93e6c938686fa6062ca8854d861d7eb1e2ad..1ba4c4871bd07bfff3b54e9af1192c6bd4c36c9d 100644 --- a/NetworkReconnection/entry/src/main/ets/pages/SocketReconnection.ets +++ b/NetworkReconnection/entry/src/main/ets/pages/SocketReconnection.ets @@ -118,8 +118,12 @@ export struct SocketReconnection { tcpSocketConnect() { if (!this.netAvailable) { - this.getUIContext().getPromptAction().showToast({ message: $r('app.string.connect_error') }); - this.getUIContext().getPromptAction().showToast({ message: "Connect error" }); + try { + this.getUIContext().getPromptAction().showToast({ message: $r('app.string.connect_error') }); + } catch (error) { + let err = error as BusinessError; + Logger.error('NetworkReconnection', `showToast fail, code = ${err.code}, message = ${err.message}`); + } return; } @@ -143,7 +147,6 @@ export struct SocketReconnection { if (err) { Logger.error('bind fail' + JSON.stringify(err)); this.getUIContext().getPromptAction().showToast({ message: $r('app.string.connect_error') }); - this.getUIContext().getPromptAction().showToast({ message: "Connect error" }); return; } @@ -158,7 +161,6 @@ export struct SocketReconnection { if (err) { Logger.error('connect fail'); this.getUIContext().getPromptAction().showToast({ message: $r('app.string.connect_error') }); - this.getUIContext().getPromptAction().showToast({ message: "Connect error" }); return; } }); @@ -167,12 +169,18 @@ export struct SocketReconnection { // [End on_socket_updated] tcpSocketDisconnect() { - this.tcp?.close(); + this.tcp?.close().catch((err : BusinessError) => { + Logger.error('bind fail' + JSON.stringify(err)); + }); } socketDownloadFile() { if (!this.netAvailable) { - this.getUIContext().getPromptAction().showToast({ message: $r('app.string.net_lost') }); + try { + this.getUIContext().getPromptAction().showToast({ message: $r('app.string.net_lost') }); + } catch (error) { + Logger.error('bind fail' + JSON.stringify(error)); + } return; } this.isDownload = true; @@ -207,38 +215,46 @@ export struct SocketReconnection { } receiveMsgFromServer(value: socket.SocketMessageInfo, file: fs.File) { - let response = buffer.from(value.message); - response.copy(this.receivedDataBuf, this.receivedDataLen); - this.receivedDataLen += value.message.byteLength; + try { + let response = buffer.from(value.message); + response.copy(this.receivedDataBuf, this.receivedDataLen); + this.receivedDataLen += value.message.byteLength; - if (this.fileLength === 0) { - this.fileLength = this.receivedDataBuf.readUInt32BE(); - this.totalSize = this.fileLength + 8 * (this.fileLength / (1024 * 1024) + 1); - } - Logger.info('valueSize:' + response.length + ',receivedDataLen:' + this.receivedDataLen); + if (this.fileLength === 0) { + this.fileLength = this.receivedDataBuf.readUInt32BE(); + this.totalSize = this.fileLength + 8 * (this.fileLength / (1024 * 1024) + 1); + } + Logger.info('valueSize:' + response.length + ',receivedDataLen:' + this.receivedDataLen); - this.process = Math.floor(this.receivedDataLen / this.totalSize * 100); - const sendNum = Math.floor(this.fileLength / (1024 * 1024)); - if (this.receivedDataLen === this.fileLength + 8 * (sendNum + 1)) { - this.saveFile(file, sendNum); + this.process = Math.floor(this.receivedDataLen / this.totalSize * 100); + const sendNum = Math.floor(this.fileLength / (1024 * 1024)); + if (this.receivedDataLen === this.fileLength + 8 * (sendNum + 1)) { + this.saveFile(file, sendNum); + } + } catch (err) { + Logger.error('receiveMsgFromServer fail:' + JSON.stringify(err)); } } saveFile(file: fs.File, sendNum: number) { - for (let i = 0; i <= sendNum; i++) { - const offset = this.receivedDataBuf.readUInt32BE(4 + i * (1024 * 1024 + 8)); - Logger.info('fileLength:' + this.fileLength + ';offset:' + offset); - if (i != sendNum) { - fs.writeSync(file.fd, - this.receivedDataBuf.subarray(8 + i * (1024 * 1024 + 8), (i + 1) * (1024 * 1024 + 8)).buffer, - { offset: offset }); - } else { - fs.writeSync(file.fd, this.receivedDataBuf.subarray(8 + i * (1024 * 1024 + 8), this.receivedDataLen).buffer, - { offset: offset }); - fs.close(file); - this.getUIContext().getPromptAction().showToast({ message: $r('app.string.download_success') }); - this.stateInit(); + try { + for (let i = 0; i <= sendNum; i++) { + const offset = this.receivedDataBuf.readUInt32BE(4 + i * (1024 * 1024 + 8)); + Logger.info('fileLength:' + this.fileLength + ';offset:' + offset); + if (i != sendNum) { + fs.writeSync(file.fd, + this.receivedDataBuf.subarray(8 + i * (1024 * 1024 + 8), (i + 1) * (1024 * 1024 + 8)).buffer, + { offset: offset }); + } else { + fs.writeSync(file.fd, this.receivedDataBuf.subarray(8 + i * (1024 * 1024 + 8), this.receivedDataLen).buffer, + { offset: offset }); + fs.close(file); + this.getUIContext().getPromptAction().showToast({ message: $r('app.string.download_success') }); + this.stateInit(); + } } + } catch (err) { + Logger.error('saveFile fail:' + JSON.stringify(err)); } } diff --git a/ServerSocket/entry/src/main/ets/pages/ServerSocketPage.ets b/ServerSocket/entry/src/main/ets/pages/ServerSocketPage.ets index 751cf2c85db3ae63f900544015d33dbd2ed0e6ff..bfb2acf386b12be472759c4e4b04a2f932a6aa60 100644 --- a/ServerSocket/entry/src/main/ets/pages/ServerSocketPage.ets +++ b/ServerSocket/entry/src/main/ets/pages/ServerSocketPage.ets @@ -40,7 +40,11 @@ struct ServerSocketPage { aboutToDisappear(): void { // Close the connection with the client. - this.socketClient?.close(); + try { + this.socketClient?.close(); + } catch (err) { + Logger.error('NetworkReconnection', `socketClient close, code = ${err.code}, message = ${err.message}`); + } // Unsubscribe from events related to TCP Socket Connection. setTimeout(() => { @@ -122,6 +126,8 @@ struct ServerSocketPage { }).catch((err: BusinessError) => { Logger.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`); }); + }).catch((err: BusinessError) => { + Logger.error('NetworkReconnection', `getWantAgent fail, code = ${err.code}, message = ${err.message}`); }); }