diff --git a/zh-cn/application-dev/connectivity/http-request.md b/zh-cn/application-dev/connectivity/http-request.md index fd4f938b813ceff5735906c3bfd6e091d1f4422f..ff59559ef3036f24b52f8376b3ed63a93155ef62 100644 --- a/zh-cn/application-dev/connectivity/http-request.md +++ b/zh-cn/application-dev/connectivity/http-request.md @@ -42,47 +42,47 @@ let httpRequest = http.createHttp(); // 用于订阅HTTP响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息 // 从API 8开始,使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+ httpRequest.on('headersReceive', (header) => { - console.info('header: ' + JSON.stringify(header)); + console.info('header: ' + JSON.stringify(header)); }); httpRequest.request( - // 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定 - "EXAMPLE_URL", - { - method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET - // 开发者根据自身业务需要添加header字段 - header: { - 'Content-Type': 'application/json' - }, - // 当使用POST请求时此字段用于传递内容 - extraData: { - "data": "data to send", - }, - expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型 - usingCache: true, // 可选,默认为true - priority: 1, // 可选,默认为1 - connectTimeout: 60000, // 可选,默认为60000ms - readTimeout: 60000, // 可选,默认为60000ms - usingProtocol: http.HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定 - }, (err, data) => { - if (!err) { - // data.result为HTTP响应内容,可根据业务需要进行解析 - console.info('Result:' + JSON.stringify(data.result)); - console.info('code:' + JSON.stringify(data.responseCode)); - // data.header为HTTP响应头,可根据业务需要进行解析 - console.info('header:' + JSON.stringify(data.header)); - console.info('cookies:' + JSON.stringify(data.cookies)); // 8+ - } else { - console.info('error:' + JSON.stringify(err)); - // 取消订阅HTTP响应头事件 - httpRequest.off('headersReceive'); - // 当该请求使用完毕时,调用destroy方法主动销毁 - httpRequest.destroy(); - } + // 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定"EXAMPLE_URL", + { + method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET + // 开发者根据自身业务需要添加header字段 + header: { + 'Content-Type': 'application/json' + }, + // 当使用POST请求时此字段用于传递内容 + extraData: { + "data": "data to send", + }, + expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型 + usingCache: true, // 可选,默认为true + priority: 1, // 可选,默认为1 + connectTimeout: 60000, // 可选,默认为60000ms + readTimeout: 60000, // 可选,默认为60000ms + usingProtocol: http.HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定 + }, (err, data) => { + if (!err) { + // data.result为HTTP响应内容,可根据业务需要进行解析 + console.info('Result:' + JSON.stringify(data.result)); + console.info('code:' + JSON.stringify(data.responseCode)); + // data.header为HTTP响应头,可根据业务需要进行解析 + console.info('header:' + JSON.stringify(data.header)); + console.info('cookies:' + JSON.stringify(data.cookies)); // 8+ + } else { + console.info('error:' + JSON.stringify(err)); + // 取消订阅HTTP响应头事件 + httpRequest.off('headersReceive'); + // 当该请求使用完毕时,调用destroy方法主动销毁 + httpRequest.destroy(); } + } ); ``` ## 相关实例 + 针对HTTP数据请求,有以下相关实例可供参考: - [使用HTTP实现与服务端通信(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/SmartChatEtsOH) \ No newline at end of file diff --git a/zh-cn/application-dev/connectivity/net-sharing.md b/zh-cn/application-dev/connectivity/net-sharing.md index 62b8ea0e8ea6470facad70b1a9edd4b1fe0dac91..c4e0186d8dad9eb51be4f925e2d48db6796c7340 100644 --- a/zh-cn/application-dev/connectivity/net-sharing.md +++ b/zh-cn/application-dev/connectivity/net-sharing.md @@ -1,29 +1,36 @@ # 网络共享 ## 简介 + 网络共享管理分享设备已有网络给其他连接设备,支持Wi-Fi热点共享、蓝牙共享和USB共享,同时提供网络共享状态、共享流量查询功能。 > **说明:** > 为了保证应用的运行效率,大部分API调用都是异步的,对于异步调用的API均提供了callback和Promise两种方式,以下示例均采用callback函数,更多方式可以查阅[API参考](../reference/apis/js-apis-net-sharing.md)。 ## 基本概念 -- WIFI共享:通过WIFI热点共享网络。 -- 蓝牙共享:通过蓝牙共享网络。 -- USB共享:通过USB共享网络。 + +- WIFI共享:通过WIFI热点共享网络。 +- 蓝牙共享:通过蓝牙共享网络。 +- USB共享:通过USB共享网络。 ## 约束 -- 开发语言:C++ JS -- 系统:linux内核 -- 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +- 开发语言:C++ JS +- 系统:linux内核 +- 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 ## 场景介绍 + 网络共享的典型场景有: -- 开启网络共享 -- 停止网络共享 -- 获取共享网络的数据流量 + +- 开启网络共享 +- 停止网络共享 +- 获取共享网络的数据流量 以下分别介绍具体开发方式。 + ## 接口说明 + 完整的JS API说明以及实例代码请参考:[网络共享](../reference/apis/js-apis-net-sharing.md)。 | 类型 | 接口 | 功能说明 | @@ -54,18 +61,18 @@ ```js // 从@ohos.net.sharing中导入sharing命名空间 - import sharing from '@ohos.net.sharing' - - // 注册监听共享状态的改变 - sharing.on('sharingStateChange', (error, data) => { - console.log(JSON.stringify(error)); - console.log(JSON.stringify(data)); - }); - - // 调用startSharing方法,来开启指定类型共享 - sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { - console.log(JSON.stringify(error)); - }); +import sharing from '@ohos.net.sharing' + +// 注册监听共享状态的改变 +sharing.on('sharingStateChange', (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); + +// 调用startSharing方法,来开启指定类型共享 +sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { + console.log(JSON.stringify(error)); +}); ``` ## 停止网络共享 @@ -79,18 +86,18 @@ ```js // 从@ohos.net.sharing中导入sharing命名空间 - import sharing from '@ohos.net.sharing' - - // 注册监听共享状态的改变 - sharing.on('sharingStateChange', (error, data) => { - console.log(JSON.stringify(error)); - console.log(JSON.stringify(data)); - }); - - // 调用stopSharing方法,来停止指定类型共享 - sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { - console.log(JSON.stringify(error)); - }); +import sharing from '@ohos.net.sharing' + +// 注册监听共享状态的改变 +sharing.on('sharingStateChange', (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); + +// 调用stopSharing方法,来停止指定类型共享 +sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { + console.log(JSON.stringify(error)); +}); ``` ## 获取共享网络的数据流量 @@ -104,27 +111,27 @@ ```js // 从@ohos.net.sharing中导入sharing命名空间 - import sharing from '@ohos.net.sharing' - - // 调用startSharing方法,来开启指定类型共享 - sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { - console.log(JSON.stringify(error)); - }); - - // 调用getStatsTotalBytes方法,来获取共享网络数据量 - sharing.getStatsTotalBytes((error, data) => { - console.log(JSON.stringify(error)); - console.log(JSON.stringify(data)); - }); - - // 调用stopSharing方法,来停止指定类型共享,共享网络数据量清零 - sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { - console.log(JSON.stringify(error)); - }); - - // 再次调用getStatsTotalBytes方法,共享网络数据量已清零 - sharing.getStatsTotalBytes((error, data) => { - console.log(JSON.stringify(error)); - console.log(JSON.stringify(data)); - }); +import sharing from '@ohos.net.sharing' + +// 调用startSharing方法,来开启指定类型共享 +sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { + console.log(JSON.stringify(error)); +}); + +// 调用getStatsTotalBytes方法,来获取共享网络数据量 +sharing.getStatsTotalBytes((error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); + +// 调用stopSharing方法,来停止指定类型共享,共享网络数据量清零 +sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { + console.log(JSON.stringify(error)); +}); + +// 再次调用getStatsTotalBytes方法,共享网络数据量已清零 +sharing.getStatsTotalBytes((error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); ``` diff --git a/zh-cn/application-dev/connectivity/socket-connection.md b/zh-cn/application-dev/connectivity/socket-connection.md index de60f2667f0cfb887ffc44836306cdaabfc43aee..63b86a61270626cb75ab8157248b0c57cf12a7cf 100644 --- a/zh-cn/application-dev/connectivity/socket-connection.md +++ b/zh-cn/application-dev/connectivity/socket-connection.md @@ -184,145 +184,144 @@ UDP与TCP流程大体类似,下面以TCP为例: 7. TLSSocket连接使用完毕后,主动关闭。 ```js - import socket from '@ohos.net.socket' - - // 创建一个(双向认证)TLS Socket连接,返回一个TLS Socket对象。 - let tlsTwoWay = socket.constructTLSSocketInstance(); - - // 订阅TLS Socket相关的订阅事件 - tlsTwoWay.on('message', value => { - console.log("on message") - let buffer = value.message - let dataView = new DataView(buffer) - let str = "" - for (let i = 0; i < dataView.byteLength; ++i) { - str += String.fromCharCode(dataView.getUint8(i)) - } - console.log("on connect received:" + str) - }); - tlsTwoWay.on('connect', () => { - console.log("on connect") - }); - tlsTwoWay.on('close', () => { - console.log("on close") - }); - - // 绑定本地IP地址和端口。 - tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { - if (err) { - console.log('bind fail'); - return; - } - console.log('bind success'); - }); - - // 设置通信过程中使用参数 - let options = { - ALPNProtocols: ["spdy/1", "http/1.1"], - - // 连接到指定的IP地址和端口。 - address: { - address: "192.168.xx.xxx", - port: xxxx, // 端口 - family: 1, - }, - - // 设置用于通信过程中完成校验的参数。 - secureOptions: { - key: "xxxx", // 密钥 - cert: "xxxx", // 数字证书 - ca: ["xxxx"], // CA证书 - passwd: "xxxx", // 生成密钥时的密码 - protocols: [socket.Protocol.TLSv12], // 通信协议 - useRemoteCipherPrefer: true, // 是否优先使用对端密码套件 - signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", // 签名算法 - cipherSuite: "AES256-SHA256", // 密码套件 - }, - }; - - // 建立连接 - tlsTwoWay.connect(options, (err, data) => { - console.error(err); - console.log(data); - }); - - // 连接使用完毕后,主动关闭。取消相关事件的订阅。 - tlsTwoWay.close((err) => { - if (err) { - console.log("close callback error = " + err); - } else { - console.log("close success"); - } - tlsTwoWay.off('message'); - tlsTwoWay.off('connect'); - tlsTwoWay.off('close'); - }); - - // 创建一个(单向认证)TLS Socket连接,返回一个TLS Socket对象。 - let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication - - // 订阅TLS Socket相关的订阅事件 - tlsTwoWay.on('message', value => { - console.log("on message") - let buffer = value.message - let dataView = new DataView(buffer) - let str = "" - for (let i = 0;i < dataView.byteLength; ++i) { - str += String.fromCharCode(dataView.getUint8(i)) - } - console.log("on connect received:" + str) - }); - tlsTwoWay.on('connect', () => { - console.log("on connect") - }); - tlsTwoWay.on('close', () => { - console.log("on close") - }); - - // 绑定本地IP地址和端口。 - tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { - if (err) { - console.log('bind fail'); - return; - } - console.log('bind success'); - }); - - // 设置通信过程中使用参数 - let oneWayOptions = { - address: { - address: "192.168.xxx.xxx", - port: xxxx, - family: 1, - }, - secureOptions: { - ca: ["xxxx","xxxx"], // CA证书 - cipherSuite: "AES256-SHA256", // 密码套件 - }, - }; - - // 建立连接 - tlsOneWay.connect(oneWayOptions, (err, data) => { - console.error(err); - console.log(data); - }); - - // 连接使用完毕后,主动关闭。取消相关事件的订阅。 - tlsTwoWay.close((err) => { - if (err) { - console.log("close callback error = " + err); - } else { - console.log("close success"); - } - tlsTwoWay.off('message'); - tlsTwoWay.off('connect'); - tlsTwoWay.off('close'); - }); +// 创建一个(双向认证)TLS Socket连接,返回一个TLS Socket对象。 +let tlsTwoWay = socket.constructTLSSocketInstance(); + +// 订阅TLS Socket相关的订阅事件 +tlsTwoWay.on('message', value => { + console.log("on message") + let buffer = value.message + let dataView = new DataView(buffer) + let str = "" + for (let i = 0; i < dataView.byteLength; ++i) { + str += String.fromCharCode(dataView.getUint8(i)) + } + console.log("on connect received:" + str) +}); +tlsTwoWay.on('connect', () => { + console.log("on connect") +}); +tlsTwoWay.on('close', () => { + console.log("on close") +}); + +// 绑定本地IP地址和端口。 +tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { + if (err) { + console.log('bind fail'); + return; + } + console.log('bind success'); +}); + +// 设置通信过程中使用参数 +let options = { + ALPNProtocols: ["spdy/1", "http/1.1"], + + // 连接到指定的IP地址和端口。 + address: { + address: "192.168.xx.xxx", + port: xxxx, // 端口 + family: 1, + }, + + // 设置用于通信过程中完成校验的参数。 + secureOptions: { + key: "xxxx", // 密钥 + cert: "xxxx", // 数字证书 + ca: ["xxxx"], // CA证书 + passwd: "xxxx", // 生成密钥时的密码 + protocols: [socket.Protocol.TLSv12], // 通信协议 + useRemoteCipherPrefer: true, // 是否优先使用对端密码套件 + signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", // 签名算法 + cipherSuite: "AES256-SHA256", // 密码套件 + }, +}; + +// 建立连接 +tlsTwoWay.connect(options, (err, data) => { + console.error(err); + console.log(data); +}); + +// 连接使用完毕后,主动关闭。取消相关事件的订阅。 +tlsTwoWay.close((err) => { + if (err) { + console.log("close callback error = " + err); + } else { + console.log("close success"); + } + tlsTwoWay.off('message'); + tlsTwoWay.off('connect'); + tlsTwoWay.off('close'); +}); + +// 创建一个(单向认证)TLS Socket连接,返回一个TLS Socket对象。 +let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication + +// 订阅TLS Socket相关的订阅事件 +tlsTwoWay.on('message', value => { + console.log("on message") + let buffer = value.message + let dataView = new DataView(buffer) + let str = "" + for (let i = 0; i < dataView.byteLength; ++i) { + str += String.fromCharCode(dataView.getUint8(i)) + } + console.log("on connect received:" + str) +}); +tlsTwoWay.on('connect', () => { + console.log("on connect") +}); +tlsTwoWay.on('close', () => { + console.log("on close") +}); + +// 绑定本地IP地址和端口。 +tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { + if (err) { + console.log('bind fail'); + return; + } + console.log('bind success'); +}); + +// 设置通信过程中使用参数 +let oneWayOptions = { + address: { + address: "192.168.xxx.xxx", + port: xxxx, + family: 1, + }, + secureOptions: { + ca: ["xxxx", "xxxx"], // CA证书 + cipherSuite: "AES256-SHA256", // 密码套件 + }, +}; + +// 建立连接 +tlsOneWay.connect(oneWayOptions, (err, data) => { + console.error(err); + console.log(data); +}); + +// 连接使用完毕后,主动关闭。取消相关事件的订阅。 +tlsTwoWay.close((err) => { + if (err) { + console.log("close callback error = " + err); + } else { + console.log("close success"); + } + tlsTwoWay.off('message'); + tlsTwoWay.off('connect'); + tlsTwoWay.off('close'); +}); ``` ## 相关实例 针对Socket连接开发,有以下相关实例可供参考: + - [`Socket`:Socket 连接(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-3.2-Release/Network/Socket) - [使用UDP实现与服务端通信(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/UdpDemoOH) - [使用TCP实现与服务端通信(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/TcpSocketDemo) diff --git a/zh-cn/application-dev/connectivity/websocket-connection.md b/zh-cn/application-dev/connectivity/websocket-connection.md index bea530b37cc1b4c04a9907bee399c347929b01e9..52a0b517318cbf994002ffda3d35635bdc67b1eb 100644 --- a/zh-cn/application-dev/connectivity/websocket-connection.md +++ b/zh-cn/application-dev/connectivity/websocket-connection.md @@ -1,13 +1,13 @@ # WebSocket连接 - ## 场景介绍 -使用WebSocket建立服务器与客户端的双向连接,需要先通过createWebSocket()方法创建WebSocket对象,然后通过connect()方法连接到服务器。当连接成功后,客户端会收到open事件的回调,之后客户端就可以通过send()方法与服务器进行通信。当服务器发信息给客户端时,客户端会收到message事件的回调。当客户端不要此连接时,可以通过调用close()方法主动断开连接,之后客户端会收到close事件的回调。 +使用WebSocket建立服务器与客户端的双向连接,需要先通过createWebSocket()方法创建WebSocket对象,然后通过connect()方法连接到服务器。 +当连接成功后,客户端会收到open事件的回调,之后客户端就可以通过send()方法与服务器进行通信。 +当服务器发信息给客户端时,客户端会收到message事件的回调。当客户端不要此连接时,可以通过调用close()方法主动断开连接,之后客户端会收到close事件的回调。 若在上述任一过程中发生错误,客户端会收到error事件的回调。 - ## 接口说明 WebSocket连接功能主要由webSocket模块提供。使用该功能需要申请ohos.permission.INTERNET权限。具体接口说明如下表。 @@ -27,7 +27,6 @@ WebSocket连接功能主要由webSocket模块提供。使用该功能需要申 | on(type: 'error') | 订阅WebSocket的Error事件。 | | off(type: 'error') | 取消订阅WebSocket的Error事件。 | - ## 开发步骤 1. 导入需要的webSocket模块。 @@ -39,52 +38,53 @@ WebSocket连接功能主要由webSocket模块提供。使用该功能需要申 4. 根据URL地址,发起WebSocket连接。 5. 使用完WebSocket连接之后,主动断开连接。 - - ```js - import webSocket from '@ohos.net.webSocket'; - - var defaultIpAddress = "ws://"; - let ws = webSocket.createWebSocket(); - ws.on('open', (err, value) => { - console.log("on open, status:" + JSON.stringify(value)); - // 当收到on('open')事件时,可以通过send()方法与服务器进行通信 - ws.send("Hello, server!", (err, value) => { - if (!err) { - console.log("Message sent successfully"); - } else { - console.log("Failed to send the message. Err:" + JSON.stringify(err)); - } - }); - }); - ws.on('message', (err, value) => { - console.log("on message, message:" + value); - // 当收到服务器的`bye`消息时(此消息字段仅为示意,具体字段需要与服务器协商),主动断开连接 - if (value === 'bye') { - ws.close((err, value) => { - if (!err) { - console.log("Connection closed successfully"); - } else { - console.log("Failed to close the connection. Err: " + JSON.stringify(err)); - } - }); - } - }); - ws.on('close', (err, value) => { - console.log("on close, code is " + value.code + ", reason is " + value.reason); - }); - ws.on('error', (err) => { - console.log("on error, error:" + JSON.stringify(err)); - }); - ws.connect(defaultIpAddress, (err, value) => { - if (!err) { - console.log("Connected successfully"); - } else { - console.log("Connection failed. Err:" + JSON.stringify(err)); - } - }); - ``` + +```js +import webSocket from '@ohos.net.webSocket'; + +var defaultIpAddress = "ws://"; +let ws = webSocket.createWebSocket(); +ws.on('open', (err, value) => { + console.log("on open, status:" + JSON.stringify(value)); + // 当收到on('open')事件时,可以通过send()方法与服务器进行通信 + ws.send("Hello, server!", (err, value) => { + if (!err) { + console.log("Message sent successfully"); + } else { + console.log("Failed to send the message. Err:" + JSON.stringify(err)); + } + }); +}); +ws.on('message', (err, value) => { + console.log("on message, message:" + value); + // 当收到服务器的`bye`消息时(此消息字段仅为示意,具体字段需要与服务器协商),主动断开连接 + if (value === 'bye') { + ws.close((err, value) => { + if (!err) { + console.log("Connection closed successfully"); + } else { + console.log("Failed to close the connection. Err: " + JSON.stringify(err)); + } + }); + } +}); +ws.on('close', (err, value) => { + console.log("on close, code is " + value.code + ", reason is " + value.reason); +}); +ws.on('error', (err) => { + console.log("on error, error:" + JSON.stringify(err)); +}); +ws.connect(defaultIpAddress, (err, value) => { + if (!err) { + console.log("Connected successfully"); + } else { + console.log("Connection failed. Err:" + JSON.stringify(err)); + } +}); +``` ## 相关实例 针对WebSocket连接的开发,有以下相关实例可供参考: + - [`WebSocket`:WebSocket(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-3.2-Release/Network/WebSocket) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-http.md b/zh-cn/application-dev/reference/apis/js-apis-http.md index 6fac1a2f1e58d0e4238614fd4cc9baa34e8fbb03..779e858f3f67a20870cee7df0ce6cd037e3beb00 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-http.md +++ b/zh-cn/application-dev/reference/apis/js-apis-http.md @@ -2,7 +2,7 @@ 本模块提供HTTP数据请求能力。应用可以通过HTTP发起一个数据请求,支持常见的GET、POST、OPTIONS、HEAD、PUT、DELETE、TRACE、CONNECT方法。 ->**说明:** +> **说明:** > >本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > @@ -24,43 +24,43 @@ let httpRequest = http.createHttp(); // 用于订阅HTTP响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息 // 从API 8开始,使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+ httpRequest.on('headersReceive', (header) => { - console.info('header: ' + JSON.stringify(header)); + console.info('header: ' + JSON.stringify(header)); }); httpRequest.request( - // 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定 - "EXAMPLE_URL", - { - method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET - // 开发者根据自身业务需要添加header字段 - header: { - 'Content-Type': 'application/json' - }, - // 当使用POST请求时此字段用于传递内容 - extraData: { - "data": "data to send", - }, - expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型 - usingCache: true, // 可选,默认为true - priority: 1, // 可选,默认为1 - connectTimeout: 60000, // 可选,默认为60000ms - readTimeout: 60000, // 可选,默认为60000ms - usingProtocol: http.HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定 - }, (err, data) => { - if (!err) { - // data.result为HTTP响应内容,可根据业务需要进行解析 - console.info('Result:' + JSON.stringify(data.result)); - console.info('code:' + JSON.stringify(data.responseCode)); - // data.header为HTTP响应头,可根据业务需要进行解析 - console.info('header:' + JSON.stringify(data.header)); - console.info('cookies:' + JSON.stringify(data.cookies)); // 8+ - } else { - console.info('error:' + JSON.stringify(err)); - // 取消订阅HTTP响应头事件 - httpRequest.off('headersReceive'); - // 当该请求使用完毕时,调用destroy方法主动销毁。 - httpRequest.destroy(); - } + // 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定 + "EXAMPLE_URL", + { + method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET + // 开发者根据自身业务需要添加header字段 + header: { + 'Content-Type': 'application/json' + }, + // 当使用POST请求时此字段用于传递内容 + extraData: { + "data": "data to send", + }, + expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型 + usingCache: true, // 可选,默认为true + priority: 1, // 可选,默认为1 + connectTimeout: 60000, // 可选,默认为60000ms + readTimeout: 60000, // 可选,默认为60000ms + usingProtocol: http.HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定 + }, (err, data) => { + if (!err) { + // data.result为HTTP响应内容,可根据业务需要进行解析 + console.info('Result:' + JSON.stringify(data.result)); + console.info('code:' + JSON.stringify(data.responseCode)); + // data.header为HTTP响应头,可根据业务需要进行解析 + console.info('header:' + JSON.stringify(data.header)); + console.info('cookies:' + JSON.stringify(data.cookies)); // 8+ + } else { + console.info('error:' + JSON.stringify(err)); + // 取消订阅HTTP响应头事件 + httpRequest.off('headersReceive'); + // 当该请求使用完毕时,调用destroy方法主动销毁。 + httpRequest.destroy(); } + } ); ``` @@ -82,6 +82,7 @@ createHttp(): HttpRequest ```js import http from '@ohos.net.http'; + let httpRequest = http.createHttp(); ``` @@ -95,8 +96,8 @@ request(url: string, callback: AsyncCallback\):void 根据URL地址,发起HTTP网络请求,使用callback方式作为异步方法。 ->**说明:** ->此接口仅支持数据大小为5M以内的数据传输。 +> **说明:** +> 此接口仅支持数据大小为5M以内的数据传输。 **需要权限**:ohos.permission.INTERNET @@ -121,7 +122,7 @@ request(url: string, callback: AsyncCallback\):void | 2300052 | Server returned nothing (no headers, no data). | | 2300999 | Unknown Other Error. | ->**错误码说明:** +> **错误码说明:** > 以上错误码的详细介绍参见[HTTP错误码](../errorcodes/errorcode-net-http.md)。 > HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) @@ -129,14 +130,14 @@ request(url: string, callback: AsyncCallback\):void ```js httpRequest.request("EXAMPLE_URL", (err, data) => { - if (!err) { - console.info('Result:' + data.result); - console.info('code:' + data.responseCode); - console.info('header:' + JSON.stringify(data.header)); - console.info('cookies:' + data.cookies); // 8+ - } else { - console.info('error:' + JSON.stringify(err)); - } + if (!err) { + console.info('Result:' + data.result); + console.info('code:' + data.responseCode); + console.info('header:' + JSON.stringify(data.header)); + console.info('cookies:' + data.cookies); // 8+ + } else { + console.info('error:' + JSON.stringify(err)); + } }); ``` @@ -146,8 +147,8 @@ request(url: string, options: HttpRequestOptions, callback: AsyncCallback\**说明:** ->此接口仅支持数据大小为5M以内的数据传输。 +> **说明:** +> 此接口仅支持数据大小为5M以内的数据传输。 **需要权限**:ohos.permission.INTERNET @@ -197,7 +198,7 @@ request(url: string, options: HttpRequestOptions, callback: AsyncCallback\**错误码说明:** +> **错误码说明:** > 以上错误码的详细介绍参见[HTTP错误码](../errorcodes/errorcode-net-http.md)。 > HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) @@ -205,25 +206,25 @@ request(url: string, options: HttpRequestOptions, callback: AsyncCallback\ { + }, (err, data) => { if (!err) { - console.info('Result:' + data.result); - console.info('code:' + data.responseCode); - console.info('header:' + JSON.stringify(data.header)); - console.info('cookies:' + data.cookies); // 8+ - console.info('header.Content-Type:' + data.header['Content-Type']); - console.info('header.Status-Line:' + data.header['Status-Line']); + console.info('Result:' + data.result); + console.info('code:' + data.responseCode); + console.info('header:' + JSON.stringify(data.header)); + console.info('cookies:' + data.cookies); // 8+ + console.info('header.Content-Type:' + data.header['Content-Type']); + console.info('header.Status-Line:' + data.header['Status-Line']); } else { - console.info('error:' + JSON.stringify(err)); + console.info('error:' + JSON.stringify(err)); } -}); + }); ``` ### request @@ -232,8 +233,8 @@ request(url: string, options? : HttpRequestOptions): Promise\ 根据URL地址,发起HTTP网络请求,使用Promise方式作为异步方法。 ->**说明:** ->此接口仅支持数据大小为5M以内的数据传输。 +> **说明:** +> 此接口仅支持数据大小为5M以内的数据传输。 **需要权限**:ohos.permission.INTERNET @@ -288,30 +289,30 @@ request(url: string, options? : HttpRequestOptions): Promise\ | 2300094 | An authentication function returned an error. | | 2300999 | Unknown Other Error. | ->**错误码说明:** +> **错误码说明:** > 以上错误码的详细介绍参见[HTTP错误码](../errorcodes/errorcode-net-http.md)。 -> HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) +> HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) **示例:** ```js let promise = httpRequest.request("EXAMPLE_URL", { - method: http.RequestMethod.GET, - connectTimeout: 60000, - readTimeout: 60000, - header: { - 'Content-Type': 'application/json' - } + method: http.RequestMethod.GET, + connectTimeout: 60000, + readTimeout: 60000, + header: { + 'Content-Type': 'application/json' + } }); promise.then((data) => { - console.info('Result:' + data.result); - console.info('code:' + data.responseCode); - console.info('header:' + JSON.stringify(data.header)); - console.info('cookies:' + data.cookies); // 8+ - console.info('header.Content-Type:' + data.header['Content-Type']); - console.info('header.Status-Line:' + data.header['Status-Line']); + console.info('Result:' + data.result); + console.info('code:' + data.responseCode); + console.info('header:' + JSON.stringify(data.header)); + console.info('cookies:' + data.cookies); // 8+ + console.info('header.Content-Type:' + data.header['Content-Type']); + console.info('header.Status-Line:' + data.header['Status-Line']); }).catch((err) => { - console.info('error:' + JSON.stringify(err)); + console.info('error:' + JSON.stringify(err)); }); ``` @@ -337,8 +338,8 @@ on(type: 'headerReceive', callback: AsyncCallback\): void 订阅HTTP Response Header 事件。 ->**说明:** ->此接口已废弃,建议使用[on('headersReceive')8+](#onheadersreceive8)替代。 +> **说明:** +> 此接口已废弃,建议使用[on('headersReceive')8+](#onheadersreceive8)替代。 **系统能力**:SystemCapability.Communication.NetStack @@ -353,7 +354,7 @@ on(type: 'headerReceive', callback: AsyncCallback\): void ```js httpRequest.on('headerReceive', (data) => { - console.info('error:' + JSON.stringify(data)); + console.info('error:' + JSON.stringify(data)); }); ``` @@ -363,7 +364,7 @@ off(type: 'headerReceive', callback?: AsyncCallback\): void 取消订阅HTTP Response Header 事件。 ->**说明:** +> **说明:** > >1. 此接口已废弃,建议使用[off('headersReceive')8+](#offheadersreceive8)替代。 > @@ -403,7 +404,7 @@ on(type: 'headersReceive', callback: Callback\): void ```js httpRequest.on('headersReceive', (header) => { - console.info('header: ' + JSON.stringify(header)); + console.info('header: ' + JSON.stringify(header)); }); ``` @@ -413,8 +414,8 @@ off(type: 'headersReceive', callback?: Callback\): void 取消订阅HTTP Response Header 事件。 ->**说明:** ->可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 +> **说明:** +> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 **系统能力**:SystemCapability.Communication.NetStack @@ -450,7 +451,7 @@ once(type: 'headersReceive', callback: Callback\): void ```js httpRequest.once('headersReceive', (header) => { - console.info('header: ' + JSON.stringify(header)); + console.info('header: ' + JSON.stringify(header)); }); ``` @@ -462,11 +463,11 @@ httpRequest.once('headersReceive', (header) => { | 名称 | 类型 | 必填 | 说明 | | -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | -| method | [RequestMethod](#requestmethod) | 否 | 请求方式。 | -| extraData | string \| Object \| ArrayBuffer6+ | 否 | 发送请求的额外数据。
- 当HTTP请求为POST、PUT等方法时,此字段为HTTP请求的content。
- 当HTTP请求为GET、OPTIONS、DELETE、TRACE、CONNECT等方法时,此字段为HTTP请求的参数补充,参数内容会拼接到URL中进行发送。6+
- 开发者传入string对象,开发者需要自行编码,将编码后的string传入。6+ | -| expectDataType9+ | [HttpDataType](#httpdatatype9) | 否 | 指定返回数据的类型。如果设置了此参数,系统将优先返回指定的类型。 | +| method | [RequestMethod](#requestmethod) | 否 | 请求方式,默认为GET。 | +| extraData | string6+ \| Object6+ \| ArrayBuffer8+ | 否 | 发送请求的额外数据,默认无此字段。
- 当HTTP请求为POST、PUT等方法时,此字段为HTTP请求的content,以UTF-8编码形式作为请求体。6+
- 当HTTP请求为GET、OPTIONS、DELETE、TRACE、CONNECT等方法时,此字段为HTTP请求参数的补充。开发者需传入Encode编码后的string类型参数,Object类型的参数无需预编码,参数内容会拼接到URL中进行发送;ArrayBuffer类型的参数不会做拼接处理。6+ | +| expectDataType9+ | [HttpDataType](#httpdatatype9) | 否 | 指定返回数据的类型,默认无此字段。如果设置了此参数,系统将优先返回指定的类型。 | | usingCache9+ | boolean | 否 | 是否使用缓存,默认为true。 | -| priority9+ | number | 否 | 优先级,范围\[1,1000],默认是1。 | +| priority9+ | number | 否 | 优先级,范围\[0,1000],默认是0。 | | header | Object | 否 | HTTP请求头字段。默认{'Content-Type': 'application/json'}。 | | readTimeout | number | 否 | 读取超时时间。单位为毫秒(ms),默认为60000ms。 | | connectTimeout | number | 否 | 连接超时时间。单位为毫秒(ms),默认为60000ms。 | @@ -541,10 +542,10 @@ request方法回调函数的返回值类型。 | 名称 | 类型 | 必填 | 说明 | | -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | -| result | string \| Object \| ArrayBuffer6+ | 是 | HTTP请求根据响应头中Content-type类型返回对应的响应格式内容:
- application/json:返回JSON格式的字符串,如需HTTP响应具体内容,需开发者自行解析
- application/octet-stream:ArrayBuffer
- 其他:string | -| resultType9+ | [HttpDataType](#httpdatatype9) | 是 | 返回值类型。 | +| result | string6+ \| Objectdeprecated 8+ \| ArrayBuffer8+ | 是 | HTTP请求根据响应头中Content-type类型返回对应的响应格式内容:
- application/json:返回JSON格式的字符串,如需HTTP响应具体内容,需开发者自行解析
- application/octet-stream:ArrayBuffer
- 其他:string | +| resultType9+ | [HttpDataType](#httpdatatype9) | 是 | 返回值类型。 | | responseCode | [ResponseCode](#responsecode) \| number | 是 | 回调函数执行成功时,此字段为[ResponseCode](#responsecode)。若执行失败,错误码将会从AsyncCallback中的err字段返回。 | -| header | Object | 是 | 发起HTTP请求返回来的响应头。当前返回的是JSON格式字符串,如需具体字段内容,需开发者自行解析。常见字段及解析方式如下:
- Content-Type:header['Content-Type'];
- Status-Line:header['Status-Line'];
- Date:header.Date/header['Date'];
- Server:header.Server/header['Server']; | +| header | Object | 是 | 发起HTTP请求返回来的响应头。当前返回的是JSON格式字符串,如需具体字段内容,需开发者自行解析。常见字段及解析方式如下:
- content-type:header['content-type'];
- status-line:header['status-line'];
- date:header.date/header['date'];
- server:header.server/header['server']; | | cookies8+ | string | 是 | 服务器返回的 cookies。 | ## http.createHttpResponseCache9+ @@ -571,6 +572,7 @@ createHttpResponseCache(cacheSize?: number): HttpResponseCache ```js import http from '@ohos.net.http'; + let httpResponseCache = http.createHttpResponseCache(); ``` @@ -653,6 +655,7 @@ httpResponseCache.delete(err => { console.info('delete success'); }); ``` + ### delete9+ delete(): Promise\ diff --git a/zh-cn/application-dev/reference/apis/js-apis-net-connection.md b/zh-cn/application-dev/reference/apis/js-apis-net-connection.md index 254046cd7ba5e3618d475708d1b3952665081532..88b20ef52f74585984bd349f605253d60661d4c1 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-net-connection.md +++ b/zh-cn/application-dev/reference/apis/js-apis-net-connection.md @@ -10,6 +10,7 @@ ```js import connection from '@ohos.net.connection' ``` + ## connection.createNetConnection createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection @@ -34,14 +35,14 @@ createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnectio **示例:** ```js -// 关注默认网络 +// 关注默认网络, 不需要传参 let netConnection = connection.createNetConnection() -// 关注蜂窝网络 +// 关注蜂窝网络,需要传入相关网络特征,timeout参数未传入说明未使用超时时间,此时timeout为0 let netConnectionCellular = connection.createNetConnection({ - netCapabilities: { - bearerTypes: [connection.NetBearType.BEARER_CELLULAR] - } + netCapabilities: { + bearerTypes: [connection.NetBearType.BEARER_CELLULAR] + } }) ``` @@ -73,8 +74,8 @@ getDefaultNet(callback: AsyncCallback\): void ```js connection.getDefaultNet(function (error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) }) ``` @@ -106,7 +107,7 @@ getDefaultNet(): Promise\ ```js connection.getDefaultNet().then(function (data) { - console.log(JSON.stringify(data)) + console.log(JSON.stringify(data)) }) ``` @@ -164,9 +165,9 @@ getAppNet(callback: AsyncCallback\): void **示例:** ```js -connection.getAppNet(function(error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) +connection.getAppNet(function (error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) }) ``` @@ -195,9 +196,9 @@ getAppNet(): Promise\; ```js connection.getAppNet().then((data) => { - console.info(JSON.stringify(data)); + console.info(JSON.stringify(data)); }).catch(error => { - console.info(JSON.stringify(error)); + console.info(JSON.stringify(error)); }) ``` @@ -232,10 +233,10 @@ setAppNet(netHandle: NetHandle, callback: AsyncCallback\): void ```js connection.getDefaultNet(function (error, netHandle) { - connection.setAppNet(netHandle, (error, data) => { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) - }); + connection.setAppNet(netHandle, (error, data) => { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) + }); }) ``` @@ -275,11 +276,11 @@ setAppNet(netHandle: NetHandle): Promise\; ```js connection.getDefaultNet().then(function (netHandle) { - connection.setAppNet(netHandle).then(() => { - console.log("success") - }).catch(error => { - console.log(JSON.stringify(error)) - }) + connection.setAppNet(netHandle).then(() => { + console.log("success") + }).catch(error => { + console.log(JSON.stringify(error)) + }) }) ``` @@ -311,8 +312,8 @@ getAllNets(callback: AsyncCallback<Array<NetHandle>>): void ```js connection.getAllNets(function (error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) }); ``` @@ -344,7 +345,7 @@ getAllNets(): Promise<Array<NetHandle>> ```js connection.getAllNets().then(function (data) { - console.log(JSON.stringify(data)) + console.log(JSON.stringify(data)) }); ``` @@ -379,10 +380,10 @@ getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\ ```js connection.getDefaultNet().then(function (netHandle) { - connection.getConnectionProperties(netHandle).then(function (data) { - console.log(JSON.stringify(data)) - }) + connection.getConnectionProperties(netHandle).then(function (data) { + console.log(JSON.stringify(data)) + }) }) ``` @@ -459,10 +460,10 @@ getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback\ ```js connection.getDefaultNet().then(function (netHandle) { - connection.getNetCapabilities(netHandle).then(function (data) { - console.log(JSON.stringify(data)) - }) + connection.getNetCapabilities(netHandle).then(function (data) { + console.log(JSON.stringify(data)) + }) }) ``` @@ -536,8 +537,8 @@ isDefaultNetMetered(callback: AsyncCallback\): void ```js connection.isDefaultNetMetered(function (error, data) { - console.log(JSON.stringify(error)) - console.log('data: ' + data) + console.log(JSON.stringify(error)) + console.log('data: ' + data) }) ``` @@ -569,7 +570,7 @@ isDefaultNetMetered(): Promise\ ```js connection.isDefaultNetMetered().then(function (data) { - console.log('data: ' + data) + console.log('data: ' + data) }) ``` @@ -601,8 +602,8 @@ hasDefaultNet(callback: AsyncCallback\): void ```js connection.hasDefaultNet(function (error, data) { - console.log(JSON.stringify(error)) - console.log('data: ' + data) + console.log(JSON.stringify(error)) + console.log('data: ' + data) }) ``` @@ -634,7 +635,7 @@ hasDefaultNet(): Promise\ ```js connection.hasDefaultNet().then(function (data) { - console.log('data: ' + data) + console.log('data: ' + data) }) ``` @@ -667,7 +668,7 @@ enableAirplaneMode(callback: AsyncCallback\): void ```js connection.enableAirplaneMode(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) ``` @@ -700,7 +701,7 @@ enableAirplaneMode(): Promise\ ```js connection.enableAirplaneMode().then(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) ``` @@ -733,7 +734,7 @@ disableAirplaneMode(callback: AsyncCallback\): void ```js connection.disableAirplaneMode(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) ``` @@ -766,7 +767,7 @@ disableAirplaneMode(): Promise\ ```js connection.disableAirplaneMode().then(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) ``` @@ -774,8 +775,7 @@ connection.disableAirplaneMode().then(function (error) { reportNetConnected(netHandle: NetHandle, callback: AsyncCallback<void>): void -向网络管理报告网络处于可用状态,调用此接口说明应用程序认为网络的可用性(ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED)与网络管理不一致。 -使用callback方式作为异步方法。 +向网络管理报告网络处于可用状态,使用callback方式作为异步方法。 **需要权限**:ohos.permission.GET_NETWORK_INFO 和 ohos.permission.INTERNET @@ -802,9 +802,9 @@ reportNetConnected(netHandle: NetHandle, callback: AsyncCallback<void>): v ```js connection.getDefaultNet().then(function (netHandle) { - connection.reportNetConnected(netHandle, function (error) { - console.log(JSON.stringify(error)) - }); + connection.reportNetConnected(netHandle, function (error) { + console.log(JSON.stringify(error)) + }); }); ``` @@ -812,8 +812,7 @@ connection.getDefaultNet().then(function (netHandle) { reportNetConnected(netHandle: NetHandle): Promise<void> -向网络管理报告网络处于可用状态,调用此接口说明应用程序认为网络的可用性(ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED)与网络管理不一致。 -使用Promise方式作为异步方法。 +向网络管理报告网络处于可用状态,使用Promise方式作为异步方法。 **需要权限**:ohos.permission.GET_NETWORK_INFO 和 ohos.permission.INTERNET @@ -844,9 +843,9 @@ reportNetConnected(netHandle: NetHandle): Promise<void> ```js connection.getDefaultNet().then(function (netHandle) { - connection.reportNetConnected(netHandle).then(function () { - console.log(`report success`) - }); + connection.reportNetConnected(netHandle).then(function () { + console.log(`report success`) + }); }); ``` @@ -854,8 +853,7 @@ connection.getDefaultNet().then(function (netHandle) { reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback<void>): void -向网络管理报告网络处于不可用状态,调用此接口说明应用程序认为网络的可用性(ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED)与网络管理不一致。 -使用callback方式作为异步方法。 +向网络管理报告网络处于不可用状态,使用callback方式作为异步方法。 **需要权限**:ohos.permission.GET_NETWORK_INFO 和 ohos.permission.INTERNET @@ -882,9 +880,9 @@ reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback<void>) ```js connection.getDefaultNet().then(function (netHandle) { - connection.reportNetDisconnected(netHandle, function (error) { - console.log(JSON.stringify(error)) - }); + connection.reportNetDisconnected(netHandle, function (error) { + console.log(JSON.stringify(error)) + }); }); ``` @@ -892,8 +890,7 @@ connection.getDefaultNet().then(function (netHandle) { reportNetDisconnected(netHandle: NetHandle): Promise<void> -向网络管理报告网络处于不可用状态,调用此接口说明应用程序认为网络的可用性(ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED)与网络管理不一致。 -使用Promise方式作为异步方法。 +向网络管理报告网络处于不可用状态,使用Promise方式作为异步方法。 **需要权限**:ohos.permission.GET_NETWORK_INFO 和 ohos.permission.INTERNET @@ -924,9 +921,9 @@ reportNetDisconnected(netHandle: NetHandle): Promise<void> ```js connection.getDefaultNet().then(function (netHandle) { - connection.reportNetDisconnected(netHandle).then(function () { - console.log(`report success`) - }); + connection.reportNetDisconnected(netHandle).then(function () { + console.log(`report success`) + }); }); ``` @@ -962,8 +959,8 @@ getAddressesByName(host: string, callback: AsyncCallback\>): ```js let host = "xxxx"; connection.getAddressesByName(host, function (error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) }) ``` @@ -1004,7 +1001,7 @@ getAddressesByName(host: string): Promise\> ```js let host = "xxxx"; connection.getAddressesByName(host).then(function (data) { - console.log(JSON.stringify(data)) + console.log(JSON.stringify(data)) }) ``` @@ -1038,12 +1035,11 @@ register(callback: AsyncCallback\): void | 2101008 | The callback is not exists. | | 2101022 | The number of requests exceeded the maximum. | - **示例:** ```js netConnection.register(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) ``` @@ -1073,7 +1069,7 @@ unregister(callback: AsyncCallback\): void ```js netConnection.unregister(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) ``` @@ -1102,17 +1098,17 @@ let netCon = connection.createNetConnection() // 先使用register接口注册订阅事件 netCon.register(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) // 订阅网络可用事件。调用register后,才能接收到此事件通知 netCon.on('netAvailable', function (data) { - console.log(JSON.stringify(data)) + console.log(JSON.stringify(data)) }) // 使用unregister接口取消订阅 netCon.unregister(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) ``` @@ -1141,17 +1137,17 @@ let netCon = connection.createNetConnection() // 先使用register接口注册订阅事件 netCon.register(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) // 订阅网络阻塞状态事件。调用register后,才能接收到此事件通知 netCon.on('netBlockStatusChange', function (data) { - console.log(JSON.stringify(data)) + console.log(JSON.stringify(data)) }) // 使用unregister接口取消订阅 netCon.unregister(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) ``` @@ -1180,23 +1176,24 @@ let netCon = connection.createNetConnection() // 先使用register接口注册订阅事件 netCon.register(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) // 订阅网络能力变化事件。调用register后,才能接收到此事件通知 netCon.on('netCapabilitiesChange', function (data) { - console.log(JSON.stringify(data)) + console.log(JSON.stringify(data)) }) // 使用unregister接口取消订阅 netCon.unregister(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) ``` ### on('netConnectionPropertiesChange') -on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void +on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHandle, connectionProperties: +ConnectionProperties }>): void 订阅网络连接信息变化事件。 @@ -1219,17 +1216,17 @@ let netCon = connection.createNetConnection() // 先使用register接口注册订阅事件 netCon.register(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) // 订阅网络连接信息变化事件。调用register后,才能接收到此事件通知 netCon.on('netConnectionPropertiesChange', function (data) { - console.log(JSON.stringify(data)) + console.log(JSON.stringify(data)) }) // 使用unregister接口取消订阅 netCon.unregister(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) ``` @@ -1258,17 +1255,17 @@ let netCon = connection.createNetConnection() // 先使用register接口注册订阅事件 netCon.register(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) // 订阅网络丢失事件。调用register后,才能接收到此事件通知 netCon.on('netLost', function (data) { - console.log(JSON.stringify(data)) + console.log(JSON.stringify(data)) }) // 使用unregister接口取消订阅 netCon.unregister(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) ``` @@ -1297,17 +1294,17 @@ let netCon = connection.createNetConnection() // 先使用register接口注册订阅事件 netCon.register(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) // 订阅网络不可用事件。调用register后,才能接收到此事件通知 netCon.on('netUnavailable', function (data) { - console.log(JSON.stringify(data)) + console.log(JSON.stringify(data)) }) // 使用unregister接口取消订阅 netCon.unregister(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) ``` @@ -1353,48 +1350,51 @@ bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\): ```js import socket from "@ohos.net.socket"; + connection.getDefaultNet().then((netHandle) => { - var tcp = socket.constructTCPSocketInstance(); - var udp = socket.constructUDPSocketInstance(); - let socketType = "TCPSocket"; - if (socketType == "TCPSocket") { - tcp.bind({ - address: '192.168.xx.xxx', port: 8080, family: 1 - }, error => { - if (error) { - console.log('bind fail'); - } - netHandle.bindSocket(tcp, (error, data) => { - if (error) { - console.log(JSON.stringify(error)); - } else { - console.log(JSON.stringify(data)); - } - }) - }) - } else { - let callback = value => { - console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); + var tcp = socket.constructTCPSocketInstance(); + var udp = socket.constructUDPSocketInstance(); + let socketType = "TCPSocket"; + if (socketType == "TCPSocket") { + tcp.bind({ + address: '192.168.xx.xxx', port: 8080, family: 1 + }, error => { + if (error) { + console.log('bind fail'); + return; + } + netHandle.bindSocket(tcp, (error, data) => { + if (error) { + console.log(JSON.stringify(error)); + } else { + console.log(JSON.stringify(data)); } - udp.on('message', callback); - udp.bind({ - address: '192.168.xx.xxx', port: 8080, family: 1 - }, error => { - if (error) { - console.log('bind fail'); - } - udp.on('message', (data) => { - console.log(JSON.stringify(data)) - }); - netHandle.bindSocket(udp, (error, data) => { - if (error) { - console.log(JSON.stringify(error)); - } else { - console.log(JSON.stringify(data)); - } - }) - }) + }) + }) + } else { + let callback = value => { + console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); } + udp.on('message', callback); + udp.bind({ + address: '192.168.xx.xxx', port: 8080, family: 1 + }, error => { + if (error) { + console.log('bind fail'); + return; + } + udp.on('message', (data) => { + console.log(JSON.stringify(data)) + }); + netHandle.bindSocket(udp, (error, data) => { + if (error) { + console.log(JSON.stringify(error)); + } else { + console.log(JSON.stringify(data)); + } + }) + }) + } }) ``` @@ -1431,44 +1431,47 @@ bindSocket(socketParam: TCPSocket \| UDPSocket): Promise\; ```js import socket from "@ohos.net.socket"; + connection.getDefaultNet().then((netHandle) => { - var tcp = socket.constructTCPSocketInstance(); - var udp = socket.constructUDPSocketInstance(); - let socketType = "TCPSocket"; - if (socketType == "TCPSocket") { - tcp.bind({ - address: '192.168.xx.xxx', port: 8080, family: 1 - }, error => { - if (error) { - console.log('bind fail'); - } - netHandle.bindSocket(tcp).then((data) => { - console.log(JSON.stringify(data)); - }).catch(error => { - console.log(JSON.stringify(error)); - }) - }) - } else { - let callback = value => { - console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); - } - udp.on('message', callback); - udp.bind({ - address: '192.168.xx.xxx', port: 8080, family: 1 - }, error => { - if (error) { - console.log('bind fail'); - } - udp.on('message', (data) => { - console.log(JSON.stringify(data)); - }) - netHandle.bindSocket(udp).then((data) => { - console.log(JSON.stringify(data)); - }).catch(error => { - console.log(JSON.stringify(error)); - }) - }) + var tcp = socket.constructTCPSocketInstance(); + var udp = socket.constructUDPSocketInstance(); + let socketType = "TCPSocket"; + if (socketType == "TCPSocket") { + tcp.bind({ + address: '192.168.xx.xxx', port: 8080, family: 1 + }, error => { + if (error) { + console.log('bind fail'); + return; + } + netHandle.bindSocket(tcp).then((data) => { + console.log(JSON.stringify(data)); + }).catch(error => { + console.log(JSON.stringify(error)); + }) + }) + } else { + let callback = value => { + console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); } + udp.on('message', callback); + udp.bind({ + address: '192.168.xx.xxx', port: 8080, family: 1 + }, error => { + if (error) { + console.log('bind fail'); + return; + } + udp.on('message', (data) => { + console.log(JSON.stringify(data)); + }) + netHandle.bindSocket(udp).then((data) => { + console.log(JSON.stringify(data)); + }).catch(error => { + console.log(JSON.stringify(error)); + }) + }) + } }) ``` @@ -1503,11 +1506,11 @@ getAddressesByName(host: string, callback: AsyncCallback\>): ```js connection.getDefaultNet().then(function (netHandle) { - let host = "xxxx"; - netHandle.getAddressesByName(host, function (error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) - }) + let host = "xxxx"; + netHandle.getAddressesByName(host, function (error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) + }) }) ``` @@ -1547,10 +1550,10 @@ getAddressesByName(host: string): Promise\> ```js connection.getDefaultNet().then(function (netHandle) { - let host = "xxxx"; - netHandle.getAddressesByName(host).then(function (data) { - console.log(JSON.stringify(data)) - }) + let host = "xxxx"; + netHandle.getAddressesByName(host).then(function (data) { + console.log(JSON.stringify(data)) + }) }) ``` @@ -1585,11 +1588,11 @@ getAddressByName(host: string, callback: AsyncCallback\): void ```js connection.getDefaultNet().then(function (netHandle) { - let host = "xxxx"; - netHandle.getAddressByName(host, function (error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) - }) + let host = "xxxx"; + netHandle.getAddressByName(host, function (error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) + }) }) ``` @@ -1629,10 +1632,10 @@ getAddressByName(host: string): Promise\ ```js connection.getDefaultNet().then(function (netHandle) { - let host = "xxxx"; - netHandle.getAddressByName(host).then(function (data) { - console.log(JSON.stringify(data)) - }) + let host = "xxxx"; + netHandle.getAddressByName(host).then(function (data) { + console.log(JSON.stringify(data)) + }) }) ``` @@ -1732,8 +1735,8 @@ connection.getDefaultNet().then(function (netHandle) { **系统能力**:SystemCapability.Communication.NetManager.Core -| 名称 | 类型 | 必填 | 说明 | +| 名称 | 类型 | 必填 | 说明 | | ------- | ------ | -- |------------------------------ | -| address | string | 是 |地址。 | +| address | string | 是 |地址。 | | family | number | 否 |IPv4 = 1,IPv6 = 2,默认IPv4。 | -| port | number | 否 |端口,取值范围\[0, 65535]。 | +| port | number | 否 |端口,取值范围\[0, 65535]。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md b/zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md index 982f8ac0517be4ed950af8dd73504753a582ac3d..f7ca1d622efc3bc8cbffbf620c055a264ad6edb2 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md +++ b/zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md @@ -48,19 +48,19 @@ setIfaceConfig(iface: string, ic: InterfaceConfiguration, callback: AsyncCallbac ```js ethernet.setIfaceConfig("eth0", { - mode: 0, - ipAddr: "192.168.xx.xxx", - route: "192.168.xx.xxx", - gateway: "192.168.xx.xxx", - netMask: "255.255.255.0", - dnsServers: "1.1.1.1", - domain: "2.2.2.2" + mode: 0, + ipAddr: "192.168.xx.xxx", + route: "192.168.xx.xxx", + gateway: "192.168.xx.xxx", + netMask: "255.255.255.0", + dnsServers: "1.1.1.1", + domain: "2.2.2.2" }, (error) => { - if (error) { - console.log("setIfaceConfig callback error = " + JSON.stringify(error)); - } else { - console.log("setIfaceConfig callback ok "); - } + if (error) { + console.log("setIfaceConfig callback error = " + JSON.stringify(error)); + } else { + console.log("setIfaceConfig callback ok "); + } }); ``` @@ -106,17 +106,17 @@ setIfaceConfig(iface: string, ic: InterfaceConfiguration): Promise\ ```js ethernet.setIfaceConfig("eth0", { - mode: 0, - ipAddr: "192.168.xx.xxx", - route: "192.168.xx.xxx", - gateway: "192.168.xx.xxx", - netMask: "255.255.255.0", - dnsServers: "1.1.1.1", - domain: "2.2.2.2" + mode: 0, + ipAddr: "192.168.xx.xxx", + route: "192.168.xx.xxx", + gateway: "192.168.xx.xxx", + netMask: "255.255.255.0", + dnsServers: "1.1.1.1", + domain: "2.2.2.2" }).then(() => { - console.log("setIfaceConfig promise ok "); + console.log("setIfaceConfig promise ok "); }).catch(error => { - console.log("setIfaceConfig promise error = " + JSON.stringify(error)); + console.log("setIfaceConfig promise error = " + JSON.stringify(error)); }); ``` @@ -154,17 +154,17 @@ getIfaceConfig(iface: string, callback: AsyncCallback\): ```js ethernet.getIfaceConfig("eth0", (error, value) => { - if (error) { - console.log("getIfaceConfig callback error = " + JSON.stringify(error)); - } else { - console.log("getIfaceConfig callback mode = " + JSON.stringify(value.mode)); - console.log("getIfaceConfig callback ipAddr = " + JSON.stringify(value.ipAddr)); - console.log("getIfaceConfig callback route = " + JSON.stringify(value.route)); - console.log("getIfaceConfig callback gateway = " + JSON.stringify(value.gateway)); - console.log("getIfaceConfig callback netMask = " + JSON.stringify(value.netMask)); - console.log("getIfaceConfig callback dnsServers = " + JSON.stringify(value.dnsServers)); - console.log("getIfaceConfig callback domain = " + JSON.stringify(value.domain)); - } + if (error) { + console.log("getIfaceConfig callback error = " + JSON.stringify(error)); + } else { + console.log("getIfaceConfig callback mode = " + JSON.stringify(value.mode)); + console.log("getIfaceConfig callback ipAddr = " + JSON.stringify(value.ipAddr)); + console.log("getIfaceConfig callback route = " + JSON.stringify(value.route)); + console.log("getIfaceConfig callback gateway = " + JSON.stringify(value.gateway)); + console.log("getIfaceConfig callback netMask = " + JSON.stringify(value.netMask)); + console.log("getIfaceConfig callback dnsServers = " + JSON.stringify(value.dnsServers)); + console.log("getIfaceConfig callback domain = " + JSON.stringify(value.domain)); + } }); ``` @@ -207,15 +207,15 @@ getIfaceConfig(iface: string): Promise\ ```js ethernet.getIfaceConfig("eth0").then((data) => { - console.log("getIfaceConfig promise mode = " + JSON.stringify(data.mode)); - console.log("getIfaceConfig promise ipAddr = " + JSON.stringify(data.ipAddr)); - console.log("getIfaceConfig promise route = " + JSON.stringify(data.route)); - console.log("getIfaceConfig promise gateway = " + JSON.stringify(data.gateway)); - console.log("getIfaceConfig promise netMask = " + JSON.stringify(data.netMask)); - console.log("getIfaceConfig promise dnsServers = " + JSON.stringify(data.dnsServers)); - console.log("getIfaceConfig promise domain = " + JSON.stringify(data.domain)); + console.log("getIfaceConfig promise mode = " + JSON.stringify(data.mode)); + console.log("getIfaceConfig promise ipAddr = " + JSON.stringify(data.ipAddr)); + console.log("getIfaceConfig promise route = " + JSON.stringify(data.route)); + console.log("getIfaceConfig promise gateway = " + JSON.stringify(data.gateway)); + console.log("getIfaceConfig promise netMask = " + JSON.stringify(data.netMask)); + console.log("getIfaceConfig promise dnsServers = " + JSON.stringify(data.dnsServers)); + console.log("getIfaceConfig promise domain = " + JSON.stringify(data.domain)); }).catch(error => { - console.log("getIfaceConfig promise error = " + JSON.stringify(error)); + console.log("getIfaceConfig promise error = " + JSON.stringify(error)); }); ``` @@ -253,11 +253,11 @@ isIfaceActive(iface: string, callback: AsyncCallback\): void ```js ethernet.isIfaceActive("eth0", (error, value) => { - if (error) { - console.log("whether2Activate callback error = " + JSON.stringify(error)); - } else { - console.log("whether2Activate callback = " + JSON.stringify(value)); - } + if (error) { + console.log("whether2Activate callback error = " + JSON.stringify(error)); + } else { + console.log("whether2Activate callback = " + JSON.stringify(value)); + } }); ``` @@ -300,9 +300,9 @@ isIfaceActive(iface: string): Promise\ ```js ethernet.isIfaceActive("eth0").then((data) => { - console.log("isIfaceActive promise = " + JSON.stringify(data)); + console.log("isIfaceActive promise = " + JSON.stringify(data)); }).catch(error => { - console.log("isIfaceActive promise error = " + JSON.stringify(error)); + console.log("isIfaceActive promise error = " + JSON.stringify(error)); }); ``` @@ -336,14 +336,14 @@ getAllActiveIfaces(callback: AsyncCallback\>): void ```js ethernet.getAllActiveIfaces((error, value) => { - if (error) { - console.log("getAllActiveIfaces callback error = " + JSON.stringify(error)); - } else { - console.log("getAllActiveIfaces callback value.length = " + JSON.stringify(value.length)); - for (let i = 0; i < value.length; i++) { - console.log("getAllActiveIfaces callback = " + JSON.stringify(value[i])); - } + if (error) { + console.log("getAllActiveIfaces callback error = " + JSON.stringify(error)); + } else { + console.log("getAllActiveIfaces callback value.length = " + JSON.stringify(value.length)); + for (let i = 0; i < value.length; i++) { + console.log("getAllActiveIfaces callback = " + JSON.stringify(value[i])); } + } }); ``` @@ -377,15 +377,83 @@ getAllActiveIfaces(): Promise\> ```js ethernet.getAllActiveIfaces().then((data) => { - console.log("getAllActiveIfaces promise data.length = " + JSON.stringify(data.length)); - for (let i = 0; i < data.length; i++) { - console.log("getAllActiveIfaces promise = " + JSON.stringify(data[i])); - } + console.log("getAllActiveIfaces promise data.length = " + JSON.stringify(data.length)); + for (let i = 0; i < data.length; i++) { + console.log("getAllActiveIfaces promise = " + JSON.stringify(data[i])); + } }).catch(error => { - console.log("getAllActiveIfaces promise error = " + JSON.stringify(error)); + console.log("getAllActiveIfaces promise error = " + JSON.stringify(error)); }); ``` +## ethernet.on('interfaceStateChange')10+ + +on(type: 'interfaceStateChange', callback: Callback\<{ iface: string, active: boolean }\>): void + +注册网卡热插拔事件,使用callback方式作为异步方法。 + +**系统接口**:此接口为系统接口。 + +**需要权限**:ohos.permission.GET_NETWORK_INFO + +**系统能力**:SystemCapability.Communication.NetManager.Ethernet + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| type | string | 是 | 订阅的事件类型,'interfaceStateChange'。 | +| callback | AsyncCallback\<{ iface: string, active: boolean }\> | 是 | 回调函数。
iface:网卡名称。
active:是否处于激活状态(true:激活;false:未激活) | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 202 | Applicable only to system applications. | +| 401 | Parameter error. | + +**示例:** + +```js + ethernet.on('interfaceStateChange', (data) => { + console.log('on interfaceSharingStateChange:' + JSON.stringify(data)); +}); +``` + +## ethernet.off('interfaceStateChange')10+ + +off(type: 'interfaceStateChange', callback?: Callback\<{ iface: string, active: boolean }\>): void + +注销网卡热插拔事件,使用callback方式作为异步方法。 + +**系统接口**:此接口为系统接口。 + +**需要权限**:ohos.permission.GET_NETWORK_INFO + +**系统能力**:SystemCapability.Communication.NetManager.Ethernet + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| type | string | 是 | 订阅的事件类型,'interfaceStateChange'。 | +| callback | AsyncCallback\<{ iface: string, active: boolean }> | 否 | 回调函数。
iface:网卡名称。
active:是否处于激活状态(true:激活;false:未激活) | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 202 | Applicable only to system applications. | +| 401 | Parameter error. | + +**示例:** + +```js +ethernet.off('interfaceStateChange'); +``` + ## InterfaceConfiguration 以太网连接配置网络信息。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-net-policy.md b/zh-cn/application-dev/reference/apis/js-apis-net-policy.md index b585364ba9fcbd70b639acc858858a704d0c7ce9..b62e5209b686975277c8d11ecfb6b55d23234961 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-net-policy.md +++ b/zh-cn/application-dev/reference/apis/js-apis-net-policy.md @@ -43,10 +43,12 @@ setBackgroundPolicy(isAllowed: boolean, callback: AsyncCallback\): void ```js policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))), (error, data) => { - this.callBack(error, data); - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) -}); + this.callBack(error, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +} +) +; ``` ## policy.setBackgroundPolicy @@ -84,9 +86,9 @@ setBackgroundPolicy(isAllowed: boolean): Promise\ **示例:** ```js -policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) +policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))).then(function (error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) }) ``` @@ -118,9 +120,9 @@ isBackgroundAllowed(callback: AsyncCallback\): void ```js policy.isBackgroundAllowed((error, data) => { - this.callBack(error, data); - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) + this.callBack(error, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) }); ``` @@ -151,9 +153,9 @@ isBackgroundAllowed(): Promise\; **示例:** ```js -policy.isBackgroundAllowed().then(function(error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) +policy.isBackgroundAllowed().then(function (error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) }) ``` @@ -190,10 +192,10 @@ setPolicyByUid(uid: number, policy: NetUidPolicy, callback: AsyncCallback\ ```js let param = { - uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy) + uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy) } policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy), (error, data) => { - this.callBack(error, data); + this.callBack(error, data); }); ``` @@ -234,11 +236,11 @@ setPolicyByUid(uid: number, policy: NetUidPolicy): Promise\; ```js let param = { - uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy) + uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy) } -policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy)).then(function(error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) +policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy)).then(function (error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) }) ``` @@ -274,7 +276,7 @@ getPolicyByUid(uid: number, callback: AsyncCallback\): void ```js policy.getPolicyByUid(Number.parseInt(this.firstParam), (error, data) => { - this.callBack(error, data); + this.callBack(error, data); }); ``` @@ -313,9 +315,9 @@ getPolicyByUid(uid: number): Promise\; **示例:** ```js -policy.getPolicyByUid(Number.parseInt(this.firstParam)).then(function(error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) +policy.getPolicyByUid(Number.parseInt(this.firstParam)).then(function (error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) }) ``` @@ -351,7 +353,7 @@ getUidsByPolicy(policy: NetUidPolicy, callback: AsyncCallback\>): ```js policy.getUidsByPolicy(Number.parseInt(this.currentNetUidPolicy), (error, data) => { - this.callBack(error, data); + this.callBack(error, data); }); ``` @@ -390,9 +392,9 @@ function getUidsByPolicy(policy: NetUidPolicy): Promise\>; **示例:** ```js -policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function(error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) +policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function (error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) }) ``` @@ -425,7 +427,7 @@ getNetQuotaPolicies(callback: AsyncCallback\>): void ```js policy.getNetQuotaPolicies((error, data) => { - this.callBack(error, data); + this.callBack(error, data); }); ``` @@ -456,9 +458,9 @@ getNetQuotaPolicies(): Promise\>; **示例:** ```js -policy.getNetQuotaPolicies().then(function(error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) +policy.getNetQuotaPolicies().then(function (error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) }) ``` @@ -493,12 +495,22 @@ setNetQuotaPolicies(quotaPolicies: Array\, callback: AsyncCallba **示例:** ```js -let param = {netType:Number.parseInt(this.netType), iccid:this.iccid, ident:this.ident, periodDuration:this.periodDuration, warningBytes:Number.parseInt(this.warningBytes), - limitBytes:Number.parseInt(this.limitBytes), lastWarningRemind:this.lastWarningRemind, lastLimitRemind:this.lastLimitRemind, metered:Boolean(Number.parseInt(this.metered)), limitAction:this.limitAction}; +let param = { + netType: Number.parseInt(this.netType), + iccid: this.iccid, + ident: this.ident, + periodDuration: this.periodDuration, + warningBytes: Number.parseInt(this.warningBytes), + limitBytes: Number.parseInt(this.limitBytes), + lastWarningRemind: this.lastWarningRemind, + lastLimitRemind: this.lastLimitRemind, + metered: Boolean(Number.parseInt(this.metered)), + limitAction: this.limitAction +}; this.netQuotaPolicyList.push(param); policy.setNetQuotaPolicies(this.netQuotaPolicyList, (error, data) => { - this.callBack(error, data); + this.callBack(error, data); }); ``` @@ -537,13 +549,23 @@ setNetQuotaPolicies(quotaPolicies: Array\): Promise\; **示例:** ```js -let param = {netType:Number.parseInt(this.netType), iccid:this.iccid, ident:this.ident, periodDuration:this.periodDuration, warningBytes:Number.parseInt(this.warningBytes), - limitBytes:Number.parseInt(this.limitBytes), lastWarningRemind:this.lastWarningRemind, lastLimitRemind:this.lastLimitRemind, metered:Boolean(Number.parseInt(this.metered)), limitAction:this.limitAction}; +let param = { + netType: Number.parseInt(this.netType), + iccid: this.iccid, + ident: this.ident, + periodDuration: this.periodDuration, + warningBytes: Number.parseInt(this.warningBytes), + limitBytes: Number.parseInt(this.limitBytes), + lastWarningRemind: this.lastWarningRemind, + lastLimitRemind: this.lastLimitRemind, + metered: Boolean(Number.parseInt(this.metered)), + limitAction: this.limitAction +}; this.netQuotaPolicyList.push(param); -policy.setNetQuotaPolicies(this.netQuotaPolicyList).then(function(error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) +policy.setNetQuotaPolicies(this.netQuotaPolicyList).then(function (error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) }) ``` @@ -579,7 +601,7 @@ restoreAllPolicies(iccid: string, callback: AsyncCallback\): void ```js this.firstParam = iccid; policy.restoreAllPolicies(this.firstParam, (error, data) => { - this.callBack(error, data); + this.callBack(error, data); }); ``` @@ -619,9 +641,9 @@ restoreAllPolicies(iccid: string): Promise\; ```js this.firstParam = iccid; -policy.restoreAllPolicies(this.firstParam).then(function(error, data){ - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) +policy.restoreAllPolicies(this.firstParam).then(function (error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) }) ``` @@ -659,10 +681,10 @@ isUidNetAllowed(uid: number, isMetered: boolean, callback: AsyncCallback\ { - this.callBack(error, data); + this.callBack(error, data); }); ``` @@ -704,11 +726,11 @@ isUidNetAllowed(uid: number, isMetered: boolean): Promise\; ```js let param = { - uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean)) + uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean)) } -policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) +policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function (error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) }) ``` @@ -746,10 +768,10 @@ isUidNetAllowed(uid: number, iface: string, callback: AsyncCallback\): ```js let param = { - uid: Number.parseInt(this.firstParam), iface: this.secondParam + uid: Number.parseInt(this.firstParam), iface: this.secondParam } policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam, (error, data) => { - this.callBack(error, data); + this.callBack(error, data); }); ``` @@ -790,11 +812,11 @@ isUidNetAllowed(uid: number, iface: string): Promise\; ```js let param = { - uid: Number.parseInt(this.firstParam), iface: this.secondParam + uid: Number.parseInt(this.firstParam), iface: this.secondParam } -policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam).then(function(error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) +policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam).then(function (error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) }) ``` @@ -831,10 +853,10 @@ setDeviceIdleAllowList(uid: number, isAllowed: boolean, callback: AsyncCallback\ ```js let param = { - uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) + uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) } policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (error, data) => { - this.callBack(error, data); + this.callBack(error, data); }); ``` @@ -875,11 +897,11 @@ setDeviceIdleAllowList(uid: number, isAllowed: boolean): Promise\; ```js let param = { - uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) + uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) } -policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) +policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function (error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) }) ``` @@ -912,7 +934,7 @@ getDeviceIdleAllowList(callback: AsyncCallback\>): void ```js policy.getDeviceIdleAllowList((error, data) => { - this.callBack(error, data); + this.callBack(error, data); }); ``` @@ -943,9 +965,9 @@ getDeviceIdleAllowList(): Promise\>; **示例:** ```js -policy.getDeviceIdleAllowList().then(function(error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) +policy.getDeviceIdleAllowList().then(function (error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) }) ``` @@ -981,7 +1003,7 @@ getBackgroundPolicyByUid(uid: number, callback: AsyncCallback\ { - this.callBack(error, data); + this.callBack(error, data); }); ``` @@ -1021,9 +1043,9 @@ getBackgroundPolicyByUid(uid: number): Promise\; ```js this.firstParam = uid -policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam)).then(function(error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) +policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam)).then(function (error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) }) ``` @@ -1059,7 +1081,7 @@ resetPolicies(iccid: string, callback: AsyncCallback\): void ```js this.firstParam = iccid policy.resetPolicies(this.firstParam, (error, data) => { - this.callBack(error, data); + this.callBack(error, data); }); ``` @@ -1098,13 +1120,13 @@ resetPolicies(iccid: string): Promise\; **示例:** ```js -policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function(error, data) { +policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function (error, data) { }) this.firstParam = iccid -policy.resetPolicies(this.firstParam).then(function(error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) +policy.resetPolicies(this.firstParam).then(function (error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) }) ``` @@ -1142,10 +1164,10 @@ updateRemindPolicy(netType: NetBearType, iccid: string, remindType: RemindType, ```js let param = { - netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType + netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType } policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType), (error, data) => { - this.callBack(error, data); + this.callBack(error, data); }); ``` @@ -1187,11 +1209,11 @@ updateRemindPolicy(netType: NetBearType, iccid: string, remindType: RemindType): ```js let param = { - netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType + netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType } -policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType)).then(function(error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) +policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType)).then(function (error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) }) ``` @@ -1228,10 +1250,10 @@ setPowerSaveAllowList(uid: number, isAllowed: boolean, callback: AsyncCallback\< ```js let param = { - uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) + uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) } policy.setPowerSaveAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (error, data) => { - this.callBack(error, data); + this.callBack(error, data); }); ``` @@ -1272,11 +1294,11 @@ setPowerSaveAllowList(uid: number, isAllowed: boolean): Promise\; ```js let param = { - uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) + uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) } -policy.setPowerSaveAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) +policy.setPowerSaveAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function (error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) }) ``` @@ -1309,7 +1331,7 @@ getPowerSaveAllowList(callback: AsyncCallback\>): void ```js policy.getPowerSaveAllowList((error, data) => { - this.callBack(error, data); + this.callBack(error, data); }); ``` @@ -1340,9 +1362,9 @@ getPowerSaveAllowList(): Promise\>; **示例:** ```js -policy.getPowerSaveAllowList().then(function(error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) +policy.getPowerSaveAllowList().then(function (error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) }) ``` @@ -1371,7 +1393,7 @@ on(type: "netUidPolicyChange", callback: Callback\<{ uid: number, policy: NetUid ```js policy.on('netUidPolicyChange', (data) => { - this.log('on netUidPolicyChange:' + JSON.stringify(data)); + this.log('on netUidPolicyChange:' + JSON.stringify(data)); }) ``` @@ -1396,7 +1418,7 @@ on(type: "netUidRuleChange", callback: Callback\<{ uid: number, rule: NetUidRule ```js policy.on('netUidRuleChange', (data) => { - this.log('on netUidRuleChange:' + JSON.stringify(data)); + this.log('on netUidRuleChange:' + JSON.stringify(data)); }) ``` @@ -1421,7 +1443,7 @@ on(type: "netMeteredIfacesChange", callback: Callback\>): void ```js policy.on('netMeteredIfacesChange', (data) => { - this.log('on netMeteredIfacesChange:' + JSON.stringify(data)); + this.log('on netMeteredIfacesChange:' + JSON.stringify(data)); }) ``` @@ -1446,7 +1468,7 @@ on(type: "netQuotaPolicyChange", callback: Callback\>): v ```js policy.on('netQuotaPolicyChange', (data) => { - this.log('on netQuotaPolicyChange:' + JSON.stringify(data)); + this.log('on netQuotaPolicyChange:' + JSON.stringify(data)); }) ``` @@ -1471,7 +1493,7 @@ on(type: "netBackgroundPolicyChange", callback: Callback\): void ```js policy.on('netBackgroundPolicyChange', (data) => { - this.log('on netBackgroundPolicyChange:' + JSON.stringify(data)); + this.log('on netBackgroundPolicyChange:' + JSON.stringify(data)); }) ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-net-sharing.md b/zh-cn/application-dev/reference/apis/js-apis-net-sharing.md index fd4ed040b47b0a7729efc4eb4b30f43c98e9a8e2..fec89275bb32c37fc1d6e050e44c6529dc644bc4 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-net-sharing.md +++ b/zh-cn/application-dev/reference/apis/js-apis-net-sharing.md @@ -43,8 +43,8 @@ isSharingSupported(callback: AsyncCallback\): void ```js sharing.isSharingSupported((error, data) => { - console.log(JSON.stringify(error)); - console.log(JSON.stringify(data)); + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); }); ``` @@ -79,9 +79,9 @@ isSharingSupported(): Promise\ ```js sharing.isSharingSupported().then(data => { - console.log(JSON.stringify(data)); + console.log(JSON.stringify(data)); }).catch(error => { - console.log(JSON.stringify(error)); + console.log(JSON.stringify(error)); }); ``` @@ -115,8 +115,8 @@ isSharing(callback: AsyncCallback\): void ```js sharing.isSharing((error, data) => { - console.log(JSON.stringify(error)); - console.log(JSON.stringify(data)); + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); }); ``` @@ -150,9 +150,9 @@ isSharing(): Promise\ ```js sharing.isSharing().then(data => { - console.log(JSON.stringify(data)); + console.log(JSON.stringify(data)); }).catch(error => { - console.log(JSON.stringify(error)); + console.log(JSON.stringify(error)); }); ``` @@ -194,9 +194,10 @@ startSharing(type: SharingIfaceType, callback: AsyncCallback\): void ```js import SharingIfaceType from '@ohos.net.sharing' -let SHARING_WIFI=0; + +let SHARING_WIFI = 0; sharing.startSharing(SHARING_WIFI, (error) => { - console.log(JSON.stringify(error)); + console.log(JSON.stringify(error)); }); ``` @@ -243,11 +244,12 @@ startSharing(type: SharingIfaceType): Promise\ ```js import SharingIfaceType from '@ohos.net.sharing' -let SHARING_WIFI=0; + +let SHARING_WIFI = 0; sharing.startSharing(SHARING_WIFI).then(() => { - console.log("start wifi sharing successful"); + console.log("start wifi sharing successful"); }).catch(error => { - console.log("start wifi sharing failed"); + console.log("start wifi sharing failed"); }); ``` @@ -287,9 +289,10 @@ stopSharing(type: SharingIfaceType, callback: AsyncCallback\): void ```js import SharingIfaceType from '@ohos.net.sharing' -let SHARING_WIFI=0; + +let SHARING_WIFI = 0; sharing.stopSharing(SHARING_WIFI, (error) => { - console.log(JSON.stringify(error)); + console.log(JSON.stringify(error)); }); ``` @@ -334,11 +337,12 @@ stopSharing(type: SharingIfaceType): Promise\ ```js import SharingIfaceType from '@ohos.net.sharing' -let SHARING_WIFI=0; + +let SHARING_WIFI = 0; sharing.stopSharing(SHARING_WIFI).then(() => { - console.log("stop wifi sharing successful"); + console.log("stop wifi sharing successful"); }).catch(error => { - console.log("stop wifi sharing failed"); + console.log("stop wifi sharing failed"); }); ``` @@ -372,8 +376,8 @@ getStatsRxBytes(callback: AsyncCallback\): void ```js sharing.getStatsRxBytes((error, data) => { - console.log(JSON.stringify(error)); - console.log(JSON.stringify(data)); + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); }); ``` @@ -407,9 +411,9 @@ getStatsRxBytes(): Promise\ ```js sharing.getStatsRxBytes().then(data => { - console.log(JSON.stringify(data)); + console.log(JSON.stringify(data)); }).catch(error => { - console.log(JSON.stringify(error)); + console.log(JSON.stringify(error)); }); ``` @@ -443,8 +447,8 @@ getStatsTxBytes(callback: AsyncCallback\): void ```js sharing.getStatsTxBytes((error, data) => { - console.log(JSON.stringify(error)); - console.log(JSON.stringify(data)); + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); }); ``` @@ -478,9 +482,9 @@ getStatsTxBytes(): Promise\ ```js sharing.getStatsTxBytes().then(data => { - console.log(JSON.stringify(data)); + console.log(JSON.stringify(data)); }).catch(error => { - console.log(JSON.stringify(error)); + console.log(JSON.stringify(error)); }); ``` @@ -514,8 +518,8 @@ getStatsTotalBytes(callback: AsyncCallback\): void ```js sharing.getStatsTotalBytes((error, data) => { - console.log(JSON.stringify(error)); - console.log(JSON.stringify(data)); + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); }); ``` @@ -549,9 +553,9 @@ getStatsTotalBytes(): Promise\ ```js sharing.getStatsTotalBytes().then(data => { - console.log(JSON.stringify(data)); + console.log(JSON.stringify(data)); }).catch(error => { - console.log(JSON.stringify(error)); + console.log(JSON.stringify(error)); }); ``` @@ -588,10 +592,11 @@ getSharingIfaces(state: SharingIfaceState, callback: AsyncCallback\ { - console.log(JSON.stringify(error)); - console.log(JSON.stringify(data)); + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); }); ``` @@ -633,11 +638,12 @@ getSharingIfaces(state: SharingIfaceState): Promise\> ```js import SharingIfaceState from '@ohos.net.sharing' -let SHARING_BLUETOOTH=2; + +let SHARING_BLUETOOTH = 2; sharing.getSharingIfaces(SHARING_BLUETOOTH).then(data => { - console.log(JSON.stringify(data)); + console.log(JSON.stringify(data)); }).catch(error => { - console.log(JSON.stringify(error)); + console.log(JSON.stringify(error)); }); ``` @@ -674,10 +680,11 @@ getSharingState(type: SharingIfaceType, callback: AsyncCallback\ { - console.log(JSON.stringify(error)); - console.log(JSON.stringify(data)); + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); }); ``` @@ -719,11 +726,12 @@ getSharingState(type: SharingIfaceType): Promise\ ```js import SharingIfaceType from '@ohos.net.sharing' -let SHARING_WIFI=0; + +let SHARING_WIFI = 0; sharing.getSharingState(SHARING_WIFI).then(data => { - console.log(JSON.stringify(data)); + console.log(JSON.stringify(data)); }).catch(error => { - console.log(JSON.stringify(error)); + console.log(JSON.stringify(error)); }); ``` @@ -760,10 +768,11 @@ getSharableRegexes(type: SharingIfaceType, callback: AsyncCallback\ { - console.log(JSON.stringify(error)); - console.log(JSON.stringify(data)); + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); }); ``` @@ -805,11 +814,12 @@ getSharableRegexes(type: SharingIfaceType): Promise\> ```js import SharingIfaceType from '@ohos.net.sharing' -let SHARING_WIFI=0; + +let SHARING_WIFI = 0; sharing.getSharableRegexes(SHARING_WIFI).then(data => { - console.log(JSON.stringify(data)); + console.log(JSON.stringify(data)); }).catch(error => { - console.log(JSON.stringify(error)); + console.log(JSON.stringify(error)); }); ``` @@ -842,8 +852,8 @@ on(type: 'sharingStateChange', callback: Callback\): void **示例:** ```js - sharing.on('sharingStateChange', (data) => { - console.log('on sharingStateChange:' + JSON.stringify(data)); +sharing.on('sharingStateChange', (data) => { + console.log('on sharingStateChange: ' + JSON.stringify(data)); }); ``` @@ -877,7 +887,7 @@ off(type: 'sharingStateChange', callback?: Callback\): void ```js sharing.off('sharingStateChange', (data) => { - console.log(JSON.stringify(data)); + console.log(JSON.stringify(data)); }); ``` @@ -910,8 +920,8 @@ on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIface **示例:** ```js - sharing.on('interfaceSharingStateChange', (data) => { - console.log('on interfaceSharingStateChange:' + JSON.stringify(data)); +sharing.on('interfaceSharingStateChange', (data) => { + console.log('on interfaceSharingStateChange:' + JSON.stringify(data)); }); ``` @@ -945,7 +955,7 @@ off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfa ```js sharing.off('interfaceSharingStateChange', (data) => { - console.log(JSON.stringify(data)); + console.log(JSON.stringify(data)); }); ``` @@ -978,8 +988,8 @@ on(type: 'sharingUpstreamChange', callback: Callback\): void **示例:** ```js - sharing.on('sharingUpstreamChange', (data) => { - console.log('on sharingUpstreamChange:' + JSON.stringify(data)); +sharing.on('sharingUpstreamChange', (data) => { + console.log('on sharingUpstreamChange:' + JSON.stringify(data)); }); ``` @@ -1013,7 +1023,7 @@ off(type: 'sharingUpstreamChange', callback?: Callback\): void ```js sharing.off('sharingUpstreamChange', (data) => { - console.log(JSON.stringify(data)); + console.log(JSON.stringify(data)); }); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-socket.md b/zh-cn/application-dev/reference/apis/js-apis-socket.md index f3d2dff5695686b48f76a97aab7fb3706d63165d..15da749a5bda97786e7a63f6fad4f7e127d90619 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-socket.md +++ b/zh-cn/application-dev/reference/apis/js-apis-socket.md @@ -2,7 +2,7 @@ 本模块提供利用Socket进行数据传输的能力,支持TCPSocket、UDPSocket、WebSocket和TLSSocket。 -> **说明:** +> **说明:** > > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 @@ -26,14 +26,12 @@ constructUDPSocketInstance(): UDPSocket | :--------------------------------- | :---------------------- | | [UDPSocket](#udpsocket) | 返回一个UDPSocket对象。 | - **示例:** ```js let udp = socket.constructUDPSocketInstance(); ``` - ## UDPSocket UDPSocket连接。在调用UDPSocket的方法前,需要先通过[socket.constructUDPSocketInstance](#socketconstructudpsocketinstance)创建UDPSocket对象。 @@ -68,14 +66,13 @@ bind(address: NetAddress, callback: AsyncCallback\): void let udp = socket.constructUDPSocketInstance(); udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { if (err) { - console.log('bind fail'); - return; + console.log('bind fail'); + return; } console.log('bind success'); }) ``` - ### bind bind(address: NetAddress): Promise\ @@ -110,14 +107,13 @@ bind(address: NetAddress): Promise\ ```js let udp = socket.constructUDPSocketInstance(); let promise = udp.bind({address: '192.168.xx.xxx', port: 8080, family: 1}); -promise .then(() => { +promise.then(() => { console.log('bind success'); }).catch(err => { console.log('bind fail'); }); ``` - ### send send(options: UDPSendOptions, callback: AsyncCallback\): void @@ -149,22 +145,21 @@ send(options: UDPSendOptions, callback: AsyncCallback\): void ```js let udp = socket.constructUDPSocketInstance(); udp.send({ - data:'Hello, server!', + data: 'Hello, server!', address: { - address:'192.168.xx.xxx', - port:xxxx, - family:1 + address: '192.168.xx.xxx', + port: xxxx, + family: 1 } -}, err=> { - if (err) { - console.log('send fail'); - return; - } - console.log('send success'); +}, err => { + if (err) { + console.log('send fail'); + return; + } + console.log('send success'); }) ``` - ### send send(options: UDPSendOptions): Promise\ @@ -201,11 +196,11 @@ send(options: UDPSendOptions): Promise\ ```js let udp = socket.constructUDPSocketInstance(); let promise = udp.send({ - data:'Hello, server!', + data: 'Hello, server!', address: { - address:'192.168.xx.xxx', - port:xxxx, - family:1 + address: '192.168.xx.xxx', + port: xxxx, + family: 1 } }); promise.then(() => { @@ -215,7 +210,6 @@ promise.then(() => { }); ``` - ### close close(callback: AsyncCallback\): void @@ -238,14 +232,13 @@ close(callback: AsyncCallback\): void let udp = socket.constructUDPSocketInstance(); udp.close(err => { if (err) { - console.log('close fail'); - return; + console.log('close fail'); + return; } console.log('close success'); }) ``` - ### close close(): Promise\ @@ -274,15 +267,14 @@ promise.then(() => { }); ``` - ### getState getState(callback: AsyncCallback\): void 获取UDPSocket状态。使用callback方式作为异步方法。 ->**说明:** ->bind方法调用成功后,才可调用此方法。 +> **说明:** +> bind方法调用成功后,才可调用此方法。 **需要权限**:ohos.permission.INTERNET @@ -306,29 +298,28 @@ getState(callback: AsyncCallback\): void let udp = socket.constructUDPSocketInstance(); udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { if (err) { - console.log('bind fail'); - return; + console.log('bind fail'); + return; } console.log('bind success'); udp.getState((err, data) => { - if (err) { - console.log('getState fail'); - return; - } - console.log('getState success:' + JSON.stringify(data)); + if (err) { + console.log('getState fail'); + return; + } + console.log('getState success:' + JSON.stringify(data)); }) }) ``` - ### getState getState(): Promise\ 获取UDPSocket状态。使用Promise方式作为异步方法。 ->**说明:** ->bind方法调用成功后,才可调用此方法。 +> **说明:** +> bind方法调用成功后,才可调用此方法。 **需要权限**:ohos.permission.INTERNET @@ -344,30 +335,30 @@ getState(): Promise\ ```js let udp = socket.constructUDPSocketInstance(); -udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { +let promise = udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}); +promise.then(err => { if (err) { - console.log('bind fail'); - return; + console.log('bind fail'); + return; } console.log('bind success'); let promise = udp.getState(); promise.then(data => { - console.log('getState success:' + JSON.stringify(data)); + console.log('getState success:' + JSON.stringify(data)); }).catch(err => { - console.log('getState fail'); + console.log('getState fail'); }); -}) +}); ``` - ### setExtraOptions setExtraOptions(options: UDPExtraOptions, callback: AsyncCallback\): void 设置UDPSocket连接的其他属性。使用callback方式作为异步方法。 ->**说明:** ->bind方法调用成功后,才可调用此方法。 +> **说明:** +> bind方法调用成功后,才可调用此方法。 **需要权限**:ohos.permission.INTERNET @@ -391,37 +382,36 @@ setExtraOptions(options: UDPExtraOptions, callback: AsyncCallback\): void ```js let udp = socket.constructUDPSocketInstance(); -udp.bind({address:'192.168.xx.xxx', port:xxxx, family:1}, err=> { +udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { if (err) { - console.log('bind fail'); - return; + console.log('bind fail'); + return; } console.log('bind success'); udp.setExtraOptions({ - receiveBufferSize:1000, - sendBufferSize:1000, - reuseAddress:false, - socketTimeout:6000, - broadcast:true - }, err=> { - if (err) { - console.log('setExtraOptions fail'); - return; - } - console.log('setExtraOptions success'); + receiveBufferSize: 1000, + sendBufferSize: 1000, + reuseAddress: false, + socketTimeout: 6000, + broadcast: true + }, err => { + if (err) { + console.log('setExtraOptions fail'); + return; + } + console.log('setExtraOptions success'); }) }) ``` - ### setExtraOptions setExtraOptions(options: UDPExtraOptions): Promise\ 设置UDPSocket连接的其他属性。使用Promise方式作为异步方法。 ->**说明:** ->bind方法调用成功后,才可调用此方法。 +> **说明:** +> bind方法调用成功后,才可调用此方法。 **需要权限**:ohos.permission.INTERNET @@ -450,27 +440,26 @@ setExtraOptions(options: UDPExtraOptions): Promise\ ```js let udp = socket.constructUDPSocketInstance(); -let promise = udp.bind({address:'192.168.xx.xxx', port:xxxx, family:1}); +let promise = udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}); promise.then(() => { console.log('bind success'); let promise1 = udp.setExtraOptions({ - receiveBufferSize:1000, - sendBufferSize:1000, - reuseAddress:false, - socketTimeout:6000, - broadcast:true + receiveBufferSize: 1000, + sendBufferSize: 1000, + reuseAddress: false, + socketTimeout: 6000, + broadcast: true }); promise1.then(() => { - console.log('setExtraOptions success'); + console.log('setExtraOptions success'); }).catch(err => { - console.log('setExtraOptions fail'); + console.log('setExtraOptions fail'); }); }).catch(err => { console.log('bind fail'); }); ``` - ### on('message') on(type: 'message', callback: Callback\<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void @@ -491,19 +480,18 @@ on(type: 'message', callback: Callback\<{message: ArrayBuffer, remoteInfo: Socke ```js let udp = socket.constructUDPSocketInstance(); udp.on('message', value => { - console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); + console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); }); ``` - ### off('message') off(type: 'message', callback?: Callback\<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void 取消订阅UDPSocket连接的接收消息事件。使用callback方式作为异步方法。 ->**说明:** ->可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 +> **说明:** +> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 **系统能力**:SystemCapability.Communication.NetStack @@ -518,8 +506,8 @@ off(type: 'message', callback?: Callback\<{message: ArrayBuffer, remoteInfo: Soc ```js let udp = socket.constructUDPSocketInstance(); -let callback = value =>{ - console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); +let callback = value => { + console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); } udp.on('message', callback); // 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 @@ -527,7 +515,6 @@ udp.off('message', callback); udp.off('message'); ``` - ### on('listening' | 'close') on(type: 'listening' | 'close', callback: Callback\): void @@ -548,22 +535,21 @@ on(type: 'listening' | 'close', callback: Callback\): void ```js let udp = socket.constructUDPSocketInstance(); udp.on('listening', () => { - console.log("on listening success"); + console.log("on listening success"); }); udp.on('close', () => { - console.log("on close success" ); + console.log("on close success"); }); ``` - ### off('listening' | 'close') off(type: 'listening' | 'close', callback?: Callback\): void 取消订阅UDPSocket连接的数据包消息事件或关闭事件。使用callback方式作为异步方法。 ->**说明:** ->可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 +> **说明:** +> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 **系统能力**:SystemCapability.Communication.NetStack @@ -578,15 +564,15 @@ off(type: 'listening' | 'close', callback?: Callback\): void ```js let udp = socket.constructUDPSocketInstance(); -let callback1 = () =>{ - console.log("on listening, success"); +let callback1 = () => { + console.log("on listening, success"); } udp.on('listening', callback1); // 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 udp.off('listening', callback1); udp.off('listening'); -let callback2 = () =>{ - console.log("on close, success"); +let callback2 = () => { + console.log("on close, success"); } udp.on('close', callback2); // 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 @@ -594,7 +580,6 @@ udp.off('close', callback2); udp.off('close'); ``` - ### on('error') on(type: 'error', callback: ErrorCallback): void @@ -615,19 +600,18 @@ on(type: 'error', callback: ErrorCallback): void ```js let udp = socket.constructUDPSocketInstance(); udp.on('error', err => { - console.log("on error, err:" + JSON.stringify(err)) + console.log("on error, err:" + JSON.stringify(err)) }); ``` - ### off('error') off(type: 'error', callback?: ErrorCallback): void 取消订阅UDPSocket连接的error事件。使用callback方式作为异步方法。 ->**说明:** ->可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 +> **说明:** +> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 **系统能力**:SystemCapability.Communication.NetStack @@ -642,8 +626,8 @@ off(type: 'error', callback?: ErrorCallback): void ```js let udp = socket.constructUDPSocketInstance(); -let callback = err =>{ - console.log("on error, err:" + JSON.stringify(err)); +let callback = err => { + console.log("on error, err:" + JSON.stringify(err)); } udp.on('error', callback); // 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 @@ -651,7 +635,6 @@ udp.off('error', callback); udp.off('error'); ``` - ## NetAddress 目标地址信息。 @@ -730,9 +713,9 @@ constructTCPSocketInstance(): TCPSocket **返回值:** - | 类型 | 说明 | +| 类型 | 说明 | | :--------------------------------- | :---------------------- | - | [TCPSocket](#tcpsocket) | 返回一个TCPSocket对象。 | +| [TCPSocket](#tcpsocket) | 返回一个TCPSocket对象。 | **示例:** @@ -740,7 +723,6 @@ constructTCPSocketInstance(): TCPSocket let tcp = socket.constructTCPSocketInstance(); ``` - ## TCPSocket TCPSocket连接。在调用TCPSocket的方法前,需要先通过[socket.constructTCPSocketInstance](#socketconstructtcpsocketinstance)创建TCPSocket对象。 @@ -775,14 +757,13 @@ bind(address: NetAddress, callback: AsyncCallback\): void let tcp = socket.constructTCPSocketInstance(); tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { if (err) { - console.log('bind fail'); - return; + console.log('bind fail'); + return; } console.log('bind success'); }) ``` - ### bind bind(address: NetAddress): Promise\ @@ -824,15 +805,14 @@ promise.then(() => { }); ``` - ### connect connect(options: TCPConnectOptions, callback: AsyncCallback\): void 连接到指定的IP地址和端口。使用callback方法作为异步方法。 ->**说明:** ->bind方法调用成功后,才可调用此方法。 +> **说明:** +> bind方法调用成功后,才可调用此方法。 **需要权限**:ohos.permission.INTERNET @@ -856,16 +836,15 @@ connect(options: TCPConnectOptions, callback: AsyncCallback\): void ```js let tcp = socket.constructTCPSocketInstance(); -tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}, err => { +tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}, err => { if (err) { - console.log('connect fail'); - return; + console.log('connect fail'); + return; } console.log('connect success'); }) ``` - ### connect connect(options: TCPConnectOptions): Promise\ @@ -899,7 +878,7 @@ connect(options: TCPConnectOptions): Promise\ ```js let tcp = socket.constructTCPSocketInstance(); -let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); +let promise = tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}); promise.then(() => { console.log('connect success') }).catch(err => { @@ -907,15 +886,14 @@ promise.then(() => { }); ``` - ### send send(options: TCPSendOptions, callback: AsyncCallback\): void 通过TCPSocket连接发送数据。使用callback方式作为异步方法。 ->**说明:** ->connect方法调用成功后,才可调用此方法。 +> **说明:** +> connect方法调用成功后,才可调用此方法。 **需要权限**:ohos.permission.INTERNET @@ -939,32 +917,29 @@ send(options: TCPSendOptions, callback: AsyncCallback\): void ```js let tcp = socket.constructTCPSocketInstance(); -let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); -promise.then(() => { +tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}, () => { console.log('connect success'); tcp.send({ - data:'Hello, server!' - },err => { - if (err) { - console.log('send fail'); - return; - } - console.log('send success'); + data: 'Hello, server!' + //此处省略encoding, 默认为utf-8编码格式 + }, err => { + if (err) { + console.log('send fail'); + return; + } + console.log('send success'); }) -}).catch(err => { - console.log('connect fail'); -}); +}) ``` - ### send send(options: TCPSendOptions): Promise\ 通过TCPSocket连接发送数据。使用Promise方式作为异步方法。 ->**说明:** ->connect方法调用成功后,才可调用此方法。 +> **说明:** +> connect方法调用成功后,才可调用此方法。 **需要权限**:ohos.permission.INTERNET @@ -993,23 +968,22 @@ send(options: TCPSendOptions): Promise\ ```js let tcp = socket.constructTCPSocketInstance(); -let promise1 = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); +let promise1 = tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}); promise1.then(() => { console.log('connect success'); let promise2 = tcp.send({ - data:'Hello, server!' + data: 'Hello, server!' }); promise2.then(() => { - console.log('send success'); + console.log('send success'); }).catch(err => { - console.log('send fail'); + console.log('send fail'); }); }).catch(err => { console.log('connect fail'); }); ``` - ### close close(callback: AsyncCallback\): void @@ -1038,14 +1012,13 @@ close(callback: AsyncCallback\): void let tcp = socket.constructTCPSocketInstance(); tcp.close(err => { if (err) { - console.log('close fail'); - return; + console.log('close fail'); + return; } console.log('close success'); }) ``` - ### close close(): Promise\ @@ -1080,15 +1053,14 @@ promise.then(() => { }); ``` - ### getRemoteAddress getRemoteAddress(callback: AsyncCallback\): void 获取对端Socket地址。使用callback方式作为异步方法。 ->**说明:** ->connect方法调用成功后,才可调用此方法。 +> **说明:** +> connect方法调用成功后,才可调用此方法。 **需要权限**:ohos.permission.INTERNET @@ -1110,30 +1082,26 @@ getRemoteAddress(callback: AsyncCallback\): void ```js let tcp = socket.constructTCPSocketInstance(); -let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); -promise.then(() => { +tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}, () => { console.log('connect success'); tcp.getRemoteAddress((err, data) => { - if (err) { - console.log('getRemoteAddressfail'); - return; - } - console.log('getRemoteAddresssuccess:' + JSON.stringify(data)); + if (err) { + console.log('getRemoteAddressfail'); + return; + } + console.log('getRemoteAddresssuccess:' + JSON.stringify(data)); }) -}).catch(err => { - console.log('connect fail'); }); ``` - ### getRemoteAddress getRemoteAddress(): Promise\ 获取对端Socket地址。使用Promise方式作为异步方法。 ->**说明:** ->connect方法调用成功后,才可调用此方法。 +> **说明:** +> connect方法调用成功后,才可调用此方法。 **需要权限**:ohos.permission.INTERNET @@ -1155,29 +1123,28 @@ getRemoteAddress(): Promise\ ```js let tcp = socket.constructTCPSocketInstance(); -let promise1 = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); +let promise1 = tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}); promise1.then(() => { console.log('connect success'); let promise2 = tcp.getRemoteAddress(); promise2.then(() => { - console.log('getRemoteAddress success'); + console.log('getRemoteAddress success'); }).catch(err => { - console.log('getRemoteAddressfail'); + console.log('getRemoteAddressfail'); }); }).catch(err => { console.log('connect fail'); }); ``` - ### getState getState(callback: AsyncCallback\): void 获取TCPSocket状态。使用callback方式作为异步方法。 ->**说明:** ->bind或connect方法调用成功后,才可调用此方法。 +> **说明:** +> bind或connect方法调用成功后,才可调用此方法。 **需要权限**:ohos.permission.INTERNET @@ -1199,30 +1166,26 @@ getState(callback: AsyncCallback\): void ```js let tcp = socket.constructTCPSocketInstance(); -let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); -promise.then(() => { +let promise = tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}, () => { console.log('connect success'); tcp.getState((err, data) => { - if (err) { - console.log('getState fail'); - return; - } - console.log('getState success:' + JSON.stringify(data)); + if (err) { + console.log('getState fail'); + return; + } + console.log('getState success:' + JSON.stringify(data)); }); -}).catch(err => { - console.log('connect fail'); }); ``` - ### getState getState(): Promise\ 获取TCPSocket状态。使用Promise方式作为异步方法。 ->**说明:** ->bind或connect方法调用成功后,才可调用此方法。 +> **说明:** +> bind或connect方法调用成功后,才可调用此方法。 **需要权限**:ohos.permission.INTERNET @@ -1244,29 +1207,28 @@ getState(): Promise\ ```js let tcp = socket.constructTCPSocketInstance(); -let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); +let promise = tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}); promise.then(() => { console.log('connect success'); let promise1 = tcp.getState(); promise1.then(() => { - console.log('getState success'); + console.log('getState success'); }).catch(err => { - console.log('getState fail'); + console.log('getState fail'); }); }).catch(err => { console.log('connect fail'); }); ``` - ### setExtraOptions setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\): void 设置TCPSocket连接的其他属性。使用callback方式作为异步方法。 ->**说明:** ->bind或connect方法调用成功后,才可调用此方法。 +> **说明:** +> bind或connect方法调用成功后,才可调用此方法。 **需要权限**:ohos.permission.INTERNET @@ -1290,39 +1252,35 @@ setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\): void ```js let tcp = socket.constructTCPSocketInstance(); -let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); -promise.then(() => { +let promise = tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}, () => { console.log('connect success'); tcp.setExtraOptions({ - keepAlive: true, - OOBInline: true, - TCPNoDelay: true, - socketLinger: { on:true, linger:10 }, - receiveBufferSize: 1000, - sendBufferSize: 1000, - reuseAddress: true, - socketTimeout: 3000, - },err => { - if (err) { - console.log('setExtraOptions fail'); - return; - } - console.log('setExtraOptions success'); + keepAlive: true, + OOBInline: true, + TCPNoDelay: true, + socketLinger: {on: true, linger: 10}, + receiveBufferSize: 1000, + sendBufferSize: 1000, + reuseAddress: true, + socketTimeout: 3000, + }, err => { + if (err) { + console.log('setExtraOptions fail'); + return; + } + console.log('setExtraOptions success'); }); -}).catch(err => { - console.log('connect fail'); }); ``` - ### setExtraOptions setExtraOptions(options: TCPExtraOptions): Promise\ 设置TCPSocket连接的其他属性,使用Promise方式作为异步方法。 ->**说明:** ->bind或connect方法调用成功后,才可调用此方法。 +> **说明:** +> bind或connect方法调用成功后,才可调用此方法。 **需要权限**:ohos.permission.INTERNET @@ -1351,30 +1309,29 @@ setExtraOptions(options: TCPExtraOptions): Promise\ ```js let tcp = socket.constructTCPSocketInstance(); -let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); +let promise = tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}); promise.then(() => { console.log('connect success'); let promise1 = tcp.setExtraOptions({ - keepAlive: true, - OOBInline: true, - TCPNoDelay: true, - socketLinger: { on:true, linger:10 }, - receiveBufferSize: 1000, - sendBufferSize: 1000, - reuseAddress: true, - socketTimeout: 3000, + keepAlive: true, + OOBInline: true, + TCPNoDelay: true, + socketLinger: {on: true, linger: 10}, + receiveBufferSize: 1000, + sendBufferSize: 1000, + reuseAddress: true, + socketTimeout: 3000, }); promise1.then(() => { - console.log('setExtraOptions success'); + console.log('setExtraOptions success'); }).catch(err => { - console.log('setExtraOptions fail'); + console.log('setExtraOptions fail'); }); }).catch(err => { console.log('connect fail'); }); ``` - ### on('message') on(type: 'message', callback: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void @@ -1395,19 +1352,18 @@ on(type: 'message', callback: Callback<{message: ArrayBuffer, remoteInfo: Socket ```js let tcp = socket.constructTCPSocketInstance(); tcp.on('message', value => { - console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo) + console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo) }); ``` - ### off('message') off(type: 'message', callback?: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void 取消订阅TCPSocket连接的接收消息事件。使用callback方式作为异步方法。 ->**说明:** ->可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 +> **说明:** +> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 **系统能力**:SystemCapability.Communication.NetStack @@ -1422,8 +1378,8 @@ off(type: 'message', callback?: Callback<{message: ArrayBuffer, remoteInfo: Sock ```js let tcp = socket.constructTCPSocketInstance(); -let callback = value =>{ - console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); +let callback = value => { + console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); } tcp.on('message', callback); // 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 @@ -1431,7 +1387,6 @@ tcp.off('message', callback); tcp.off('message'); ``` - ### on('connect' | 'close') on(type: 'connect' | 'close', callback: Callback\): void @@ -1452,22 +1407,21 @@ on(type: 'connect' | 'close', callback: Callback\): void ```js let tcp = socket.constructTCPSocketInstance(); tcp.on('connect', () => { - console.log("on connect success") + console.log("on connect success") }); tcp.on('close', data => { - console.log("on close success") + console.log("on close success") }); ``` - ### off('connect' | 'close') off(type: 'connect' | 'close', callback?: Callback\): void 取消订阅TCPSocket的连接事件或关闭事件。使用callback方式作为异步方法。 ->**说明:** ->可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 +> **说明:** +> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 **系统能力**:SystemCapability.Communication.NetStack @@ -1482,15 +1436,15 @@ off(type: 'connect' | 'close', callback?: Callback\): void ```js let tcp = socket.constructTCPSocketInstance(); -let callback1 = () =>{ - console.log("on connect success"); +let callback1 = () => { + console.log("on connect success"); } tcp.on('connect', callback1); // 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 tcp.off('connect', callback1); tcp.off('connect'); -let callback2 = () =>{ - console.log("on close success"); +let callback2 = () => { + console.log("on close success"); } tcp.on('close', callback2); // 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 @@ -1498,7 +1452,6 @@ tcp.off('close', callback2); tcp.off('close'); ``` - ### on('error') on(type: 'error', callback: ErrorCallback): void @@ -1519,19 +1472,18 @@ on(type: 'error', callback: ErrorCallback): void ```js let tcp = socket.constructTCPSocketInstance(); tcp.on('error', err => { - console.log("on error, err:" + JSON.stringify(err)) + console.log("on error, err:" + JSON.stringify(err)) }); ``` - ### off('error') off(type: 'error', callback?: ErrorCallback): void 取消订阅TCPSocket连接的error事件。使用callback方式作为异步方法。 ->**说明:** ->可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 +> **说明:** +> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 **系统能力**:SystemCapability.Communication.NetStack @@ -1546,8 +1498,8 @@ off(type: 'error', callback?: ErrorCallback): void ```js let tcp = socket.constructTCPSocketInstance(); -let callback = err =>{ - console.log("on error, err:" + JSON.stringify(err)); +let callback = err => { + console.log("on error, err:" + JSON.stringify(err)); } tcp.on('error', callback); // 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 @@ -1555,7 +1507,6 @@ tcp.off('error', callback); tcp.off('error'); ``` - ## TCPConnectOptions TCPSocket连接的参数。 @@ -1769,12 +1720,11 @@ getState(): Promise\ **示例:** ```js -tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { - if (err) { - console.log('bind fail'); - return; - } +let promiseBind = tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}); +promiseBind.then(() => { console.log('bind success'); +}).catch((err) => { + console.log('bind fail'); }); let promise = tls.getState(); promise.then(() => { @@ -1822,18 +1772,19 @@ tls.setExtraOptions({ keepAlive: true, OOBInline: true, TCPNoDelay: true, - socketLinger: { on:true, linger:10 }, + socketLinger: {on: true, linger: 10}, receiveBufferSize: 1000, sendBufferSize: 1000, reuseAddress: true, socketTimeout: 3000, -},err => { +}, err => { if (err) { console.log('setExtraOptions fail'); return; } console.log('setExtraOptions success'); }); + ``` ### setExtraOptions9+ @@ -1878,7 +1829,7 @@ let promise = tls.setExtraOptions({ keepAlive: true, OOBInline: true, TCPNoDelay: true, - socketLinger: { on:true, linger:10 }, + socketLinger: {on: true, linger: 10}, receiveBufferSize: 1000, sendBufferSize: 1000, reuseAddress: true, @@ -1956,12 +1907,12 @@ let options = { }, }; tlsTwoWay.connect(options, (err, data) => { - console.error("connect callback error"+err); + console.error("connect callback error" + err); console.log(JSON.stringify(data)); }); let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication - tlsOneWay.bind({address: '192.168.xxx.xxx', port: 8080, family: 1}, err => { +tlsOneWay.bind({address: '192.168.xxx.xxx', port: 8080, family: 1}, err => { if (err) { console.log('bind fail'); return; @@ -1975,12 +1926,12 @@ let oneWayOptions = { family: 1, }, secureOptions: { - ca: ["xxxx","xxxx"], + ca: ["xxxx", "xxxx"], cipherSuite: "AES256-SHA256", }, }; tlsOneWay.connect(oneWayOptions, (err, data) => { - console.error("connect callback error"+err); + console.error("connect callback error" + err); console.log(JSON.stringify(data)); }); ``` @@ -2075,7 +2026,7 @@ let oneWayOptions = { family: 1, }, secureOptions: { - ca: ["xxxx","xxxx"], + ca: ["xxxx", "xxxx"], cipherSuite: "AES256-SHA256", }, }; @@ -2551,7 +2502,7 @@ send(data: string): Promise\ **示例:** ```js -tls.send("xxxx").then(() =>{ +tls.send("xxxx").then(() => { console.log("send success"); }).catch(err => { console.error(err); @@ -2619,7 +2570,7 @@ close(): Promise\ **示例:** ```js -tls.close().then(() =>{ +tls.close().then(() => { console.log("close success"); }).catch(err => { console.error(err); diff --git a/zh-cn/application-dev/reference/apis/js-apis-webSocket.md b/zh-cn/application-dev/reference/apis/js-apis-webSocket.md index 9853827f5e3a37af24b76d19c8c0e982dfcc5b93..a6474bf69108d1bb6e627fd086dabd26dec5ae04 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-webSocket.md +++ b/zh-cn/application-dev/reference/apis/js-apis-webSocket.md @@ -1,15 +1,16 @@ # @ohos.net.webSocket (WebSocket连接) -> **说明:** +> **说明:** > > 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 -使用WebSocket建立服务器与客户端的双向连接,需要先通过[createWebSocket](#websocketcreatewebsocket)方法创建[WebSocket](#websocket)对象,然后通过[connect](#connect)方法连接到服务器。当连接成功后,客户端会收到[open](#onopen)事件的回调,之后客户端就可以通过[send](#send)方法与服务器进行通信。当服务器发信息给客户端时,客户端会收到[message](#onmessage)事件的回调。当客户端不要此连接时,可以通过调用[close](#close)方法主动断开连接,之后客户端会收到[close](#onclose)事件的回调。 +使用WebSocket建立服务器与客户端的双向连接,需要先通过[createWebSocket](#websocketcreatewebsocket)方法创建[WebSocket](#websocket)对象,然后通过[connect](#connect)方法连接到服务器。 +当连接成功后,客户端会收到[open](#onopen)事件的回调,之后客户端就可以通过[send](#send)方法与服务器进行通信。 +当服务器发信息给客户端时,客户端会收到[message](#onmessage)事件的回调。当客户端不要此连接时,可以通过调用[close](#close)方法主动断开连接,之后客户端会收到[close](#onclose)事件的回调。 若在上述任一过程中发生错误,客户端会收到[error](#onerror)事件的回调。 - ## 导入模块 ```js @@ -21,44 +22,48 @@ import webSocket from '@ohos.net.webSocket'; ```js import webSocket from '@ohos.net.webSocket'; -var defaultIpAddress = "ws://"; +let defaultIpAddress = "ws://"; let ws = webSocket.createWebSocket(); ws.on('open', (err, value) => { - console.log("on open, status:" + value['status'] + ", message:" + value['message']); - // 当收到on('open')事件时,可以通过send()方法与服务器进行通信 - ws.send("Hello, server!", (err, value) => { - if (!err) { - console.log("send success"); - } else { - console.log("send fail, err:" + JSON.stringify(err)); - } - }); + if (err != undefined) { + console.log(JSON.stringify(err)) + return + } + console.log("on open, status:" + value['status'] + ", message:" + value['message']); + // 当收到on('open')事件时,可以通过send()方法与服务器进行通信 + ws.send("Hello, server!", (err, value) => { + if (!err) { + console.log("send success"); + } else { + console.log("send fail, err:" + JSON.stringify(err)); + } + }); }); ws.on('message', (err, value) => { - console.log("on message, message:" + value); - // 当收到服务器的`bye`消息时(此消息字段仅为示意,具体字段需要与服务器协商),主动断开连接 - if (value === 'bye') { - ws.close((err, value) => { - if (!err) { - console.log("close success"); - } else { - console.log("close fail, err is " + JSON.stringify(err)); - } - }); - } + console.log("on message, message:" + value); + // 当收到服务器的`bye`消息时(此消息字段仅为示意,具体字段需要与服务器协商),主动断开连接 + if (value === 'bye') { + ws.close((err, value) => { + if (!err) { + console.log("close success"); + } else { + console.log("close fail, err is " + JSON.stringify(err)); + } + }); + } }); ws.on('close', (err, value) => { - console.log("on close, code is " + value.code + ", reason is " + value.reason); + console.log("on close, code is " + value.code + ", reason is " + value.reason); }); ws.on('error', (err) => { - console.log("on error, error:" + JSON.stringify(err)); + console.log("on error, error:" + JSON.stringify(err)); }); ws.connect(defaultIpAddress, (err, value) => { - if (!err) { - console.log("connect success"); - } else { - console.log("connect fail, err:" + JSON.stringify(err)); - } + if (!err) { + console.log("connect success"); + } else { + console.log("connect fail, err:" + JSON.stringify(err)); + } }); ``` @@ -82,7 +87,6 @@ createWebSocket(): WebSocket let ws = webSocket.createWebSocket(); ``` - ## WebSocket 在调用WebSocket的方法前,需要先通过[webSocket.createWebSocket](#websocketcreatewebsocket)创建一个WebSocket。 @@ -93,6 +97,9 @@ connect(url: string, callback: AsyncCallback\): void 根据URL地址,建立一个WebSocket连接,使用callback方式作为异步方法。 +> **说明:** +> 可通过监听error事件获得该接口的执行结果,错误发生时会得到错误码:200。 + **需要权限**:ohos.permission.INTERNET **系统能力**:SystemCapability.Communication.NetStack @@ -117,21 +124,23 @@ connect(url: string, callback: AsyncCallback\): void let ws = webSocket.createWebSocket(); let url = "ws://" ws.connect(url, (err, value) => { - if (!err) { - console.log("connect success"); - } else { - console.log("connect fail, err:" + JSON.stringify(err)) - } + if (!err) { + console.log("connect success"); + } else { + console.log("connect fail, err:" + JSON.stringify(err)) + } }); ``` - ### connect connect(url: string, options: WebSocketRequestOptions, callback: AsyncCallback\): void 根据URL地址和header,建立一个WebSocket连接,使用callback方式作为异步方法。 +> **说明:** +> 可通过监听error事件获得该接口的执行结果,错误发生时会得到错误码:200。 + **需要权限**:ohos.permission.INTERNET **系统能力**:SystemCapability.Communication.NetStack @@ -157,26 +166,28 @@ connect(url: string, options: WebSocketRequestOptions, callback: AsyncCallback\< let ws = webSocket.createWebSocket(); let url = "ws://" ws.connect(url, { - header: { - "key": "value", - "key2": "value2" - } + header: { + "key": "value", + "key2": "value2" + } }, (err, value) => { - if (!err) { - console.log("connect success"); - } else { - console.log("connect fail, err:" + JSON.stringify(err)) - } + if (!err) { + console.log("connect success"); + } else { + console.log("connect fail, err:" + JSON.stringify(err)) + } }); ``` - ### connect connect(url: string, options?: WebSocketRequestOptions): Promise\ 根据URL地址和header,建立一个WebSocket连接,使用Promise方式作为异步方法。 +> **说明:** +> 可通过监听error事件获得该接口的执行结果,错误发生时会得到错误码:200。 + **需要权限**:ohos.permission.INTERNET **系统能力**:SystemCapability.Communication.NetStack @@ -208,13 +219,12 @@ let ws = webSocket.createWebSocket(); let url = "ws://" let promise = ws.connect(url); promise.then((value) => { - console.log("connect success") + console.log("connect success") }).catch((err) => { - console.log("connect fail, error:" + JSON.stringify(err)) + console.log("connect fail, error:" + JSON.stringify(err)) }); ``` - ### send send(data: string | ArrayBuffer, callback: AsyncCallback\): void @@ -245,17 +255,16 @@ send(data: string | ArrayBuffer, callback: AsyncCallback\): void let ws = webSocket.createWebSocket(); let url = "ws://" ws.connect(url, (err, value) => { - ws.send("Hello, server!", (err, value) => { - if (!err) { - console.log("send success"); - } else { - console.log("send fail, err:" + JSON.stringify(err)) - } - }); + ws.send("Hello, server!", (err, value) => { + if (!err) { + console.log("send success"); + } else { + console.log("send fail, err:" + JSON.stringify(err)) + } + }); }); ``` - ### send send(data: string | ArrayBuffer): Promise\ @@ -291,16 +300,15 @@ send(data: string | ArrayBuffer): Promise\ let ws = webSocket.createWebSocket(); let url = "ws://" ws.connect(url, (err, value) => { - let promise = ws.send("Hello, server!"); - promise.then((value) => { - console.log("send success") - }).catch((err) => { - console.log("send fail, error:" + JSON.stringify(err)) - }); + let promise = ws.send("Hello, server!"); + promise.then((value) => { + console.log("send success") + }).catch((err) => { + console.log("send fail, error:" + JSON.stringify(err)) + }); }); ``` - ### close close(callback: AsyncCallback\): void @@ -328,17 +336,15 @@ close(callback: AsyncCallback\): void ```js let ws = webSocket.createWebSocket(); -let url = "ws://" ws.close((err, value) => { - if (!err) { - console.log("close success") - } else { - console.log("close fail, err is " + JSON.stringify(err)) - } + if (!err) { + console.log("close success") + } else { + console.log("close fail, err is " + JSON.stringify(err)) + } }); ``` - ### close close(options: WebSocketCloseOptions, callback: AsyncCallback\): void @@ -367,20 +373,18 @@ close(options: WebSocketCloseOptions, callback: AsyncCallback\): void ```js let ws = webSocket.createWebSocket(); -let url = "ws://" ws.close({ - code: 1000, - reason: "your reason" + code: 1000, + reason: "your reason" }, (err, value) => { - if (!err) { - console.log("close success") - } else { - console.log("close fail, err is " + JSON.stringify(err)) - } + if (!err) { + console.log("close success") + } else { + console.log("close fail, err is " + JSON.stringify(err)) + } }); ``` - ### close close(options?: WebSocketCloseOptions): Promise\ @@ -414,19 +418,17 @@ close(options?: WebSocketCloseOptions): Promise\ ```js let ws = webSocket.createWebSocket(); -let url = "ws://" let promise = ws.close({ - code: 1000, - reason: "your reason" + code: 1000, + reason: "your reason" }); promise.then((value) => { - console.log("close success") + console.log("close success") }).catch((err) => { - console.log("close fail, err is " + JSON.stringify(err)) + console.log("close fail, err is " + JSON.stringify(err)) }); ``` - ### on('open') on(type: 'open', callback: AsyncCallback\): void @@ -442,25 +444,23 @@ on(type: 'open', callback: AsyncCallback\): void | type | string | 是 | 'open':WebSocket的打开事件。 | | callback | AsyncCallback\ | 是 | 回调函数。 | - **示例:** ```js let ws = webSocket.createWebSocket(); ws.on('open', (err, value) => { - console.log("on open, status:" + value['status'] + ", message:" + value['message']); + console.log("on open, status:" + value['status'] + ", message:" + value['message']); }); ``` - ### off('open') off(type: 'open', callback?: AsyncCallback\): void 取消订阅WebSocket的打开事件,使用callback方式作为异步方法。 ->**说明:** ->可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 +> **说明:** +> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 **系统能力**:SystemCapability.Communication.NetStack @@ -476,22 +476,21 @@ off(type: 'open', callback?: AsyncCallback\): void ```js let ws = webSocket.createWebSocket(); let callback1 = (err, value) => { - console.log("on open, status:" + value['status'] + ", message:" + value['message']); + console.log("on open, status:" + value['status'] + ", message:" + value['message']); } ws.on('open', callback1); // 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅 ws.off('open', callback1); ``` - ### on('message') on(type: 'message', callback: AsyncCallback\): void 订阅WebSocket的接收到服务器消息事件,使用callback方式作为异步方法。每个消息最大长度为4K,超过4K自动分片。 ->**说明:** ->AsyncCallback中的数据可以是字符串(API 6)或ArrayBuffer(API 8)。 +> **说明:** +> AsyncCallback中的数据可以是字符串(API 6)或ArrayBuffer(API 8)。 **系统能力**:SystemCapability.Communication.NetStack @@ -507,20 +506,19 @@ on(type: 'message', callback: AsyncCallback\): void ```js let ws = webSocket.createWebSocket(); ws.on('message', (err, value) => { - console.log("on message, message:" + value); + console.log("on message, message:" + value); }); ``` - ### off('message') off(type: 'message', callback?: AsyncCallback\): void 取消订阅WebSocket的接收到服务器消息事件,使用callback方式作为异步方法。每个消息最大长度为4K,超过4K自动分片。 ->**说明:** ->AsyncCallback中的数据可以是字符串(API 6)或ArrayBuffer(API 8)。 ->可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 +> **说明:** +> AsyncCallback中的数据可以是字符串(API 6)或ArrayBuffer(API 8)。 +> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 **系统能力**:SystemCapability.Communication.NetStack @@ -538,7 +536,6 @@ let ws = webSocket.createWebSocket(); ws.off('message'); ``` - ### on('close') on(type: 'close', callback: AsyncCallback\<{ code: number, reason: string }\>): void @@ -559,19 +556,18 @@ on(type: 'close', callback: AsyncCallback\<{ code: number, reason: string }\>): ```js let ws = webSocket.createWebSocket(); ws.on('close', (err, value) => { - console.log("on close, code is " + value.code + ", reason is " + value.reason); + console.log("on close, code is " + value.code + ", reason is " + value.reason); }); ``` - ### off('close') off(type: 'close', callback?: AsyncCallback\<{ code: number, reason: string }\>): void 取消订阅WebSocket的关闭事件,使用callback方式作为异步方法。 ->**说明:** ->可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 +> **说明:** +> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 **系统能力**:SystemCapability.Communication.NetStack @@ -589,7 +585,6 @@ let ws = webSocket.createWebSocket(); ws.off('close'); ``` - ### on('error') on(type: 'error', callback: ErrorCallback): void @@ -603,26 +598,25 @@ on(type: 'error', callback: ErrorCallback): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------- | ---- | ------------------------------- | | type | string | 是 | 'error':WebSocket的Error事件。 | -| callback | ErrorCallback | 是 | 回调函数。 | +| callback | ErrorCallback | 是 | 回调函数。
常见错误码:200 | **示例:** ```js let ws = webSocket.createWebSocket(); ws.on('error', (err) => { - console.log("on error, error:" + JSON.stringify(err)) + console.log("on error, error:" + JSON.stringify(err)) }); ``` - ### off('error') off(type: 'error', callback?: ErrorCallback): void 取消订阅WebSocket的Error事件,使用callback方式作为异步方法。 ->**说明:** ->可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 +> **说明:** +> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 **系统能力**:SystemCapability.Communication.NetStack @@ -640,7 +634,6 @@ let ws = webSocket.createWebSocket(); ws.off('error'); ``` - ## WebSocketRequestOptions 建立WebSocket连接时,可选参数的类型和说明。 @@ -651,7 +644,6 @@ ws.off('error'); | ------ | ------ | ---- | ------------------------------------------------------------ | | header | Object | 否 | 建立WebSocket连接可选参数,代表建立连接时携带的HTTP头信息。参数内容自定义,也可以不指定。 | - ## WebSocketCloseOptions 关闭WebSocket连接时,可选参数的类型和说明。