diff --git a/en/application-dev/connectivity/http-request.md b/en/application-dev/connectivity/http-request.md index 39ada2bc9b21b8e5d157806f5164c02219c65296..223e40a97ecddcfa6b1613106d94ba942ee22006 100644 --- a/en/application-dev/connectivity/http-request.md +++ b/en/application-dev/connectivity/http-request.md @@ -49,44 +49,43 @@ let httpRequest = http.createHttp(); // This API is used to listen for the HTTP Response Header event, which is returned earlier than the result of the HTTP request. It is up to you whether to listen for HTTP Response Header events. // on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8. httpRequest.on('headersReceive', (header) => { - console.info('header: ' + JSON.stringify(header)); + console.info('header: ' + JSON.stringify(header)); }); httpRequest.request( - // Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL. - "EXAMPLE_URL", - { - method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET. - // You can add header fields based on service requirements. - header: { - 'Content-Type': 'application/json' - }, - // This field is used to transfer data when the POST request is used. - extraData: { - "data": "data to send", - }, - expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data. - usingCache: true, // Optional. The default value is true. - priority: 1, // Optional. The default value is 1. - connectTimeout: 60000 // Optional. The default value is 60000, in ms. - readTimeout: 60000, // Optional. The default value is 60000, in ms. - usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system. - usingProxy: false, // Optional. By default, network proxy is not used. This field is supported since API 10. - }, (err, data) => { - if (!err) { - // data.result carries the HTTP response. Parse the response based on service requirements. - console.info('Result:' + JSON.stringify(data.result)); - console.info('code:' + JSON.stringify(data.responseCode)); - // data.header carries the HTTP response header. Parse the content based on service requirements. - console.info('header:' + JSON.stringify(data.header)); - console.info('cookies:' + JSON.stringify(data.cookies)); // 8+ - } else { - console.info('error:' + JSON.stringify(err)); - // Unsubscribe from HTTP Response Header events. - httpRequest.off('headersReceive'); - // Call the destroy() method to release resources after HttpRequest is complete. - httpRequest.destroy(); - } + // Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL. + { + method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET. + // You can add header fields based on service requirements. + header: { + 'Content-Type': 'application/json' + }, + // This field is used to transfer data when the POST request is used. + extraData: { + "data": "data to send", + }, + expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data. + usingCache: true, // Optional. The default value is true. + priority: 1, // Optional. The default value is 1. + connectTimeout: 60000 // Optional. The default value is 60000, in ms. + readTimeout: 60000, // Optional. The default value is 60000, in ms. + usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system. + usingProxy: false, // Optional. By default, network proxy is not used. This field is supported since API 10. + }, (err, data) => { + if (!err) { + // data.result carries the HTTP response. Parse the response based on service requirements. + console.info('Result:' + JSON.stringify(data.result)); + console.info('code:' + JSON.stringify(data.responseCode)); + // data.header carries the HTTP response header. Parse the content based on service requirements. + console.info('header:' + JSON.stringify(data.header)); + console.info('cookies:' + JSON.stringify(data.cookies)); // 8+ + } else { + console.info('error:' + JSON.stringify(err)); + // Unsubscribe from HTTP Response Header events. + httpRequest.off('headersReceive'); + // Call the destroy() method to release resources after HttpRequest is complete. + httpRequest.destroy(); } + } ); ``` @@ -108,61 +107,56 @@ import http from '@ohos.net.http' let httpRequest = http.createHttp(); // Subscribe to HTTP response header events. httpRequest.on('headersReceive', (header) => { - console.info('header: ' + JSON.stringify(header)); + console.info('header: ' + JSON.stringify(header)); }); // Subscribe to events indicating receiving of HTTP streaming responses. let res = ''; httpRequest.on('dataReceive', (data) => { - res += data; - console.info('res: ' + res); + res += data; + console.info('res: ' + res); }); // Subscribe to events indicating completion of receiving HTTP streaming responses. httpRequest.on('dataEnd', () => { - console.info('No more data in response, data receive end'); + console.info('No more data in response, data receive end'); }); // Subscribe to events indicating progress of receiving HTTP streaming responses. httpRequest.on('dataProgress', (data) => { - console.log("dataProgress receiveSize:" + data.receiveSize+ ", totalSize:" + data.totalSize); + console.log("dataProgress receiveSize:" + data.receiveSize + ", totalSize:" + data.totalSize); }); httpRequest.request2( - // Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL. - "EXAMPLE_URL", - { - method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET. - // You can add header fields based on service requirements. - header: { - 'Content-Type': 'application/json' - }, - // This field is used to transfer data when the POST request is used. - extraData: { - "data": "data to send", - }, - expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data. - usingCache: true, // Optional. The default value is true. - priority: 1, // Optional. The default value is 1. - connectTimeout: 60000 // Optional. The default value is 60000, in ms. - readTimeout: 60000, // Optional. The default value is 60000, in ms. If a large amount of data needs to be transmitted, you are advised to set this parameter to a larger value to ensure normal data transmission. - usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system. - }, (err, data) => { - console.info('error:' + JSON.stringify(err)); - console.info('ResponseCode :' + JSON.stringify(data)); - // Unsubscribe from HTTP Response Header events. - httpRequest.off('headersReceive'); - // Unregister the observer for events indicating receiving of HTTP streaming responses. - httpRequest.off('dataReceive'); - // Unregister the observer for events indicating progress of receiving HTTP streaming responses. - httpRequest.off('dataProgress'); - // Unregister the observer for events indicating completion of receiving HTTP streaming responses. - httpRequest.off('dataEnd'); - // Call the destroy() method to release resources after HttpRequest is complete. - httpRequest.destroy(); - } + // Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL. + "EXAMPLE_URL", + { + method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET. + // You can add header fields based on service requirements. + header: { + 'Content-Type': 'application/json' + }, + // This field is used to transfer data when the POST request is used. + extraData: { + "data": "data to send", + }, + expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data. + usingCache: true, // Optional. The default value is true. + priority: 1, // Optional. The default value is 1. + connectTimeout: 60000 // Optional. The default value is 60000, in ms. + readTimeout: 60000, // Optional. The default value is 60000, in ms. If a large amount of data needs to be transmitted, you are advised to set this parameter to a larger value to ensure normal data transmission. + usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system. + }, (err, data) => { + console.info('error:' + JSON.stringify(err)); + console.info('ResponseCode :' + JSON.stringify(data)); + // Unsubscribe from HTTP Response Header events. + httpRequest.off('headersReceive'); + // Unregister the observer for events indicating receiving of HTTP streaming responses. + httpRequest.off('dataReceive'); + // Unregister the observer for events indicating progress of receiving HTTP streaming responses. + httpRequest.off('dataProgress'); + // Unregister the observer for events indicating completion of receiving HTTP streaming responses. + httpRequest.off('dataEnd'); + // Call the destroy() method to release resources after HttpRequest is complete. + httpRequest.destroy(); + } ); -``` - -## Samples -The following sample is provided to help you better understand how to develop the HTTP data request feature: -- [HTTP Data Request (ArkTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Connectivity/Http) -- [HTTP Communication (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/SmartChatEtsOH) +``` \ No newline at end of file diff --git a/en/application-dev/connectivity/net-connection-manager.md b/en/application-dev/connectivity/net-connection-manager.md index 1eddb3b5bbe47cb4d02123986647955d0492629e..69ce20a372c60c2bf0443db2697c5a65352bf34c 100644 --- a/en/application-dev/connectivity/net-connection-manager.md +++ b/en/application-dev/connectivity/net-connection-manager.md @@ -1,31 +1,38 @@ # Network Connection Management ## Introduction + The Network Connection Management module provides basic network management capabilities, including management of Wi-Fi/cellular/Ethernet connection priorities, network quality evaluation, subscription to network connection status changes, query of network connection information, and DNS resolution. > **NOTE** > To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-connection.md). ## Basic Concepts -- Producer: a provider of data networks, such as Wi-Fi, cellular, and Ethernet. -- Consumer: a user of data networks, for example, an application or a system service. -- Network probe: a mechanism used to detect the network availability to prevent the switch from an available network to an unavailable network. The probe type can be binding network detection, DNS detection, HTTP detection, or HTTPS detection. -- Network selection: a mechanism used to select the optimal network when multiple networks coexist. It is triggered when the network status, network information, or network quality evaluation score changes. + +- Producer: a provider of data networks, such as Wi-Fi, cellular, and Ethernet. +- Consumer: a user of data networks, for example, an application or a system service. +- Network probe: a mechanism used to detect the network availability to prevent the switch from an available network to an unavailable network. The probe type can be binding network detection, DNS detection, HTTP detection, or HTTPS detection. +- Network selection: a mechanism used to select the optimal network when multiple networks coexist. It is triggered when the network status, network information, or network quality evaluation score changes. ## **Constraints** -- Programming language: C++ and JS -- System: Linux kernel -- The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +- Programming language: C++ and JS +- System: Linux kernel +- The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## When to Use + Typical application scenarios of network connection management are as follows: -- Subscribing to status changes of the specified network -- Obtaining the list of all registered networks -- Querying network connection information based on the data network -- Resolving the domain name of a network to obtain all IP addresses + +- Subscribing to status changes of the specified network +- Obtaining the list of all registered networks +- Querying network connection information based on the data network +- Resolving the domain name of a network to obtain all IP addresses The following describes the development procedure specific to each application scenario. + ## Available APIs + For the complete list of APIs and example code, see [Network Connection Management](../reference/apis/js-apis-net-connection.md). | Type| API| Description| @@ -75,44 +82,46 @@ For the complete list of APIs and example code, see [Network Connection Manageme ```js // Import the connection namespace. - import connection from '@ohos.net.connection' - - let netCap = { - // Assume that the default network is Wi-Fi. If you need to create a cellular network connection, set the network type to CELLULAR. - bearerTypes: [connection.NetBearType.BEARER_CELLULAR], - // Set the network capability to INTERNET. - networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET], - }; - let netSpec = { - netCapabilities: netCap, - }; - - // Set the timeout value to 10s. The default value is 0. - let timeout = 10 * 1000; - - // Create a NetConnection object. - let conn = connection.createNetConnection(netSpec, timeout); - - // Listen to network status change events. If the network is available, an on_netAvailable event is returned. - conn.on('netAvailable', (data=> { - console.log("net is available, netId is " + data.netId); - })); - - // Listen to network status change events. If the network is unavailable, an on_netUnavailable event is returned. - conn.on('netUnavailable', (data=> { - console.log("net is unavailable, netId is " + data.netId); - })); - - // Register an observer for network status changes. - conn.register((err, data) => {}); - - // Unregister the observer for network status changes. - conn.unregister((err, data) => {}); +import connection from '@ohos.net.connection' + +let netCap = { + // Assume that the default network is Wi-Fi. If you need to create a cellular network connection, set the network type to CELLULAR. + bearerTypes: [connection.NetBearType.BEARER_CELLULAR], + // Set the network capability to INTERNET. + networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET], +}; +let netSpec = { + netCapabilities: netCap, +}; + +// Set the timeout value to 10s. The default value is 0. +let timeout = 10 * 1000; + +// Create a NetConnection object. +let conn = connection.createNetConnection(netSpec, timeout); + +// Listen to network status change events. If the network is available, an on_netAvailable event is returned. +conn.on('netAvailable', (data => { + console.log("net is available, netId is " + data.netId); +})); + +// Listen to network status change events. If the network is unavailable, an on_netUnavailable event is returned. +conn.on('netUnavailable', (data => { + console.log("net is unavailable, netId is " + data.netId); +})); + +// Register an observer for network status changes. +conn.register((err, data) => { +}); + +// Unregister the observer for network status changes. +conn.unregister((err, data) => { +}); ``` -## Obtaining the List of All Registered Networks +## Obtaining the List of All Registered Networks -### How to Develop +### How to Develop 1. Import the connection namespace from **@ohos.net.connection.d.ts**. @@ -120,21 +129,21 @@ For the complete list of APIs and example code, see [Network Connection Manageme ```js // Import the connection namespace. - import connection from '@ohos.net.connection' - - // Obtain the list of all connected networks. - connection.getAllNets((err, data) => { - console.log(JSON.stringify(err)); - console.log(JSON.stringify(data)); - if (data) { - this.netList = data; - } - }) +import connection from '@ohos.net.connection' + +// Obtain the list of all connected networks. +connection.getAllNets((err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)); + if (data) { + this.netList = data; + } +}) ``` -## Querying Network Capability Information and Connection Information of Specified Data Network +## Querying Network Capability Information and Connection Information of Specified Data Network -### How to Develop +### How to Develop 1. Import the connection namespace from **@ohos.net.connection.d.ts**. @@ -146,89 +155,89 @@ For the complete list of APIs and example code, see [Network Connection Manageme ```js // Import the connection namespace. - import connection from '@ohos.net.connection' - - // Call getDefaultNet to obtain the default data network specified by **NetHandle**. - connection.getDefaultNet((err, data) => { - console.log(JSON.stringify(err)); - console.log(JSON.stringify(data)); - if (data) { - this.netHandle = data; - } - }) - - // Obtain the network capability information of the data network specified by **NetHandle**. The capability information includes information such as the network type and specific network capabilities. - connection.getNetCapabilities(this.netHandle, (err, data) => { - console.log(JSON.stringify(err)); - - // Obtain the network type via bearerTypes. - for (let item of data.bearerTypes) { - if (item == 0) { - // Cellular network - console.log(JSON.stringify("BEARER_CELLULAR")); - } else if (item == 1) { - // Wi-Fi network - console.log(JSON.stringify("BEARER_WIFI")); - } else if (item == 3) { - // Ethernet network - console.log(JSON.stringify("BEARER_ETHERNET")); - } - } - - // Obtain the specific network capabilities via networkCap. - for (let item of data.networkCap) { - if (item == 0) { - // The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages. - console.log(JSON.stringify("NET_CAPABILITY_MMS")); - } else if (item == 11) { - // The network traffic is not metered. - console.log(JSON.stringify("NET_CAPABILITY_NOT_METERED")); - } else if (item == 12) { - // The network has the Internet access capability, which is set by the network provider. - console.log(JSON.stringify("NET_CAPABILITY_INTERNET")); - } else if (item == 15) { - // The network does not use a Virtual Private Network (VPN). - console.log(JSON.stringify("NET_CAPABILITY_NOT_VPN")); - } else if (item == 16) { - // The Internet access capability of the network is successfully verified by the connection management module. - console.log(JSON.stringify("NET_CAPABILITY_VALIDATED")); - } - } - }) - - // Obtain the connection information of the data network specified by NetHandle. Connection information includes link and route information. - connection.getConnectionProperties(this.netHandle, (err, data) => { - console.log(JSON.stringify(err)); - console.log(JSON.stringify(data)); - }) - - // Call getAllNets to obtain the list of all connected networks via Array. - connection.getAllNets((err, data) => { - console.log(JSON.stringify(err)); - console.log(JSON.stringify(data)); - if (data) { - this.netList = data; - } - }) - - for (let item of this.netList) { - // Obtain the network capability information of the network specified by each netHandle on the network list cyclically. - connection.getNetCapabilities(item, (err, data) => { - console.log(JSON.stringify(err)); - console.log(JSON.stringify(data)); - }) - - // Obtain the connection information of the network specified by each netHandle on the network list cyclically. - connection.getConnectionProperties(item, (err, data) => { - console.log(JSON.stringify(err)); - console.log(JSON.stringify(data)); - }) - } +import connection from '@ohos.net.connection' + +// Call getDefaultNet to obtain the default data network specified by **NetHandle**. +connection.getDefaultNet((err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)); + if (data) { + this.netHandle = data; + } +}) + +// Obtain the network capability information of the data network specified by **NetHandle**. The capability information includes information such as the network type and specific network capabilities. +connection.getNetCapabilities(this.netHandle, (err, data) => { + console.log(JSON.stringify(err)); + + // Obtain the network type via bearerTypes. + for (let item of data.bearerTypes) { + if (item == 0) { + // Cellular network + console.log(JSON.stringify("BEARER_CELLULAR")); + } else if (item == 1) { + // Wi-Fi network + console.log(JSON.stringify("BEARER_WIFI")); + } else if (item == 3) { + // Ethernet network + console.log(JSON.stringify("BEARER_ETHERNET")); + } + } + + // Obtain the specific network capabilities via networkCap. + for (let item of data.networkCap) { + if (item == 0) { + // The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages. + console.log(JSON.stringify("NET_CAPABILITY_MMS")); + } else if (item == 11) { + // The network traffic is not metered. + console.log(JSON.stringify("NET_CAPABILITY_NOT_METERED")); + } else if (item == 12) { + // The network has the Internet access capability, which is set by the network provider. + console.log(JSON.stringify("NET_CAPABILITY_INTERNET")); + } else if (item == 15) { + // The network does not use a Virtual Private Network (VPN). + console.log(JSON.stringify("NET_CAPABILITY_NOT_VPN")); + } else if (item == 16) { + // The Internet access capability of the network is successfully verified by the connection management module. + console.log(JSON.stringify("NET_CAPABILITY_VALIDATED")); + } + } +}) + +// Obtain the connection information of the data network specified by NetHandle. Connection information includes link and route information. +connection.getConnectionProperties(this.netHandle, (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)); +}) + +// Call getAllNets to obtain the list of all connected networks via Array. +connection.getAllNets((err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)); + if (data) { + this.netList = data; + } +}) + +for (let item of this.netList) { + // Obtain the network capability information of the network specified by each netHandle on the network list cyclically. + connection.getNetCapabilities(item, (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)); + }) + + // Obtain the connection information of the network specified by each netHandle on the network list cyclically. + connection.getConnectionProperties(item, (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)); + }) +} ``` -## Resolving the domain name of a network to obtain all IP addresses +## Resolving the domain name of a network to obtain all IP addresses -### How to Develop +### How to Develop 1. Import the connection namespace from **@ohos.net.connection.d.ts**. @@ -236,11 +245,11 @@ For the complete list of APIs and example code, see [Network Connection Manageme ```js // Import the connection namespace. - import connection from '@ohos.net.connection' +import connection from '@ohos.net.connection' - // Use the default network to resolve the host name to obtain the list of all IP addresses. - connection.getAddressesByName(this.host, (err, data) => { - console.log(JSON.stringify(err)); - console.log(JSON.stringify(data)); - }) +// Use the default network to resolve the host name to obtain the list of all IP addresses. +connection.getAddressesByName(this.host, (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)); +}) ``` diff --git a/en/application-dev/connectivity/net-ethernet.md b/en/application-dev/connectivity/net-ethernet.md index 85c4ef4fc15f4c2228eb8351ddb5cd730ff5fe94..f1891594166c9ecf3688b93d78cdece890796d35 100644 --- a/en/application-dev/connectivity/net-ethernet.md +++ b/en/application-dev/connectivity/net-ethernet.md @@ -1,25 +1,29 @@ # Ethernet Connection ## Introduction -The Ethernet Connection module allows a device to access the Internet through a network cable. -After a device is connected to the Ethernet through a network cable, the device can obtain a series of network attributes, such as the dynamically allocated IP address, subnet mask, gateway, and DNS. You can manually configure and obtain the network attributes of the device in static mode. + +The Ethernet Connection module allows a device to access the Internet through a network cable. After a device is connected to the Ethernet through a network cable, the device can obtain a series of network attributes, such as the dynamically allocated IP address, subnet mask, gateway, and DNS. You can manually configure and obtain the network attributes of the device in static mode. > **NOTE** > To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-ethernet.md). ## **Constraints** -- Programming language: C++ and JS -- System: Linux kernel -- The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +- Programming language: C++ and JS +- System: Linux kernel +- The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## When to Use + Typical application scenarios of Ethernet connection are as follows: -- Dynamically assigning a series of network attributes, such as the IP address, subnet mask, gateway, and DNS in DHCP mode to enable network access -- Configuring a series of network attributes, such as the IP address, subnet mask, gateway, and DNS, in static mode to enable network access. + +- Dynamically assigning a series of network attributes, such as the IP address, subnet mask, gateway, and DNS in DHCP mode to enable network access +- Configuring a series of network attributes, such as the IP address, subnet mask, gateway, and DNS, in static mode to enable network access. The following describes the development procedure specific to each application scenario. ## Available APIs + For the complete list of APIs and example code, see [Ethernet Connection](../reference/apis/js-apis-net-ethernet.md). | Type| API| Description| @@ -28,6 +32,8 @@ For the complete list of APIs and example code, see [Ethernet Connection](../ref | ohos.net.ethernet | function getIfaceConfig(iface: string, callback: AsyncCallback\): void | Obtains the network attributes of the specified Ethernet network. This API uses an asynchronous callback to return the result.| | ohos.net.ethernet | function isIfaceActive(iface: string, callback: AsyncCallback\): void | Checks whether the specified network port is active. This API uses an asynchronous callback to return the result.| | ohos.net.ethernet | function getAllActiveIfaces(callback: AsyncCallback\>): void; | Obtains the list of all active network ports. This API uses an asynchronous callback to return the result.| +| ohos.net.ethernet | function on(type: 'interfaceStateChange', callback: Callback\<{ iface: string, active: boolean }\>): void; | Subscribes to interface state change events.| +| ohos.net.ethernet | function off(type: 'interfaceStateChange', callback?: Callback\<{ iface: string, active: boolean }\>): void; | Unsubscribes from interface state change events.| ## Ethernet Connection – DHCP Mode @@ -39,44 +45,45 @@ For the complete list of APIs and example code, see [Ethernet Connection](../ref ```js // Import the ethernet namespace from @ohos.net.ethernet. - import ethernet from '@ohos.net.ethernet' - - // Call getAllActiveIfaces to obtain the list of all active network ports. - ethernet.getAllActiveIfaces((error, data) => { - if (error) { - console.log("getAllActiveIfaces callback error = " + error); - } else { - console.log("getAllActiveIfaces callback data.length = " + data.length); - for (let i = 0; i < data.length; i++) { - console.log("getAllActiveIfaces callback = " + data[i]); - } - } - }); - - // Call isIfaceActive to check whether the specified network port is active. - ethernet.isIfaceActive("eth0", (error, data) => { - if (error) { - console.log("isIfaceActive callback error = " + error); - } else { - console.log("isIfaceActive callback = " + data); - } - }); - - // Call getIfaceConfig to obtain the network attributes of the specified Ethernet network. - ethernet.getIfaceConfig("eth0", (error, data) => { - if (error) { - console.log("getIfaceConfig callback error = " + error); - } else { - console.log("getIfaceConfig callback mode = " + data.mode); - console.log("getIfaceConfig callback ipAddr = " + data.ipAddr); - console.log("getIfaceConfig callback routeAddr = " + data.routeAddr); - console.log("getIfaceConfig callback gateAddr = " + data.gateAddr); - console.log("getIfaceConfig callback maskAddr = " + data.maskAddr); - console.log("getIfaceConfig callback dns0Addr = " + data.dns0Addr); - console.log("getIfaceConfig callback dns1Addr = " + data.dns1Addr); - } - }); +import ethernet from '@ohos.net.ethernet' + +// Call getAllActiveIfaces to obtain the list of all active network ports. +ethernet.getAllActiveIfaces((error, data) => { + if (error) { + console.log("getAllActiveIfaces callback error = " + error); + } else { + console.log("getAllActiveIfaces callback data.length = " + data.length); + for (let i = 0; i < data.length; i++) { + console.log("getAllActiveIfaces callback = " + data[i]); + } + } +}); + +// Call isIfaceActive to check whether the specified network port is active. +ethernet.isIfaceActive("eth0", (error, data) => { + if (error) { + console.log("isIfaceActive callback error = " + error); + } else { + console.log("isIfaceActive callback = " + data); + } +}); + +// Call getIfaceConfig to obtain the network attributes of the specified Ethernet network. +ethernet.getIfaceConfig("eth0", (error, data) => { + if (error) { + console.log("getIfaceConfig callback error = " + error); + } else { + console.log("getIfaceConfig callback mode = " + data.mode); + console.log("getIfaceConfig callback ipAddr = " + data.ipAddr); + console.log("getIfaceConfig callback routeAddr = " + data.routeAddr); + console.log("getIfaceConfig callback gateAddr = " + data.gateAddr); + console.log("getIfaceConfig callback maskAddr = " + data.maskAddr); + console.log("getIfaceConfig callback dns0Addr = " + data.dns0Addr); + console.log("getIfaceConfig callback dns1Addr = " + data.dns1Addr); + } +}); ``` + ## Ethernet Connection – Static Mode ### How to Develop @@ -90,51 +97,75 @@ For the complete list of APIs and example code, see [Ethernet Connection](../ref ```js // Import the ethernet namespace from @ohos.net.ethernet. - import ethernet from '@ohos.net.ethernet' - - // Call getAllActiveIfaces to obtain the list of all active network ports. - ethernet.getAllActiveIfaces((error, data) => { - if (error) { - console.log("getAllActiveIfaces callback error = " + error); - } else { - console.log("getAllActiveIfaces callback data.length = " + data.length); - for (let i = 0; i < data.length; i++) { - console.log("getAllActiveIfaces callback = " + data[i]); - } - } - }); - - // Call isIfaceActive to check whether the specified network port is active. - ethernet.isIfaceActive("eth0", (error, data) => { - if (error) { - console.log("isIfaceActive callback error = " + error); - } else { - console.log("isIfaceActive callback = " + data); - } - }); - - // Call setIfaceConfig to configure the network attributes of the specified Ethernet network. - ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.xx.xx", routeAddr:"192.168.xx.xx", - gateAddr:"192.168.xx.xx", maskAddr:"255.255.xx.xx", dnsAddr0:"1.1.xx.xx", dnsAddr1:"2.2.xx.xx"},(error) => { - if (error) { - console.log("setIfaceConfig callback error = " + error); - } else { - console.log("setIfaceConfig callback ok "); - } - }); - - // Call getIfaceConfig to obtain the network attributes of the specified Ethernet network. - ethernet.getIfaceConfig("eth0", (error, data) => { - if (error) { - console.log("getIfaceConfig callback error = " + error); - } else { - console.log("getIfaceConfig callback mode = " + data.mode); - console.log("getIfaceConfig callback ipAddr = " + data.ipAddr); - console.log("getIfaceConfig callback routeAddr = " + data.routeAddr); - console.log("getIfaceConfig callback gateAddr = " + data.gateAddr); - console.log("getIfaceConfig callback maskAddr = " + data.maskAddr); - console.log("getIfaceConfig callback dns0Addr = " + data.dns0Addr); - console.log("getIfaceConfig callback dns1Addr = " + data.dns1Addr); - } - }); +import ethernet from '@ohos.net.ethernet' + +// Call getAllActiveIfaces to obtain the list of all active network ports. +ethernet.getAllActiveIfaces((error, data) => { + if (error) { + console.log("getAllActiveIfaces callback error = " + error); + } else { + console.log("getAllActiveIfaces callback data.length = " + data.length); + for (let i = 0; i < data.length; i++) { + console.log("getAllActiveIfaces callback = " + data[i]); + } + } +}); + +// Call isIfaceActive to check whether the specified network port is active. +ethernet.isIfaceActive("eth0", (error, data) => { + if (error) { + console.log("isIfaceActive callback error = " + error); + } else { + console.log("isIfaceActive callback = " + data); + } +}); + +// Call setIfaceConfig to configure the network attributes of the specified Ethernet network. +ethernet.setIfaceConfig("eth0", { + mode: ethernet.STATIC, ipAddr: "192.168.xx.xx", routeAddr: "192.168.xx.xx", + gateAddr: "192.168.xx.xx", maskAddr: "255.255.xx.xx", dnsAddr0: "1.1.xx.xx", dnsAddr1: "2.2.xx.xx" +}, (error) => { + if (error) { + console.log("setIfaceConfig callback error = " + error); + } else { + console.log("setIfaceConfig callback ok "); + } +}); + +// Call getIfaceConfig to obtain the network attributes of the specified Ethernet network. +ethernet.getIfaceConfig("eth0", (error, data) => { + if (error) { + console.log("getIfaceConfig callback error = " + error); + } else { + console.log("getIfaceConfig callback mode = " + data.mode); + console.log("getIfaceConfig callback ipAddr = " + data.ipAddr); + console.log("getIfaceConfig callback routeAddr = " + data.routeAddr); + console.log("getIfaceConfig callback gateAddr = " + data.gateAddr); + console.log("getIfaceConfig callback maskAddr = " + data.maskAddr); + console.log("getIfaceConfig callback dns0Addr = " + data.dns0Addr); + console.log("getIfaceConfig callback dns1Addr = " + data.dns1Addr); + } +}); +``` + +## Subscribes the status change of network device interfaces. + +### How to Develop + +1. Import the **ethernet** namespace from **@ohos.net.ethernet**. +2. Call the **on()** method to subscribe to **interfaceStateChange** events. It is up to you whether to listen for **interfaceStateChange** events. +3. Check whether an **interfaceStateChange** event is triggered when the interface state changes. +4. Call the **off()** method to unsubscribe from **interfaceStateChange** events. + +```js + // Import the ethernet namespace from @ohos.net.ethernet. +import ethernet from '@ohos.net.ethernet' + +// Subscribe to interfaceStateChange events. +ethernet.on('interfaceStateChange', ((data) => { + console.log(JSON.stringify(data)); +})); + +// Unsubscribe from interfaceStateChange events. +ethernet.off('interfaceStateChange'); ``` diff --git a/en/application-dev/connectivity/net-sharing.md b/en/application-dev/connectivity/net-sharing.md index d5bc9cf2f8817723f0f23d666c45997a6735f706..331ffec3b1a1e0047c39e2fe416ad5c05e913b61 100644 --- a/en/application-dev/connectivity/net-sharing.md +++ b/en/application-dev/connectivity/net-sharing.md @@ -1,29 +1,36 @@ # Network Sharing ## Introduction + The Network Sharing module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing. It also allows you to query the network sharing state and shared mobile data volume. > **NOTE** > To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-sharing.md). ## Basic Concepts -- Wi-Fi sharing: Shares the network through a Wi-Fi hotspot. -- Bluetooth sharing: Shares the network through Bluetooth. -- USB tethering: Shares the network using a USB flash drive. + +- Wi-Fi sharing: Shares the network through a Wi-Fi hotspot. +- Bluetooth sharing: Shares the network through Bluetooth. +- USB tethering: Shares the network using a USB flash drive. ## **Constraints** -- Programming language: C++ and JS -- System: Linux kernel -- The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +- Programming language: C++ and JS +- System: Linux kernel +- The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## When to Use + Typical network sharing scenarios are as follows: -- Enabling network sharing -- Disabling network sharing -- Obtaining the data traffic of the shared network + +- Enabling network sharing +- Disabling network sharing +- Obtaining the data traffic of the shared network The following describes the development procedure specific to each application scenario. + ## Available APIs + For the complete list of APIs and example code, see [Network Sharing](../reference/apis/js-apis-net-sharing.md). | Type| API| Description| @@ -54,18 +61,18 @@ For the complete list of APIs and example code, see [Network Sharing](../referen ```js // Import the sharing namespace from @ohos.net.sharing. - import sharing from '@ohos.net.sharing' - - // Subscribe to network sharing state changes. - sharing.on('sharingStateChange', (error, data) => { - console.log(JSON.stringify(error)); - console.log(JSON.stringify(data)); - }); - - // Call startSharing to start network sharing of the specified type. - sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { - console.log(JSON.stringify(error)); - }); +import sharing from '@ohos.net.sharing' + +// Subscribe to network sharing state changes. +sharing.on('sharingStateChange', (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); + +// Call startSharing to start network sharing of the specified type. +sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { + console.log(JSON.stringify(error)); +}); ``` ## Disabling network sharing @@ -79,18 +86,18 @@ For the complete list of APIs and example code, see [Network Sharing](../referen ```js // Import the sharing namespace from @ohos.net.sharing. - import sharing from '@ohos.net.sharing' - - // Subscribe to network sharing state changes. - sharing.on('sharingStateChange', (error, data) => { - console.log(JSON.stringify(error)); - console.log(JSON.stringify(data)); - }); - - // Call stopSharing to stop network sharing of the specified type. - sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { - console.log(JSON.stringify(error)); - }); +import sharing from '@ohos.net.sharing' + +// Subscribe to network sharing state changes. +sharing.on('sharingStateChange', (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); + +// Call stopSharing to stop network sharing of the specified type. +sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { + console.log(JSON.stringify(error)); +}); ``` ## Obtaining the data traffic of the shared network @@ -104,27 +111,27 @@ For the complete list of APIs and example code, see [Network Sharing](../referen ```js // Import the sharing namespace from @ohos.net.sharing. - import sharing from '@ohos.net.sharing' - - // Call startSharing to start network sharing of the specified type. - sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { - console.log(JSON.stringify(error)); - }); - - // Call getStatsTotalBytes to obtain the data traffic generated during data sharing. - sharing.getStatsTotalBytes((error, data) => { - console.log(JSON.stringify(error)); - console.log(JSON.stringify(data)); - }); - - // Call stopSharing to stop network sharing of the specified type and clear the data volume of network sharing. - sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { - console.log(JSON.stringify(error)); - }); - - // Call getStatsTotalBytes again. The data volume of network sharing has been cleared. - sharing.getStatsTotalBytes((error, data) => { - console.log(JSON.stringify(error)); - console.log(JSON.stringify(data)); - }); +import sharing from '@ohos.net.sharing' + +// Call startSharing to start network sharing of the specified type. +sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { + console.log(JSON.stringify(error)); +}); + +// Call getStatsTotalBytes to obtain the data traffic generated during data sharing. +sharing.getStatsTotalBytes((error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); + +// Call stopSharing to stop network sharing of the specified type and clear the data volume of network sharing. +sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { + console.log(JSON.stringify(error)); +}); + +// Call getStatsTotalBytes again. The data volume of network sharing has been cleared. +sharing.getStatsTotalBytes((error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); ``` diff --git a/en/application-dev/connectivity/socket-connection.md b/en/application-dev/connectivity/socket-connection.md index 5cae73b2a5c84f280aea80e299605ee80ac2553a..ea2a3ba6dcfb849ea64971503e246e94b16f34a1 100644 --- a/en/application-dev/connectivity/socket-connection.md +++ b/en/application-dev/connectivity/socket-connection.md @@ -186,136 +186,136 @@ TLS Socket connection process on the client: ```js import socket from '@ohos.net.socket' - // Create a TLS Socket connection (for two-way authentication). - let tlsTwoWay = socket.constructTLSSocketInstance(); - - // Subscribe to TLS Socket connection events. - 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") - }); - - // Bind the local IP address and port number. - tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { - if (err) { - console.log('bind fail'); - return; - } - console.log('bind success'); - }); - - // Set the communication parameters. - let options = { - ALPNProtocols: ["spdy/1", "http/1.1"], - - // Set up a connection to the specified IP address and port number. - address: { - address: "192.168.xx.xxx", - port: xxxx, // Port - family: 1, - }, - - // Set the parameters used for authentication during communication. - secureOptions: { - key: "xxxx", // Key - cert: "xxxx", // Digital certificate - ca: ["xxxx"], // CA certificate - passwd: "xxxx", // Password for generating the key - protocols: [socket.Protocol.TLSv12], // Communication protocol - useRemoteCipherPrefer: true, // Whether to preferentially use the peer cipher suite - signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", // Signature algorithm - cipherSuite: "AES256-SHA256", // Cipher suite - }, - }; - - // Set up a connection. - tlsTwoWay.connect(options, (err, data) => { - console.error(err); - console.log(data); - }); - - // Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events. - 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'); - }); - - // Create a TLS Socket connection (for one-way authentication). - let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication - - // Subscribe to TLS Socket connection events. - 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") - }); - - // Bind the local IP address and port number. - tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { - if (err) { - console.log('bind fail'); - return; - } - console.log('bind success'); - }); - - // Set the communication parameters. - let oneWayOptions = { - address: { - address: "192.168.xxx.xxx", - port: xxxx, - family: 1, - }, - secureOptions: { - ca: ["xxxx","xxxx"], // CA certificate - cipherSuite: "AES256-SHA256", // Cipher suite - }, - }; - - // Set up a connection. - tlsOneWay.connect(oneWayOptions, (err, data) => { - console.error(err); - console.log(data); - }); - - // Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events. - 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'); - }); -``` +// Create a TLS Socket connection (for two-way authentication). +let tlsTwoWay = socket.constructTLSSocketInstance(); + +// Subscribe to TLS Socket connection events. +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") +}); + +// Bind the local IP address and port number. +tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { + if (err) { + console.log('bind fail'); + return; + } + console.log('bind success'); +}); + +// Set the communication parameters. +let options = { + ALPNProtocols: ["spdy/1", "http/1.1"], + + // Set up a connection to the specified IP address and port number. + address: { + address: "192.168.xx.xxx", + port: xxxx, // Port + family: 1, + }, + + // Set the parameters used for authentication during communication. + secureOptions: { + key: "xxxx", // Key + cert: "xxxx", // Digital certificate + ca: ["xxxx"], // CA certificate + passwd: "xxxx", // Password for generating the key + protocols: [socket.Protocol.TLSv12], // Communication protocol + useRemoteCipherPrefer: true, // Whether to preferentially use the peer cipher suite + signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", // Signature algorithm + cipherSuite: "AES256-SHA256", // Cipher suite + }, +}; + +// Set up a connection. +tlsTwoWay.connect(options, (err, data) => { + console.error(err); + console.log(data); +}); + +// Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events. +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'); +}); + +// Create a TLS Socket connection (for one-way authentication). +let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication + +// Subscribe to TLS Socket connection events. +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") +}); + +// Bind the local IP address and port number. +tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { + if (err) { + console.log('bind fail'); + return; + } + console.log('bind success'); +}); + +// Set the communication parameters. +let oneWayOptions = { + address: { + address: "192.168.xxx.xxx", + port: xxxx, + family: 1, + }, + secureOptions: { + ca: ["xxxx","xxxx"], // CA certificate + cipherSuite: "AES256-SHA256", // Cipher suite + }, +}; + +// Set up a connection. +tlsOneWay.connect(oneWayOptions, (err, data) => { + console.error(err); + console.log(data); +}); + +// Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events. +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'); +}); +``` \ No newline at end of file diff --git a/en/application-dev/connectivity/websocket-connection.md b/en/application-dev/connectivity/websocket-connection.md index b68d537fc5ad96f3ab60b53e2e75a96d7b555f76..dfcc9bd7f877393bf1bf8d868046d5d12e896678 100644 --- a/en/application-dev/connectivity/websocket-connection.md +++ b/en/application-dev/connectivity/websocket-connection.md @@ -1,45 +1,42 @@ # WebSocket Connection - -## Use Cases +## When to Use You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the **createWebSocket()** API to create a **WebSocket** object and then use the **connect()** API to connect to the server. If the connection is successful, the client will receive a callback of the **open** event. Then, the client can communicate with the server using the **send()** API. When the server sends a message to the client, the client will receive a callback of the **message** event. If the client no longer needs this connection, it can call the **close()** API to disconnect from the server. Then, the client will receive a callback of the **close** event. If an error occurs in any of the preceding processes, the client will receive a callback of the **error** event. - ## Available APIs The WebSocket connection function is mainly implemented by the WebSocket module. To use related APIs, you must declare the **ohos.permission.INTERNET** permission. The following table describes the related APIs. -| API | Description | +| API| Description| | -------- | -------- | -| createWebSocket() | Creates a WebSocket connection. | -| connect() | Establishes a WebSocket connection to a given URL. | -| send() | Sends data through the WebSocket connection. | -| close() | Closes a WebSocket connection. | -| on(type: 'open') | Enables listening for **open** events of a WebSocket connection. | -| off(type: 'open') | Disables listening for **open** events of a WebSocket connection. | -| on(type: 'message') | Enables listening for **message** events of a WebSocket connection. | -| off(type: 'message') | Disables listening for **message** events of a WebSocket connection. | -| on(type: 'close') | Enables listening for **close** events of a WebSocket connection. | -| off(type: 'close') | Disables listening for **close** events of a WebSocket connection. | -| on(type: 'error') | Enables listening for **error** events of a WebSocket connection. | -| off(type: 'error') | Disables listening for **error** events of a WebSocket connection. | - +| createWebSocket() | Creates a WebSocket connection.| +| connect() | Establishes a WebSocket connection to a given URL.| +| send() | Sends data through the WebSocket connection.| +| close() | Closes a WebSocket connection.| +| on(type: 'open') | Enables listening for **open** events of a WebSocket connection.| +| off(type: 'open') | Disables listening for **open** events of a WebSocket connection.| +| on(type: 'message') | Enables listening for **message** events of a WebSocket connection.| +| off(type: 'message') | Disables listening for **message** events of a WebSocket connection.| +| on(type: 'close') | Enables listening for **close** events of a WebSocket connection.| +| off(type: 'close') | Disables listening for **close** events of a WebSocket connection.| +| on(type: 'error') | Enables listening for **error** events of a WebSocket connection.| +| off(type: 'error') | Disables listening for **error** events of a WebSocket connection.| ## How to Develop -1. Import the required WebSocket module. +1. Import the required webSocket module. 2. Create a **WebSocket** object. -3. (Optional) Subscribe to WebSocket open, message, close, and error events. +3. (Optional) Subscribe to WebSocket **open**, **message**, **close**, and **error** events. 4. Establish a WebSocket connection to a given URL. 5. Close the WebSocket connection if it is no longer needed. - + ```js import webSocket from '@ohos.net.webSocket'; diff --git a/en/application-dev/reference/apis/js-apis-hidebug.md b/en/application-dev/reference/apis/js-apis-hidebug.md index 186b2dc92d8bf4fd2693f06b5b6e062bb9a7fc29..bf0666974e940393f8da4ec229eeae3e7d59e639 100644 --- a/en/application-dev/reference/apis/js-apis-hidebug.md +++ b/en/application-dev/reference/apis/js-apis-hidebug.md @@ -173,7 +173,7 @@ Obtains system service information. **Example** ```js -import fileio from '@ohos.fileio' +import fs from '@ohos.file.fs' import hidebug from '@ohos.hidebug' import featureAbility from '@ohos.ability.featureAbility' @@ -181,7 +181,7 @@ let context = featureAbility.getContext(); context.getFilesDir().then((data) => { var path = data + "/serviceInfo.txt" console.info("output path: " + path) - let fd = fileio.openSync(path, 0o102, 0o666) + let fd = fs.openSync(path, 0o102, 0o666) var serviceId = 10 var args = new Array("allInfo") try { @@ -190,7 +190,7 @@ context.getFilesDir().then((data) => { console.info(error.code) console.info(error.message) } - fileio.closeSync(fd); + fs.closeSync(fd); }) ``` @@ -283,7 +283,7 @@ try { startProfiling(filename : string) : void -> **NOTE**
This API is deprecated since API version 9. You are advised to use [hidebug.startJsCpuProfiling](#hidebugstartjscpuprofiling9) instead. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [hidebug.startJsCpuProfiling](#hidebugstartjscpuprofiling9). Starts the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`. @@ -309,7 +309,7 @@ hidebug.stopProfiling(); stopProfiling() : void -> **NOTE**
This API is deprecated since API version 9. You are advised to use [hidebug.stopJsCpuProfiling](#hidebugstopjscpuprofiling9) instead. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [hidebug.stopJsCpuProfiling](#hidebugstopjscpuprofiling9). Stops the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`. @@ -329,7 +329,7 @@ hidebug.stopProfiling(); dumpHeapData(filename : string) : void -> **NOTE**
This API is deprecated since API version 9. You are advised to use [hidebug.dumpJsHeapData](#hidebugdumpjsheapdata9) instead. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [hidebug.dumpJsHeapData](#hidebugdumpjsheapdata9). Exports the heap data. diff --git a/en/application-dev/reference/apis/js-apis-http.md b/en/application-dev/reference/apis/js-apis-http.md index 1d0ef9bbc8c424b0e6538a55993cc5f993f7af20..fcee0a77ce1fcadabd6c8209ea8502984f4c1c94 100644 --- a/en/application-dev/reference/apis/js-apis-http.md +++ b/en/application-dev/reference/apis/js-apis-http.md @@ -2,7 +2,7 @@ The **http** module provides the HTTP data request capability. An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**. ->**NOTE** +> **NOTE** > >The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > @@ -24,44 +24,44 @@ let httpRequest = http.createHttp(); // This API is used to listen for the HTTP Response Header event, which is returned earlier than the result of the HTTP request. It is up to you whether to listen for HTTP Response Header events. // on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8. httpRequest.on('headersReceive', (header) => { - console.info('header: ' + JSON.stringify(header)); + console.info('header: ' + JSON.stringify(header)); }); httpRequest.request( - // Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL. - "EXAMPLE_URL", - { - method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET. - // You can add header fields based on service requirements. - header: { - 'Content-Type': 'application/json' - }, - // This field is used to transfer data when the POST request is used. - extraData: { - "data": "data to send", - }, - expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data. - usingCache: true, // Optional. The default value is true. - priority: 1, // Optional. The default value is 1. - connectTimeout: 60000 // Optional. The default value is 60000, in ms. - readTimeout: 60000, // Optional. The default value is 60000, in ms. - usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system. - usingProxy: false, // Optional. By default, network proxy is not used. This field is supported since API 10. - }, (err, data) => { - if (!err) { - // data.result carries the HTTP response. Parse the response based on service requirements. - console.info('Result:' + JSON.stringify(data.result)); - console.info('code:' + JSON.stringify(data.responseCode)); - // data.header carries the HTTP response header. Parse the content based on service requirements. - console.info('header:' + JSON.stringify(data.header)); - console.info('cookies:' + JSON.stringify(data.cookies)); // 8+ - } else { - console.info('error:' + JSON.stringify(err)); - // Unsubscribe from HTTP Response Header events. - httpRequest.off('headersReceive'); - // Call the destroy() method to release resources after HttpRequest is complete. - httpRequest.destroy(); - } + // Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL. + "EXAMPLE_URL", + { + method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET. + // You can add header fields based on service requirements. + header: { + 'Content-Type': 'application/json' + }, + // This parameter is used to transfer data when the POST request is used. + extraData: { + "data": "data to send", + }, + expectDataType: http.HttpDataType.STRING, // Optional. This parameter specifies the type of the return data. + usingCache: true, // Optional. The default value is true. + priority: 1, // Optional. The default value is 1. + connectTimeout: 60000 // Optional. The default value is 60000, in ms. + readTimeout: 60000, // Optional. The default value is 60000, in ms. + usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system. + usingProxy: false, // Optional. By default, network proxy is not used. This field is supported since API 10. + }, (err, data) => { + if (!err) { + // data.result carries the HTTP response. Parse the response based on service requirements. + console.info('Result:' + JSON.stringify(data.result)); + console.info('code:' + JSON.stringify(data.responseCode)); + // data.header carries the HTTP response header. Parse the content based on service requirements. + console.info('header:' + JSON.stringify(data.header)); + console.info('cookies:' + JSON.stringify(data.cookies)); // 8+ + } else { + console.info('error:' + JSON.stringify(err)); + // Unsubscribe from HTTP Response Header events. + httpRequest.off('headersReceive'); + // Call the destroy() method to release resources after HttpRequest is complete. + httpRequest.destroy(); } + } ); ``` @@ -83,6 +83,7 @@ Creates an HTTP request. You can use this API to initiate or destroy an HTTP req ```js import http from '@ohos.net.http'; + let httpRequest = http.createHttp(); ``` @@ -96,8 +97,8 @@ request(url: string, callback: AsyncCallback\):void Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result. ->**NOTE** ->This API supports only transfer of data not greater than 5 MB. +> **NOTE** +> This API supports only transfer of data not greater than 5 MB. **Required permissions**: ohos.permission.INTERNET @@ -122,7 +123,7 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback | 2300052 | Server returned nothing (no headers, no data). | | 2300999 | Unknown Other Error. | ->**NOTE** +> **NOTE** > For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). > The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html). @@ -130,14 +131,14 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback ```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)); + } }); ``` @@ -147,8 +148,8 @@ request(url: string, options: HttpRequestOptions, callback: AsyncCallback\**NOTE** ->This API supports only transfer of data not greater than 5 MB. +> **NOTE** +> This API supports only transfer of data not greater than 5 MB. **Required permissions**: ohos.permission.INTERNET @@ -198,7 +199,7 @@ Initiates an HTTP request containing specified options to a given URL. This API | 2300094 | An authentication function returned an error. | | 2300999 | Unknown Other Error. | ->**NOTE** +> **NOTE** > For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). > The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html). @@ -206,25 +207,25 @@ Initiates an HTTP request containing specified options to a given URL. This API ```js httpRequest.request("EXAMPLE_URL", -{ + { method: http.RequestMethod.GET, header: { - 'Content-Type': 'application/json' + 'Content-Type': 'application/json' }, readTimeout: 60000, connectTimeout: 60000 -}, (err, data) => { + }, (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 @@ -233,8 +234,8 @@ request(url: string, options? : HttpRequestOptions): Promise\ Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result. ->**NOTE** ->This API supports only transfer of data not greater than 5 MB. +> **NOTE** +> This API supports only transfer of data not greater than 5 MB. **Required permissions**: ohos.permission.INTERNET @@ -289,7 +290,7 @@ Initiates an HTTP request containing specified options to a given URL. This API | 2300094 | An authentication function returned an error. | | 2300999 | Unknown Other Error. | ->**NOTE** +> **NOTE** > For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). > The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html). @@ -297,22 +298,22 @@ Initiates an HTTP request containing specified options to a given URL. This API ```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)); }); ``` @@ -334,7 +335,7 @@ httpRequest.destroy(); request2(url: string, callback: AsyncCallback\): void -Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result, which is a streaming response. +Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result, which is a streaming response. **Required permissions**: ohos.permission.INTERNET @@ -359,7 +360,7 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback | 2300052 | Server returned nothing (no headers, no data). | | 2300999 | Unknown Other Error. | ->**NOTE** +> **NOTE** > For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). > The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html). @@ -367,11 +368,11 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback ```js httpRequest.request2("EXAMPLE_URL", (err, data) => { - if (!err) { - console.info("request2 OK! ResponseCode is " + JSON.stringify(data)); - } else { - console.info("request2 ERROR : err = " + JSON.stringify(err)); - } + if (!err) { + console.info("request2 OK! ResponseCode is " + JSON.stringify(data)); + } else { + console.info("request2 ERROR : err = " + JSON.stringify(err)); + } }) ``` @@ -429,7 +430,7 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback | 2300094 | An authentication function returned an error. | | 2300999 | Unknown Other Error. | ->**NOTE** +> **NOTE** > For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). > The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html). @@ -437,21 +438,22 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback ```js httpRequest.request2("EXAMPLE_URL", -{ + { method: http.RequestMethod.GET, header: { - 'Content-Type': 'application/json' + 'Content-Type': 'application/json' }, readTimeout: 60000, connectTimeout: 60000 -}, (err, data) => { + }, (err, data) => { if (!err) { - console.info("request2 OK! ResponseCode is " + JSON.stringify(data)); + console.info("request2 OK! ResponseCode is " + JSON.stringify(data)); } else { - console.info("request2 ERROR : err = " + JSON.stringify(err)); + console.info("request2 ERROR : err = " + JSON.stringify(err)); } -}) + }) ``` + ### request210+ request2(url: string, options? : HttpRequestOptions): Promise\ @@ -472,7 +474,7 @@ Initiates an HTTP request containing specified options to a given URL. This API **Return value** | Type | Description | -| :------------------------------------- | :-------------------------------- | +| ------------------------------------- | -------------------------------- | | Promise\<[number](#responsecode)\> | Promise used to return the result.| **Error codes** @@ -511,25 +513,25 @@ Initiates an HTTP request containing specified options to a given URL. This API | 2300094 | An authentication function returned an error. | | 2300999 | Unknown Other Error. | ->**NOTE** +> **NOTE** > For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). > The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html). **Example** ```js -let promise = httpRequest.request("EXAMPLE_URL", { - method: http.RequestMethod.GET, - connectTimeout: 60000, - readTimeout: 60000, - header: { - 'Content-Type': 'application/json' - } +let promise = httpRequest.request2("EXAMPLE_URL", { + method: http.RequestMethod.GET, + connectTimeout: 60000, + readTimeout: 60000, + header: { + 'Content-Type': 'application/json' + } }); promise.then((data) => { - console.info("request2 OK!" + JSON.stringify(data)); + console.info("request2 OK!" + JSON.stringify(data)); }).catch((err) => { - console.info("request2 ERROR : err = " + JSON.stringify(err)); + console.info("request2 ERROR : err = " + JSON.stringify(err)); }); ``` @@ -539,8 +541,8 @@ on(type: 'headerReceive', callback: AsyncCallback\): void Registers an observer for HTTP Response Header events. ->**NOTE** ->This API has been deprecated. You are advised to use [on('headersReceive')8+](#onheadersreceive8). +> **NOTE** +> This API has been deprecated. You are advised to use [on('headersReceive')8+](#onheadersreceive8). **System capability**: SystemCapability.Communication.NetStack @@ -555,7 +557,7 @@ Registers an observer for HTTP Response Header events. ```js httpRequest.on('headerReceive', (data) => { - console.info('error:' + JSON.stringify(data)); + console.info('error:' + JSON.stringify(data)); }); ``` @@ -565,7 +567,7 @@ off(type: 'headerReceive', callback?: AsyncCallback\): void Unregisters the observer for HTTP Response Header events. ->**NOTE** +> **NOTE** > >1. This API has been deprecated. You are advised to use [off('headersReceive')8+](#offheadersreceive8). > @@ -605,7 +607,7 @@ Registers an observer for HTTP Response Header events. ```js httpRequest.on('headersReceive', (header) => { - console.info('header: ' + JSON.stringify(header)); + console.info('header: ' + JSON.stringify(header)); }); ``` @@ -615,8 +617,8 @@ off(type: 'headersReceive', callback?: Callback\): void Unregisters the observer for HTTP Response Header events. ->**NOTE** ->You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. +> **NOTE** +> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -652,9 +654,10 @@ Registers a one-time observer for HTTP Response Header events. Once triggered, t ```js httpRequest.once('headersReceive', (header) => { - console.info('header: ' + JSON.stringify(header)); + console.info('header: ' + JSON.stringify(header)); }); ``` + ### on('dataReceive')10+ on(type: 'dataReceive', callback: Callback\): void @@ -674,7 +677,7 @@ Registers an observer for events indicating receiving of HTTP streaming response ```js httpRequest.on('dataReceive', (data) => { - console.info('dataReceive length: ' + JSON.stringify(data.byteLength)); + console.info('dataReceive length: ' + JSON.stringify(data.byteLength)); }); ``` @@ -684,8 +687,8 @@ off(type: 'dataReceive', callback?: Callback\): void Unregisters the observer for events indicating receiving of HTTP streaming responses. ->**NOTE** ->You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. +> **NOTE** +> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -720,8 +723,8 @@ Registers an observer for events indicating completion of receiving HTTP streami **Example** ```js -httpRequest.on('dataReceive', () => { - console.info('Receive dataEnd! '); +httpRequest.on('dataEnd', () => { + console.info('Receive dataEnd !'); }); ``` @@ -731,8 +734,8 @@ off(type: 'dataEnd', callback?: Callback\): void Unregisters the observer for events indicating completion of receiving HTTP streaming responses. ->**NOTE** ->You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. +> **NOTE** +> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -751,7 +754,7 @@ httpRequest.off('dataEnd'); ### on('dataProgress')10+ - on(type: 'dataProgress', callback: Callback\<{ receiveSize: number, totalSize: number }\>): void +on(type: 'dataProgress', callback: AsyncCallback\<{ receiveSize: number, totalSize: number }\>): void Registers an observer for events indicating progress of receiving HTTP streaming responses. @@ -762,13 +765,13 @@ Registers an observer for events indicating progress of receiving HTTP streaming | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | --------------------------------- | | type | string | Yes | Event type. The value is **dataProgress**.| -| callback | AsyncCallback\<{ receiveSize: number, totalSize: number }\> | Yes | Callback used to return the result.
**receiveSize**: number of received bytes.
**totalSize**: total number of bytes to be received.| +| callback | AsyncCallback\<{ receiveSize: number, totalSize: number }\> | Yes | Callback used to return the result.
- **receiveSize**: number of received bytes.
- **totalSize**: total number of bytes to be received.| **Example** ```js httpRequest.on('dataProgress', (data) => { - console.info('dataProgress:' + JSON.stringify(data)); + console.info('dataProgress:' + JSON.stringify(data)); }); ``` @@ -778,8 +781,8 @@ off(type: 'dataProgress', callback?: Callback\<{ receiveSize: number, totalSize: Unregisters the observer for events indicating progress of receiving HTTP streaming responses. ->**NOTE** ->You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. +> **NOTE** +> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -795,6 +798,7 @@ Unregisters the observer for events indicating progress of receiving HTTP stream ```js httpRequest.off('dataProgress'); ``` + ## HttpRequestOptions Specifies the type and value range of the optional parameters in the HTTP request. @@ -803,11 +807,11 @@ Specifies the type and value range of the optional parameters in the HTTP reques | Name | Type | Mandatory| Description | | -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | -| method | [RequestMethod](#requestmethod) | No | Request method. | -| extraData | string \| Object \| ArrayBuffer6+ | No | Additional data of the request.
- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.
- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.6+
- To pass in a string object, you first need to encode the object on your own.6+ | -| expectDataType9+ | [HttpDataType](#httpdatatype9) | No | Type of the return data. If this parameter is set, the system returns the specified type of data preferentially.| +| method | [RequestMethod](#requestmethod) | No | Request method. The default value is **GET**. | +| extraData | string6+ \| Object6+ \| ArrayBuffer8+ | No | Additional data for sending a request. This parameter is not used by default.
- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request and is encoded in UTF-8 format.6+
- If the HTTP request uses the GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter serves as a supplement to HTTP request parameters. Parameters of the string type need to be encoded before being passed to the HTTP request. Parameters of the object type do not need to be precoded and will be directly concatenated to the URL. Parameters of the ArrayBuffer type will not be concatenated to the URL.6+ | +| expectDataType9+ | [HttpDataType](#httpdatatype9) | No | Type of the returned data. This parameter is not used by default. If this parameter is set, the system returns the specified type of data preferentially.| | usingCache9+ | boolean | No | Whether to use the cache. The default value is **true**. | -| priority9+ | number | No | Priority. The value range is \[1,1000]. The default value is **1**. | +| priority9+ | number | No | Priority. The value range is \[0, 1000]. The default value is **0**. | | header | Object | No | HTTP request header. The default value is **{'Content-Type': 'application/json'}**. | | readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. | | connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. | @@ -883,10 +887,10 @@ Defines the response to an HTTP request. | Name | Type | Mandatory| Description | | -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | -| result | string \| Object \| ArrayBuffer6+ | Yes | Response content returned based on **Content-type** in the response header:
- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.
- application/octet-stream: ArrayBuffer
- Others: string| +| result | string6+ \| Objectdeprecated 8+ \| ArrayBuffer8+ | Yes | Response content returned based on **Content-type** in the response header:
- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.
- application/octet-stream: ArrayBuffer
- Others: string| | resultType9+ | [HttpDataType](#httpdatatype9) | Yes | Type of the return value. | | responseCode | [ResponseCode](#responsecode) \| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**.| -| header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:
- Content-Type: header['Content-Type'];
- Status-Line: header['Status-Line'];
- Date: header.Date/header['Date'];
- Server: header.Server/header['Server'];| +| header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:
- content-type: header['content-type'];
- status-line: header['status-line'];
- date: header.date/header['date'];
- server: header.server/header['server'];| | cookies8+ | string | Yes | Cookies returned by the server. | ## http.createHttpResponseCache9+ @@ -913,6 +917,7 @@ Creates a default object to store responses to HTTP access requests. ```js import http from '@ohos.net.http'; + let httpResponseCache = http.createHttpResponseCache(); ``` @@ -995,6 +1000,7 @@ httpResponseCache.delete(err => { console.info('delete success'); }); ``` + ### delete9+ delete(): Promise\ diff --git a/en/application-dev/reference/apis/js-apis-net-connection.md b/en/application-dev/reference/apis/js-apis-net-connection.md index f5c48ddd07342118d752a82a00972aec398685ea..45d8c07528dcfdcd553743d1b512ca4e0ec8f2ae 100644 --- a/en/application-dev/reference/apis/js-apis-net-connection.md +++ b/en/application-dev/reference/apis/js-apis-net-connection.md @@ -10,6 +10,7 @@ The network connection management module provides basic network management capab ```js import connection from '@ohos.net.connection' ``` + ## connection.createNetConnection createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection @@ -34,14 +35,14 @@ Creates a **NetConnection** object. **netSpecifier** specifies the network, and **Example** ```js -// Default network +// For the default network, you do not need to pass in parameters. let netConnection = connection.createNetConnection() -// Cellular network +// For the cellular network, you need to pass in related network parameters. If the timeout parameter is not specified, the timeout value is 0 by default. let netConnectionCellular = connection.createNetConnection({ - netCapabilities: { - bearerTypes: [connection.NetBearType.BEARER_CELLULAR] - } + netCapabilities: { + bearerTypes: [connection.NetBearType.BEARER_CELLULAR] + } }) ``` @@ -73,8 +74,8 @@ Obtains the default active data network. This API uses an asynchronous callback ```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 @@ Obtains the default active data network. This API uses a promise to return the r ```js connection.getDefaultNet().then(function (data) { - console.log(JSON.stringify(data)) + console.log(JSON.stringify(data)) }) ``` @@ -166,9 +167,9 @@ Obtains the global HTTP proxy configuration of the network. This API uses an asy **Example** ```js -connection.getGlobalHttpProxy((error,data) => { - console.info(JSON.stringify(error)); - console.info(JSON.stringify(data)); +connection.getGlobalHttpProxy((error, data) => { + console.info(JSON.stringify(error)); + console.info(JSON.stringify(data)); }) ``` @@ -199,9 +200,9 @@ Obtains the global HTTP proxy configuration of the network. This API uses a prom ```js connection.getGlobalHttpProxy().then((data) => { - console.info(JSON.stringify(data)); + console.info(JSON.stringify(data)); }).catch(error => { - console.info(JSON.stringify(error)); + console.info(JSON.stringify(error)); }) ``` @@ -237,16 +238,15 @@ Sets the global HTTP proxy configuration of the network. This API uses an asynch **Example** ```js -let exclusionStr="192.168,baidu.com" +let exclusionStr = "192.168,baidu.com" let exclusionArray = exclusionStr.split(','); let httpProxy = { - host: "192.168.xx.xxx", - port: 8080, - exclusionList: exclusionArray + host: "192.168.xx.xxx", + port: 8080, + exclusionList: exclusionArray } -connection.setGlobalHttpProxy(httpProxy, (error, data) => { - console.info(JSON.stringify(error)); - console.info(JSON.stringify(data)); +connection.setGlobalHttpProxy(httpProxy, (error) => { + console.info(JSON.stringify(error)); }); ``` @@ -287,17 +287,17 @@ Sets the global HTTP proxy configuration of the network. This API uses a promise **Example** ```js -let exclusionStr="192.168,baidu.com" +let exclusionStr = "192.168,baidu.com" let exclusionArray = exclusionStr.split(','); let httpProxy = { - host: "192.168.xx.xxx", - port: 8080, - exclusionList: exclusionArray + host: "192.168.xx.xxx", + port: 8080, + exclusionList: exclusionArray } connection.setGlobalHttpProxy(httpProxy).then(() => { - console.info("success"); -}).catch(error=>{ - console.info(JSON.stringify(error)); + console.info("success"); +}).catch(error => { + console.info(JSON.stringify(error)); }) ``` @@ -325,9 +325,9 @@ Obtains information about the network bound to an application. This API uses an **Example** ```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)) }) ``` @@ -356,9 +356,9 @@ Obtains information about the network bound to an application. This API uses a p ```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)); }) ``` @@ -393,10 +393,10 @@ Binds an application to the specified network, so that the application can acces ```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)) + }); }) ``` @@ -436,11 +436,11 @@ Binds an application to the specified network, so that the application can acces ```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)) + }) }) ``` @@ -472,8 +472,8 @@ Obtains the list of all connected networks. This API uses an asynchronous callba ```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)) }); ``` @@ -505,7 +505,7 @@ Obtains the list of all connected networks. This API uses a promise to return th ```js connection.getAllNets().then(function (data) { - console.log(JSON.stringify(data)) + console.log(JSON.stringify(data)) }); ``` @@ -540,10 +540,10 @@ Obtains connection properties of the network corresponding to the **netHandle**. ```js connection.getDefaultNet().then(function (netHandle) { - connection.getConnectionProperties(netHandle, function (error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) - }) + connection.getConnectionProperties(netHandle, function (error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) + }) }) ``` @@ -583,9 +583,9 @@ Obtains connection properties of the network corresponding to the **netHandle**. ```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)) + }) }) ``` @@ -620,10 +620,10 @@ Obtains capability information of the network corresponding to the **netHandle** ```js connection.getDefaultNet().then(function (netHandle) { - connection.getNetCapabilities(netHandle, function (error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) - }) + connection.getNetCapabilities(netHandle, function (error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) + }) }) ``` @@ -663,9 +663,9 @@ Obtains capability information of the network corresponding to the **netHandle** ```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)) + }) }) ``` @@ -697,8 +697,8 @@ Checks whether the data traffic usage on the current network is metered. This AP ```js connection.isDefaultNetMetered(function (error, data) { - console.log(JSON.stringify(error)) - console.log('data: ' + data) + console.log(JSON.stringify(error)) + console.log('data: ' + data) }) ``` @@ -730,7 +730,7 @@ Checks whether the data traffic usage on the current network is metered. This AP ```js connection.isDefaultNetMetered().then(function (data) { - console.log('data: ' + data) + console.log('data: ' + data) }) ``` @@ -762,8 +762,8 @@ Checks whether the default data network is activated. This API uses an asynchron ```js connection.hasDefaultNet(function (error, data) { - console.log(JSON.stringify(error)) - console.log('data: ' + data) + console.log(JSON.stringify(error)) + console.log('data: ' + data) }) ``` @@ -795,7 +795,7 @@ Checks whether the default data network is activated. This API uses a promise to ```js connection.hasDefaultNet().then(function (data) { - console.log('data: ' + data) + console.log('data: ' + data) }) ``` @@ -828,7 +828,7 @@ Enables the airplane mode. This API uses an asynchronous callback to return the ```js connection.enableAirplaneMode(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) ``` @@ -861,7 +861,7 @@ Enables the airplane mode. This API uses a promise to return the result. ```js connection.enableAirplaneMode().then(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) ``` @@ -894,7 +894,7 @@ Disables the airplane mode. This API uses an asynchronous callback to return the ```js connection.disableAirplaneMode(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) ``` @@ -927,7 +927,7 @@ Disables the airplane mode. This API uses a promise to return the result. ```js connection.disableAirplaneMode().then(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) ``` @@ -935,8 +935,7 @@ connection.disableAirplaneMode().then(function (error) { reportNetConnected(netHandle: NetHandle, callback: AsyncCallback<void>): void -Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. -This API uses an asynchronous callback to return the result. +Reports connection of the data network to the network management module. This API uses an asynchronous callback to return the result. **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET @@ -963,9 +962,9 @@ This API uses an asynchronous callback to return the result. ```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)) + }); }); ``` @@ -973,8 +972,7 @@ connection.getDefaultNet().then(function (netHandle) { reportNetConnected(netHandle: NetHandle): Promise<void> -Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. -This API uses a promise to return the result. +Reports connection of the data network to the network management module. This API uses a promise to return the result. **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET @@ -1005,9 +1003,9 @@ This API uses a promise to return the result. ```js connection.getDefaultNet().then(function (netHandle) { - connection.reportNetConnected(netHandle).then(function () { - console.log(`report success`) - }); + connection.reportNetConnected(netHandle).then(function () { + console.log(`report success`) + }); }); ``` @@ -1015,8 +1013,7 @@ connection.getDefaultNet().then(function (netHandle) { reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback<void>): void -Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. -This API uses an asynchronous callback to return the result. +Reports disconnection of the data network to the network management module. This API uses an asynchronous callback to return the result. **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET @@ -1043,9 +1040,9 @@ This API uses an asynchronous callback to return the result. ```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)) + }); }); ``` @@ -1053,8 +1050,7 @@ connection.getDefaultNet().then(function (netHandle) { reportNetDisconnected(netHandle: NetHandle): Promise<void> -Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. -This API uses a promise to return the result. +Reports disconnection of the data network to the network management module. This API uses a promise to return the result. **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET @@ -1085,9 +1081,9 @@ This API uses a promise to return the result. ```js connection.getDefaultNet().then(function (netHandle) { - connection.reportNetDisconnected(netHandle).then(function () { - console.log(`report success`) - }); + connection.reportNetDisconnected(netHandle).then(function () { + console.log(`report success`) + }); }); ``` @@ -1123,8 +1119,8 @@ Resolves the host name by using the default network to obtain all IP addresses. ```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)) }) ``` @@ -1165,7 +1161,7 @@ Resolves the host name by using the default network to obtain all IP addresses. ```js let host = "xxxx"; connection.getAddressesByName(host).then(function (data) { - console.log(JSON.stringify(data)) + console.log(JSON.stringify(data)) }) ``` @@ -1173,6 +1169,11 @@ connection.getAddressesByName(host).then(function (data) { Represents the network connection handle. +> **NOTE** +> When a device changes to the network connected state, the **netAvailable**, **netCapabilitiesChange**, and **netConnectionPropertiesChange** events will be triggered. +> When a device changes to the network disconnected state, the **netLost** event will be triggered. +> When a device switches from a Wi-Fi network to a cellular network, the **netLost** event will be first triggered to indicate that the Wi-Fi network is lost and then the **netAvaliable** event will be triggered to indicate that the cellular network is available. + ### register register(callback: AsyncCallback\): void @@ -1199,12 +1200,11 @@ Registers a listener for network status changes. | 2101008 | The callback is not exists. | | 2101022 | The number of requests exceeded the maximum. | - **Example** ```js netConnection.register(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) ``` @@ -1234,7 +1234,7 @@ Unregisters the listener for network status changes. ```js netConnection.unregister(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) ``` @@ -1263,17 +1263,17 @@ let netCon = connection.createNetConnection() // Call register to register a listener. netCon.register(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) // Subscribe to netAvailable events. Event notifications can be received only after register is called. netCon.on('netAvailable', function (data) { - console.log(JSON.stringify(data)) + console.log(JSON.stringify(data)) }) // Call unregister to unregister the listener. netCon.unregister(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) ``` @@ -1281,9 +1281,9 @@ netCon.unregister(function (error) { on(type: 'netBlockStatusChange', callback: Callback<{ netHandle: NetHandle, blocked: boolean }>): void -Registers a listener for **netBlockStatusChange** events. +Registers a listener for **netBlockStatusChange** events. This API uses an asynchronous callback to return the result. -**Model restriction**: Before you call this API, make sure tat you have called **register** to add a listener and called **unregister** API to unsubscribe from status changes of the default network. +**Model restriction**: Before you call this API, make sure that you have called **register** to add a listener and called **unregister** API to unsubscribe from status changes of the default network. **System capability**: SystemCapability.Communication.NetManager.Core @@ -1302,17 +1302,17 @@ let netCon = connection.createNetConnection() // Call register to register a listener. netCon.register(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) // Subscribe to netBlockStatusChange events. Event notifications can be received only after register is called. netCon.on('netBlockStatusChange', function (data) { - console.log(JSON.stringify(data)) + console.log(JSON.stringify(data)) }) // Call unregister to unregister the listener. netCon.unregister(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) ``` @@ -1341,23 +1341,24 @@ let netCon = connection.createNetConnection() // Call register to register a listener. netCon.register(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) // Subscribe to netCapabilitiesChange events. Event notifications can be received only after register is called. netCon.on('netCapabilitiesChange', function (data) { - console.log(JSON.stringify(data)) + console.log(JSON.stringify(data)) }) // Call unregister to unregister the listener. 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 Registers a listener for **netConnectionPropertiesChange** events. @@ -1370,7 +1371,7 @@ Registers a listener for **netConnectionPropertiesChange** events. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | string | Yes | Event type. The value is fixed to **netConnectionPropertiesChange**.
**netConnectionPropertiesChange**: event indicating that network connection properties have changed.| -| callback | Callback<{ netHandle: [NetHandle](#nethandle), connectionProperties: [ConnectionProperties](#connectionproperties) }> | Yes | Callback used to return the network handle (**netHandle**) and capability information (**netCap**).| +| callback | Callback<{ netHandle: [NetHandle](#nethandle), connectionProperties: [ConnectionProperties](#connectionproperties) }> | Yes | Callback used to return the network handle (**netHandle**) and connection information (**connectionProperties**).| **Example** @@ -1380,17 +1381,17 @@ let netCon = connection.createNetConnection() // Call register to register a listener. netCon.register(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) // Subscribe to netConnectionPropertiesChange events. Event notifications can be received only after register is called. netCon.on('netConnectionPropertiesChange', function (data) { - console.log(JSON.stringify(data)) + console.log(JSON.stringify(data)) }) // Call unregister to unregister the listener. netCon.unregister(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) ``` @@ -1419,17 +1420,17 @@ let netCon = connection.createNetConnection() // Call register to register a listener. netCon.register(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) // Subscribe to netLost events. Event notifications can be received only after register is called. netCon.on('netLost', function (data) { - console.log(JSON.stringify(data)) + console.log(JSON.stringify(data)) }) // Call unregister to unregister the listener. netCon.unregister(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) ``` @@ -1458,17 +1459,17 @@ let netCon = connection.createNetConnection() // Call register to register a listener. netCon.register(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) // Subscribe to netUnavailable events. Event notifications can be received only after register is called. netCon.on('netUnavailable', function (data) { - console.log(JSON.stringify(data)) + console.log(JSON.stringify(data)) }) // Call unregister to unregister the listener. netCon.unregister(function (error) { - console.log(JSON.stringify(error)) + console.log(JSON.stringify(error)) }) ``` @@ -1514,48 +1515,51 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses ```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)); + } + }) + }) + } }) ``` @@ -1592,44 +1596,47 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses ```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)); + }) + }) + } }) ``` @@ -1664,11 +1671,11 @@ Resolves the host name by using the corresponding network to obtain all IP addre ```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)) + }) }) ``` @@ -1708,10 +1715,10 @@ Resolves the host name by using the corresponding network to obtain all IP addre ```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)) + }) }) ``` @@ -1746,11 +1753,11 @@ Resolves the host name by using the corresponding network to obtain the first IP ```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)) + }) }) ``` @@ -1790,10 +1797,10 @@ Resolves the host name by using the corresponding network to obtain the first IP ```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)) + }) }) ``` @@ -1905,8 +1912,8 @@ Defines a network address. **System capability**: SystemCapability.Communication.NetManager.Core -| Name | Type | Mandatory| Description | +| Name| Type| Mandatory| Description| | ------- | ------ | -- |------------------------------ | -| address | string | Yes|Network address. | +| address | string | Yes|Network address.| | family | number | No|Address family identifier. The value is **1** for IPv4 and **2** for IPv6. The default value is **1**.| -| port | number | No|Port number. The value ranges from **0** to **65535**. | +| port | number | No|Port number. The value ranges from **0** to **65535**.| diff --git a/en/application-dev/reference/apis/js-apis-net-ethernet.md b/en/application-dev/reference/apis/js-apis-net-ethernet.md index d86e3904ec9c8789a645fde87492da5f5cd0c250..25a7622ad00c1a62d3df0a85a94b703664ef64d4 100644 --- a/en/application-dev/reference/apis/js-apis-net-ethernet.md +++ b/en/application-dev/reference/apis/js-apis-net-ethernet.md @@ -48,19 +48,19 @@ Sets the network interface configuration. This API uses an asynchronous callback ```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 @@ Sets the network interface configuration. This API uses a promise to return the ```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 @@ Obtains the configuration of a network interface. This API uses an asynchronous ```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 @@ Obtains the configuration of a network interface. This API uses a promise to ret ```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 @@ Checks whether a network interface is active. This API uses an asynchronous call ```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 @@ Checks whether a network interface is active. This API uses a promise to return ```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 @@ Obtains the list of all active network interfaces. This API uses an asynchronous ```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 @@ Obtains the list of all active network interfaces. This API uses a promise to re ```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 + +Registers an observer for NIC hot swap events. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Ethernet + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | string | Yes | Event type. The value is **interfaceStateChange**.| +| callback | AsyncCallback\<{ iface: string, active: boolean }\> | Yes | Callback used to return the result.
**iface**: NIC name.
**active**: whether the NIC is active. The value **true** indicates that the NIC is active, and the value **false** indicates the opposite.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 202 | Applicable only to system applications. | +| 401 | Parameter error. | + +**Example** + +```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 + +Unregisters the observer for NIC hot swap events. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Ethernet + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | string | Yes | Event type. The value is **interfaceStateChange**.| +| callback | AsyncCallback\<{ iface: string, active: boolean }> | No | Callback used to return the result.
**iface**: NIC name.
**active**: whether the NIC is active. The value **true** indicates that the NIC is active, and the value **false** indicates the opposite.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 202 | Applicable only to system applications. | +| 401 | Parameter error. | + +**Example** + +```js +ethernet.off('interfaceStateChange'); +``` + ## InterfaceConfiguration Defines the network configuration for the Ethernet connection. diff --git a/en/application-dev/reference/apis/js-apis-net-mdns.md b/en/application-dev/reference/apis/js-apis-net-mdns.md index 2f32a68fea2b56a3acd4458f09ebff0102bcbc16..2190dbe59ceca1336096944b8203826263c5294e 100644 --- a/en/application-dev/reference/apis/js-apis-net-mdns.md +++ b/en/application-dev/reference/apis/js-apis-net-mdns.md @@ -10,6 +10,7 @@ Multicast DNS (mDNS) provides functions such as adding, removing, discovering, a ```js import mdns from '@ohos.net.mdns' ``` + ## mdns.addLocalService addLocalService(context: Context, serviceInfo: LocalServiceInfo, callback: AsyncCallback\): void @@ -22,7 +23,7 @@ Adds an mDNS service. This API uses an asynchronous callback to return the resul | Name | Type | Mandatory| Description | |-------------|----------------------------------|-----------|-------------------------------------------------| -| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-app-ability-uiAbility.md).| | serviceInfo | [LocalServiceInfo](#localserviceinfo) | Yes | mDNS service information. | | callback | AsyncCallback\<[LocalServiceInfo](#localserviceinfo)> | Yes | Callback used to return the result. If the operation is successful, **error** is **undefined** and **data** is the mDNS service information. | @@ -37,28 +38,65 @@ Adds an mDNS service. This API uses an asynchronous callback to return the resul | 2204008 | Service instance duplicated. | | 2204010 | Send packet failed. | ->**NOTE** +> **NOTE** > For details about the error codes, see [mDNS Error Codes](../errorcodes/errorcode-net-mdns.md). **Example** +FA model: + ```js +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); + +let localServiceInfo = { + serviceType: "_print._tcp", + serviceName: "servicename", + port: 5555, + host: { + address: "10.14.**.***", + }, + serviceAttribute: [{ + key: "111", + value: [1] + }] +} + +mdns.addLocalService(context, localServiceInfo, function (error, data) { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +Stage model: + +```ts +// Obtain the context. +import UIAbility from '@ohos.app.ability.UIAbility'; +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + globalThis.context = this.context; + } +} +let context = globalThis.context; + let localServiceInfo = { - serviceType: "_print._tcp", - serviceName: "servicename", - port: 5555, - host: { - address: "10.14.**.***", - }, - serviceAttribute: [{ - key: "111", - value: [1] - }] + serviceType: "_print._tcp", + serviceName: "servicename", + port: 5555, + host: { + address: "10.14.**.***", + }, + serviceAttribute: [{ + key: "111", + value: [1] + }] } mdns.addLocalService(context, localServiceInfo, function (error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); }); ``` @@ -74,7 +112,7 @@ Adds an mDNS service. This API uses a promise to return the result. | Name | Type | Mandatory| Description | |-------------|----------------------------------|-----------|-------------------------------------------------| -| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-app-ability-uiAbility.md).| | serviceInfo | [LocalServiceInfo](#localserviceinfo) | Yes | mDNS service information. | **Return value** @@ -94,27 +132,63 @@ Adds an mDNS service. This API uses a promise to return the result. | 2204008 | Service instance duplicated. | | 2204010 | Send packet failed. | ->**NOTE** +> **NOTE** > For details about the error codes, see [mDNS Error Codes](../errorcodes/errorcode-net-mdns.md). **Example** +FA model: + ```js +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); + +let localServiceInfo = { + serviceType: "_print._tcp", + serviceName: "servicename", + port: 5555, + host: { + address: "10.14.**.***", + }, + serviceAttribute: [{ + key: "111", + value: [1] + }] +} + +mdns.addLocalService(context, localServiceInfo).then(function (data) { + console.log(JSON.stringify(data)); +}); +``` + +Stage model: + +```ts +// Obtain the context. +import UIAbility from '@ohos.app.ability.UIAbility'; +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + globalThis.context = this.context; + } +} +let context = globalThis.context; + let localServiceInfo = { - serviceType: "_print._tcp", - serviceName: "servicename", - port: 5555, - host: { - address: "10.14.**.***", - }, - serviceAttribute: [{ - key: "111", - value: [1] - }] + serviceType: "_print._tcp", + serviceName: "servicename", + port: 5555, + host: { + address: "10.14.**.***", + }, + serviceAttribute: [{ + key: "111", + value: [1] + }] } mdns.addLocalService(context, localServiceInfo).then(function (data) { - console.log(JSON.stringify(data)) + console.log(JSON.stringify(data)); }); ``` @@ -130,7 +204,7 @@ Removes an mDNS service. This API uses an asynchronous callback to return the re | Name | Type | Mandatory| Description | |-------------|----------------------------------|-----------|-------------------------------------------------| -| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-app-ability-uiAbility.md).| | serviceInfo | [LocalServiceInfo](#localserviceinfo) | Yes | mDNS service information. | | callback | AsyncCallback\<[LocalServiceInfo](#localserviceinfo)> | Yes | Callback used to return the result. If the operation is successful, **error** is **undefined** and **data** is the mDNS service information. | @@ -145,28 +219,65 @@ Removes an mDNS service. This API uses an asynchronous callback to return the re | 2204008 | Service instance duplicated. | | 2204010 | Send packet failed. | ->**NOTE** +> **NOTE** > For details about the error codes, see [mDNS Error Codes](../errorcodes/errorcode-net-mdns.md). **Example** +FA model: + ```js +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); + +let localServiceInfo = { + serviceType: "_print._tcp", + serviceName: "servicename", + port: 5555, + host: { + address: "10.14.**.***", + }, + serviceAttribute: [{ + key: "111", + value: [1] + }] +} + +mdns.removeLocalService(context, localServiceInfo, function (error, data) { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +Stage model: + +```ts +// Obtain the context. +import UIAbility from '@ohos.app.ability.UIAbility'; +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + globalThis.context = this.context; + } +} +let context = globalThis.context; + let localServiceInfo = { - serviceType: "_print._tcp", - serviceName: "servicename", - port: 5555, - host: { - address: "10.14.**.***", - }, - serviceAttribute: [{ - key: "111", - value: [1] - }] + serviceType: "_print._tcp", + serviceName: "servicename", + port: 5555, + host: { + address: "10.14.**.***", + }, + serviceAttribute: [{ + key: "111", + value: [1] + }] } mdns.removeLocalService(context, localServiceInfo, function (error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); }); ``` @@ -182,7 +293,7 @@ Removes an mDNS service. This API uses a promise to return the result. | Name | Type | Mandatory| Description | |-------------|----------------------------------|-----------|-------------------------------------------------| -| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-app-ability-uiAbility.md).| | serviceInfo | [LocalServiceInfo](#localserviceinfo) | Yes | mDNS service information. | **Return value** @@ -202,27 +313,63 @@ Removes an mDNS service. This API uses a promise to return the result. | 2204008 | Service instance duplicated. | | 2204010 | Send packet failed. | ->**NOTE** +> **NOTE** > For details about the error codes, see [mDNS Error Codes](../errorcodes/errorcode-net-mdns.md). **Example** +FA model: + ```js +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); + +let localServiceInfo = { + serviceType: "_print._tcp", + serviceName: "servicename", + port: 5555, + host: { + address: "10.14.**.***", + }, + serviceAttribute: [{ + key: "111", + value: [1] + }] +} + +mdns.removeLocalService(context, localServiceInfo).then(function (data) { + console.log(JSON.stringify(data)); +}); +``` + +Stage model: + +```ts +// Obtain the context. +import UIAbility from '@ohos.app.ability.UIAbility'; +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + globalThis.context = this.context; + } +} +let context = globalThis.context; + let localServiceInfo = { - serviceType: "_print._tcp", - serviceName: "servicename", - port: 5555, - host: { - address: "10.14.**.***", - }, - serviceAttribute: [{ - key: "111", - value: [1] - }] + serviceType: "_print._tcp", + serviceName: "servicename", + port: 5555, + host: { + address: "10.14.**.***", + }, + serviceAttribute: [{ + key: "111", + value: [1] + }] } mdns.removeLocalService(context, localServiceInfo).then(function (data) { - console.log(JSON.stringify(data)) + console.log(JSON.stringify(data)); }); ``` @@ -238,20 +385,41 @@ Creates a **DiscoveryService** object, which is used to discover mDNS services o | Name | Type | Mandatory| Description | |-------------|---------|-----------| ------------------------------------------------------------ | -| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-app-ability-uiAbility.md).| | serviceType | string | Yes | Type of the mDNS services to be discovered.| **Return value** | Type | Description | | ----------------------------- |---------------------------------| -| DiscoveryService | **DiscoveryService** object used to discover mDNS services of the specified type.| +| DiscoveryService | **DiscoveryService** object used to discover mDNS services based on the specified **serviceType** and **Context**.| **Example** +FA model: + ```js +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); + let serviceType = "_print._tcp"; +let discoveryService = mdns.createDiscoveryService(context, serviceType); +``` + +Stage model: +```ts +// Obtain the context. +import UIAbility from '@ohos.app.ability.UIAbility'; +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + globalThis.context = this.context; + } +} +let context = globalThis.context; + +let serviceType = "_print._tcp"; let discoveryService = mdns.createDiscoveryService(context, serviceType); ``` @@ -267,7 +435,7 @@ Resolves an mDNS service. This API uses an asynchronous callback to return the r | Name | Type | Mandatory| Description | |-------------|----------------------------------|-----------|-------------------------------------------------------------| -| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-app-ability-uiAbility.md).| | serviceInfo | [LocalServiceInfo](#localserviceinfo) | Yes | mDNS service information. | | callback | AsyncCallback\<[LocalServiceInfo](#localserviceinfo)> | Yes | Callback used to return the result. If the operation is successful, **error** is **undefined** and **data** is the mDNS service information. | @@ -282,28 +450,65 @@ Resolves an mDNS service. This API uses an asynchronous callback to return the r | 2204006 | Request timeout. | | 2204010 | Send packet failed. | ->**NOTE** +> **NOTE** > For details about the error codes, see [mDNS Error Codes](../errorcodes/errorcode-net-mdns.md). **Example** +FA model: + ```js +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); + +let localServiceInfo = { + serviceType: "_print._tcp", + serviceName: "servicename", + port: 5555, + host: { + address: "10.14.**.***", + }, + serviceAttribute: [{ + key: "111", + value: [1] + }] +} + +mdns.resolveLocalService(context, localServiceInfo, function (error, data) { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +Stage model: + +```ts +// Obtain the context. +import UIAbility from '@ohos.app.ability.UIAbility'; +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + globalThis.context = this.context; + } +} +let context = globalThis.context; + let localServiceInfo = { - serviceType: "_print._tcp", - serviceName: "servicename", - port: 5555, - host: { - address: "10.14.**.***", - }, - serviceAttribute: [{ - key: "111", - value: [1] - }] + serviceType: "_print._tcp", + serviceName: "servicename", + port: 5555, + host: { + address: "10.14.**.***", + }, + serviceAttribute: [{ + key: "111", + value: [1] + }] } mdns.resolveLocalService(context, localServiceInfo, function (error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); }); ``` @@ -319,7 +524,7 @@ Resolves an mDNS service. This API uses a promise to return the result. | Name | Type | Mandatory| Description | |-------------|--------------|-----------|-----------------------------------------------------| -| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-app-ability-uiAbility.md).| | serviceInfo | [LocalServiceInfo](#localserviceinfo) | Yes | mDNS service information. | **Return value** @@ -339,30 +544,65 @@ Resolves an mDNS service. This API uses a promise to return the result. | 2204006 | Request timeout. | | 2204010 | Send packet failed. | ->**NOTE** +> **NOTE** > For details about the error codes, see [mDNS Error Codes](../errorcodes/errorcode-net-mdns.md). **Example** +FA model: + ```js +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); + let localServiceInfo = { - serviceType: "_print._tcp", - serviceName: "servicename", - port: 5555, - host: { - address: "10.14.**.***", - }, - serviceAttribute: [{ - key: "111", - value: [1] - }] + serviceType: "_print._tcp", + serviceName: "servicename", + port: 5555, + host: { + address: "10.14.**.***", + }, + serviceAttribute: [{ + key: "111", + value: [1] + }] } -mdns.resolveLocalService(context, localServiceInfo).then(function (data){ - console.log(JSON.stringify(data)); -}) +mdns.resolveLocalService(context, localServiceInfo).then(function (data) { + console.log(JSON.stringify(data)); +}); ``` +Stage model: + +```ts +// Obtain the context. +import UIAbility from '@ohos.app.ability.UIAbility'; +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + globalThis.context = this.context; + } +} +let context = globalThis.context; + +let localServiceInfo = { + serviceType: "_print._tcp", + serviceName: "servicename", + port: 5555, + host: { + address: "10.14.**.***", + }, + serviceAttribute: [{ + key: "111", + value: [1] + }] +} + +mdns.resolveLocalService(context, localServiceInfo).then(function (data) { + console.log(JSON.stringify(data)); +}); +``` ## DiscoveryService Defines a **DiscoveryService** object for discovering mDNS services of the specified type. @@ -377,7 +617,29 @@ Searches for mDNS services on the LAN. **Example** +FA model: + ```js +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); + +let discoveryService = mdns.createDiscoveryService(context, serviceType); +discoveryService.startSearchingMDNS(); +``` + +Stage model: + +```ts +// Obtain the context. +import UIAbility from '@ohos.app.ability.UIAbility'; +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + globalThis.context = this.context; + } +} +let context = globalThis.context; + let discoveryService = mdns.createDiscoveryService(context, serviceType); discoveryService.startSearchingMDNS(); ``` @@ -392,7 +654,29 @@ Stops searching for mDNS services on the LAN. **Example** +FA model: + ```js +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); + +let discoveryService = mdns.createDiscoveryService(context, serviceType); +discoveryService.stopSearchingMDNS(); +``` + +Stage model: + +```ts +// Obtain the context. +import UIAbility from '@ohos.app.ability.UIAbility'; +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + globalThis.context = this.context; + } +} +let context = globalThis.context; + let discoveryService = mdns.createDiscoveryService(context, serviceType); discoveryService.stopSearchingMDNS(); ``` @@ -420,7 +704,7 @@ let discoveryService = mdns.createDiscoveryService(context, serviceType); discoveryService.startSearchingMDNS(); discoveryService.on('discoveryStart', (data) => { - console.log(JSON.stringify(data)); + console.log(JSON.stringify(data)); }); discoveryService.stopSearchingMDNS(); @@ -449,7 +733,7 @@ let discoveryService = mdns.createDiscoveryService(context, serviceType); discoveryService.startSearchingMDNS(); discoveryService.on('discoveryStop', (data) => { - console.log(JSON.stringify(data)); + console.log(JSON.stringify(data)); }); discoveryService.stopSearchingMDNS(); @@ -457,7 +741,7 @@ discoveryService.stopSearchingMDNS(); ### on('serviceFound') -on(type: 'serviceFound', callback: Callback<[LocalServiceInfo](#localserviceinfo)>): void +on(type: 'serviceFound', callback: Callback\): void Enables listening for **serviceFound** events. @@ -478,7 +762,7 @@ let discoveryService = mdns.createDiscoveryService(context, serviceType); discoveryService.startSearchingMDNS(); discoveryService.on('serviceFound', (data) => { - console.log(JSON.stringify(data)); + console.log(JSON.stringify(data)); }); discoveryService.stopSearchingMDNS(); @@ -486,7 +770,7 @@ discoveryService.stopSearchingMDNS(); ### on('serviceLost') -on(type: 'serviceLost', callback: Callback<[LocalServiceInfo](#localserviceinfo)>): void +on(type: 'serviceLost', callback: Callback\): void Enables listening for **serviceLost** events. @@ -507,7 +791,7 @@ let discoveryService = mdns.createDiscoveryService(context, serviceType); discoveryService.startSearchingMDNS(); discoveryService.on('serviceLost', (data) => { - console.log(JSON.stringify(data)); + console.log(JSON.stringify(data)); }); discoveryService.stopSearchingMDNS(); @@ -546,6 +830,6 @@ Defines the mDNS error information. | Name | Value | Description | | --------------- | ---- | ----------- | -| INTERNAL_ERROR | 0 | Operation failed because of an internal error. | -| ALREADY_ACTIVE | 1 | Operation failed because the service already exists.| +| INTERNAL_ERROR | 0 | Operation failed because of an internal error. (not supported currently) | +| ALREADY_ACTIVE | 1 | Operation failed because the service already exists. (not supported currently)| | MAX_LIMIT | 2 | Operation failed because the number of requests exceeds the maximum value. (not supported currently)| diff --git a/en/application-dev/reference/apis/js-apis-net-policy.md b/en/application-dev/reference/apis/js-apis-net-policy.md index 375ee31e24b9a24d14aae0217f12b8cd78eb57b1..a945b1516a40c6ab43f6586c5f70bff40d75d52d 100644 --- a/en/application-dev/reference/apis/js-apis-net-policy.md +++ b/en/application-dev/reference/apis/js-apis-net-policy.md @@ -43,10 +43,12 @@ Sets a background network policy. This API uses an asynchronous callback to retu ```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 @@ Sets a background network policy. This API uses a promise to return the result. **Example** ```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 @@ Obtains the background network policy. This API uses an asynchronous callback to ```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 @@ Obtains the background network policy. This API uses a promise to return the res **Example** ```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 @@ Sets an application-specific network policy. This API uses an asynchronous callb ```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 @@ Sets an application-specific network policy. This API uses a promise to return t ```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 @@ Obtains an application-specific network policy by **uid**. This API uses an asyn ```js policy.getPolicyByUid(Number.parseInt(this.firstParam), (error, data) => { - this.callBack(error, data); + this.callBack(error, data); }); ``` @@ -313,9 +315,9 @@ Obtains an application-specific network policy by **uid**. This API uses a promi **Example** ```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 @@ Obtains the UID array of applications configured with a certain application-spec ```js policy.getUidsByPolicy(Number.parseInt(this.currentNetUidPolicy), (error, data) => { - this.callBack(error, data); + this.callBack(error, data); }); ``` @@ -390,9 +392,9 @@ Obtains the UID array of applications configured with a certain application-spec **Example** ```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 @@ Obtains the network quota policies. This API uses an asynchronous callback to re ```js policy.getNetQuotaPolicies((error, data) => { - this.callBack(error, data); + this.callBack(error, data); }); ``` @@ -456,9 +458,9 @@ Obtains the network quota policies. This API uses a promise to return the result **Example** ```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 @@ Sets an array of network quota policies. This API uses an asynchronous callback **Example** ```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 @@ Sets an array of network quota policies. This API uses a promise to return the r **Example** ```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 @@ Restores all the policies (cellular network, background network, firewall, and a ```js this.firstParam = iccid; policy.restoreAllPolicies(this.firstParam, (error, data) => { - this.callBack(error, data); + this.callBack(error, data); }); ``` @@ -619,9 +641,9 @@ Restores all the policies (cellular network, background network, firewall, and a ```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 @@ Checks whether an application is allowed to access metered networks. This API us ```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)), (error, data) => { - this.callBack(error, data); + this.callBack(error, data); }); ``` @@ -704,11 +726,11 @@ Checks whether an application is allowed to access metered networks. This API us ```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 @@ Checks whether an application is allowed to access the given network. This API u ```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 @@ Checks whether an application is allowed to access the given network. This API u ```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 @@ Sets whether to add an application to the device idle allowlist. This API uses a ```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 @@ Sets whether to add an application to the device idle allowlist. This API uses a ```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 @@ Obtains the UID array of applications that are on the device idle allowlist. Thi ```js policy.getDeviceIdleAllowList((error, data) => { - this.callBack(error, data); + this.callBack(error, data); }); ``` @@ -943,9 +965,9 @@ Obtains the UID array of applications that are on the device idle allowlist. Thi **Example** ```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 @@ Obtains the background network policies configured for the given application. Th ```js this.firstParam = uid policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam), (error, data) => { - this.callBack(error, data); + this.callBack(error, data); }); ``` @@ -1021,9 +1043,9 @@ Obtains the background network policies configured for the given application. Th ```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 @@ Restores all the policies (cellular network, background network, firewall, and a ```js this.firstParam = iccid policy.resetPolicies(this.firstParam, (error, data) => { - this.callBack(error, data); + this.callBack(error, data); }); ``` @@ -1098,13 +1120,13 @@ Restores all the policies (cellular network, background network, firewall, and a **Example** ```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 @@ Updates a reminder policy. This API uses an asynchronous callback to return the ```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 @@ Updates a reminder policy. This API uses a promise to return the result. ```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 @@ Sets whether to add an application to the power-saving allowlist. This API uses ```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 @@ Sets whether to add an application to the power-saving allowlist. This API uses ```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 @@ Obtains the UID array of applications that are on the power-saving allowlist. Th ```js policy.getPowerSaveAllowList((error, data) => { - this.callBack(error, data); + this.callBack(error, data); }); ``` @@ -1340,9 +1362,9 @@ Obtains the UID array of applications that are on the device idle allowlist. Thi **Example** ```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 @@ Subscribes to policy changes. This API uses an asynchronous callback to return t ```js policy.on('netUidPolicyChange', (data) => { - this.log('on netUidPolicyChange: ' + JSON.stringify(data)); + this.log('on netUidPolicyChange: ' + JSON.stringify(data)); }) ``` @@ -1396,7 +1418,7 @@ Subscribes to rule changes. This API uses an asynchronous callback to return the ```js policy.on('netUidRuleChange', (data) => { - this.log('on netUidRuleChange: ' + JSON.stringify(data)); + this.log('on netUidRuleChange: ' + JSON.stringify(data)); }) ``` @@ -1421,7 +1443,7 @@ Subscribes to metered **iface** changes. This API uses an asynchronous callback ```js policy.on('netMeteredIfacesChange', (data) => { - this.log('on netMeteredIfacesChange: ' + JSON.stringify(data)); + this.log('on netMeteredIfacesChange: ' + JSON.stringify(data)); }) ``` @@ -1446,7 +1468,7 @@ Subscribes to network quota policy changes. This API uses an asynchronous callba ```js policy.on('netQuotaPolicyChange', (data) => { - this.log('on netQuotaPolicyChange: ' + JSON.stringify(data)); + this.log('on netQuotaPolicyChange: ' + JSON.stringify(data)); }) ``` @@ -1471,7 +1493,7 @@ Subscribes to background network policy changes. This API uses an asynchronous c ```js policy.on('netBackgroundPolicyChange', (data) => { - this.log('on netBackgroundPolicyChange: ' + JSON.stringify(data)); + this.log('on netBackgroundPolicyChange: ' + JSON.stringify(data)); }) ``` @@ -1540,10 +1562,10 @@ Enumerates the reminder types. **System capability**: SystemCapability.Communication.NetManager.Core -| Name | Value| Description | +| Name| Value| Description| | ---------------------- | - | ------- | -| REMIND_TYPE_WARNING | 1 | Warning.| -| REMIND_TYPE_LIMIT | 2 | Limit.| +| REMIND_TYPE_WARNING | 1 | Warning.| +| REMIND_TYPE_LIMIT | 2 | Limit.| ## NetUidPolicy diff --git a/en/application-dev/reference/apis/js-apis-net-sharing.md b/en/application-dev/reference/apis/js-apis-net-sharing.md index f4682131182b59d9b54c26978ec780cd738172ef..0cda70aa2939c0da8f5aec7875d75bb48d309120 100644 --- a/en/application-dev/reference/apis/js-apis-net-sharing.md +++ b/en/application-dev/reference/apis/js-apis-net-sharing.md @@ -43,8 +43,8 @@ Checks whether network sharing is supported. This API uses an asynchronous callb ```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 @@ Checks whether network sharing is supported. This API uses a promise to return t ```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 @@ Checks whether network sharing is in progress. This API uses an asynchronous cal ```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 @@ Checks whether network sharing is in progress. This API uses a promise to return ```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 @@ Starts network sharing of a specified type. This API uses an asynchronous callba ```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 @@ Starts network sharing of a specified type. This API uses a promise to return th ```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 @@ Stops network sharing of a specified type. This API uses an asynchronous callbac ```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 @@ Stops network sharing of a specified type. This API uses a promise to return the ```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 @@ Obtains the volume of mobile data traffic received via network sharing. This API ```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 @@ Obtains the volume of mobile data traffic received via network sharing. This API ```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 @@ Obtains the volume of mobile data traffic sent via network sharing. This API use ```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 @@ Obtains the volume of mobile data traffic sent via network sharing. This API use ```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 @@ Obtains the volume of mobile data traffic sent and received via network sharing. ```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 @@ Obtains the volume of mobile data traffic sent and received via network sharing. ```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 @@ Obtains the names of NICs in the specified network sharing state. This API uses ```js import SharingIfaceState from '@ohos.net.sharing' -let SHARING_BLUETOOTH=2; + +let SHARING_BLUETOOTH = 2; sharing.getSharingIfaces(SHARING_BLUETOOTH, (error, data) => { - console.log(JSON.stringify(error)); - console.log(JSON.stringify(data)); + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); }); ``` @@ -633,11 +638,12 @@ Obtains the names of NICs in the specified network sharing state. This API uses ```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 @@ Obtains the network sharing state of the specified type. This API uses an asynch ```js import SharingIfaceType from '@ohos.net.sharing' -let SHARING_WIFI=0; + +let SHARING_WIFI = 0; sharing.getSharingState(SHARING_WIFI, (error, data) => { - console.log(JSON.stringify(error)); - console.log(JSON.stringify(data)); + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); }); ``` @@ -719,11 +726,12 @@ Obtains the network sharing state of the specified type. This API uses a 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 @@ Obtains regular expressions of NICs of a specified type. This API uses an asynch ```js import SharingIfaceType from '@ohos.net.sharing' -let SHARING_WIFI=0; + +let SHARING_WIFI = 0; sharing.getSharableRegexes(SHARING_WIFI, (error, data) => { - console.log(JSON.stringify(error)); - console.log(JSON.stringify(data)); + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); }); ``` @@ -805,11 +814,12 @@ Obtains regular expressions of NICs of a specified type. This API uses a 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 @@ Subscribes to network sharing state changes. This API uses an asynchronous callb **Example** ```js - sharing.on('sharingStateChange', (data) => { - console.log('on sharingStateChange: ' + JSON.stringify(data)); +sharing.on('sharingStateChange', (data) => { + console.log('on sharingStateChange: ' + JSON.stringify(data)); }); ``` @@ -877,13 +887,14 @@ Unsubscribes from network sharing state changes. This API uses an asynchronous c ```js sharing.off('sharingStateChange', (data) => { - console.log(JSON.stringify(data)); + console.log(JSON.stringify(data)); }); ``` ## sharing.on('interfaceSharingStateChange') -on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void +on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIfaceType, iface: string, state: +SharingIfaceState }>): void Subscribes to network sharing state changes of a specified NIC. This API uses an asynchronous callback to return the result. @@ -910,14 +921,15 @@ Subscribes to network sharing state changes of a specified NIC. This API uses an **Example** ```js - sharing.on('interfaceSharingStateChange', (data) => { - console.log('on interfaceSharingStateChange: ' + JSON.stringify(data)); +sharing.on('interfaceSharingStateChange', (data) => { + console.log('on interfaceSharingStateChange:' + JSON.stringify(data)); }); ``` ## sharing.off('interfaceSharingStateChange') -off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void +off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfaceType, iface: string, state: +SharingIfaceState }>): void Unsubscribes from network sharing status changes of a specified NIC. This API uses an asynchronous callback to return the result. @@ -945,7 +957,7 @@ Unsubscribes from network sharing status changes of a specified NIC. This API us ```js sharing.off('interfaceSharingStateChange', (data) => { - console.log(JSON.stringify(data)); + console.log(JSON.stringify(data)); }); ``` @@ -978,8 +990,8 @@ Subscribes to upstream network changes. This API uses an asynchronous callback t **Example** ```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 +1025,7 @@ Unsubscribes from upstream network changes. This API uses an asynchronous callba ```js sharing.off('sharingUpstreamChange', (data) => { - console.log(JSON.stringify(data)); + console.log(JSON.stringify(data)); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-socket.md b/en/application-dev/reference/apis/js-apis-socket.md index d60b3e4eaf6245634140ba6c217bb3d97eb2ac25..9209f82aa03cab5df8afe6384cd3b48e0730f1c3 100644 --- a/en/application-dev/reference/apis/js-apis-socket.md +++ b/en/application-dev/reference/apis/js-apis-socket.md @@ -26,14 +26,12 @@ Creates a **UDPSocket** object. | :--------------------------------- | :---------------------- | | [UDPSocket](#udpsocket) | **UDPSocket** object.| - **Example** ```js let udp = socket.constructUDPSocketInstance(); ``` - ## UDPSocket Defines a **UDPSocket** connection. Before invoking UDPSocket APIs, you need to call [socket.constructUDPSocketInstance](#socketconstructudpsocketinstance) to create a **UDPSocket** object. @@ -68,14 +66,13 @@ Binds the IP address and port number. The port number can be specified or random 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 @@ Binds the IP address and port number. The port number can be specified or random ```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 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p ```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 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p ```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 @@ Closes a UDPSocket connection. This API uses an asynchronous callback to return 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 Obtains the status of the UDPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE** ->This API can be called only after **bind** is successfully called. +> **NOTE** +> This API can be called only after **bind** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -306,29 +298,28 @@ Obtains the status of the UDPSocket connection. This API uses an asynchronous ca 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\ Obtains the status of the UDPSocket connection. This API uses a promise to return the result. ->**NOTE** ->This API can be called only after **bind** is successfully called. +> **NOTE** +> This API can be called only after **bind** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -344,30 +335,30 @@ Obtains the status of the UDPSocket connection. This API uses a promise to retur ```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 Sets other attributes of the UDPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE** ->This API can be called only after **bind** is successfully called. +> **NOTE** +> This API can be called only after **bind** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -391,37 +382,36 @@ Sets other attributes of the UDPSocket connection. This API uses an asynchronous ```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\ Sets other attributes of the UDPSocket connection. This API uses a promise to return the result. ->**NOTE** ->This API can be called only after **bind** is successfully called. +> **NOTE** +> This API can be called only after **bind** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -450,27 +440,26 @@ Sets other attributes of the UDPSocket connection. This API uses a promise to re ```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 @@ Enables listening for message receiving events of the UDPSocket connection. This ```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 Disables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE** ->You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. +> **NOTE** +> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -518,8 +506,8 @@ Disables listening for message receiving events of the UDPSocket connection. Thi ```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); // You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. @@ -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 @@ Enables listening for data packet message events or close events of the UDPSocke ```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 Disables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE** ->You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. +> **NOTE** +> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -578,15 +564,15 @@ Disables listening for data packet message events or close events of the UDPSock ```js let udp = socket.constructUDPSocketInstance(); -let callback1 = () =>{ - console.log("on listening, success"); +let callback1 = () => { + console.log("on listening, success"); } udp.on('listening', callback1); // You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. 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); // You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. @@ -594,7 +580,6 @@ udp.off('close', callback2); udp.off('close'); ``` - ### on('error') on(type: 'error', callback: ErrorCallback): void @@ -615,19 +600,18 @@ Enables listening for error events of the UDPSocket connection. This API uses an ```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 Disables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE** ->You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. +> **NOTE** +> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -642,8 +626,8 @@ Disables listening for error events of the UDPSocket connection. This API uses a ```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); // You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. @@ -651,7 +635,6 @@ udp.off('error', callback); udp.off('error'); ``` - ## NetAddress Defines the destination address. @@ -730,9 +713,9 @@ Creates a **TCPSocket** object. **Return value** - | Type | Description | +| Type | Description | | :--------------------------------- | :---------------------- | - | [TCPSocket](#tcpsocket) | **TCPSocket** object.| +| [TCPSocket](#tcpsocket) | **TCPSocket** object.| **Example** @@ -740,7 +723,6 @@ Creates a **TCPSocket** object. let tcp = socket.constructTCPSocketInstance(); ``` - ## TCPSocket Defines a TCPSocket connection. Before invoking TCPSocket APIs, you need to call [socket.constructTCPSocketInstance](#socketconstructtcpsocketinstance) to create a **TCPSocket** object. @@ -775,14 +757,13 @@ Binds the IP address and port number. The port number can be specified or random 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 Sets up a connection to the specified IP address and port number. This API uses an asynchronous callback to return the result. ->**NOTE** ->This API can be called only after **bind** is successfully called. +> **NOTE** +> This API can be called only after **bind** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -856,16 +836,15 @@ Sets up a connection to the specified IP address and port number. This API uses ```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 @@ Sets up a connection to the specified IP address and port number. This API uses ```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 Sends data over a TCPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE** ->This API can be called only after **connect** is successfully called. +> **NOTE** +> This API can be called only after **connect** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -939,32 +917,29 @@ Sends data over a TCPSocket connection. This API uses an asynchronous callback t ```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 is omitted here. The UTF-8 encoding format is used by default. + }, err => { + if (err) { + console.log('send fail'); + return; + } + console.log('send success'); }) -}).catch(err => { - console.log('connect fail'); -}); +}) ``` - ### send send(options: TCPSendOptions): Promise\ Sends data over a TCPSocket connection. This API uses a promise to return the result. ->**NOTE** ->This API can be called only after **connect** is successfully called. +> **NOTE** +> This API can be called only after **connect** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -993,23 +968,22 @@ Sends data over a TCPSocket connection. This API uses a promise to return the re ```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 @@ Closes a TCPSocket connection. This API uses an asynchronous callback to return 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 Obtains the remote address of a socket connection. This API uses an asynchronous callback to return the result. ->**NOTE** ->This API can be called only after **connect** is successfully called. +> **NOTE** +> This API can be called only after **connect** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -1110,30 +1082,26 @@ Obtains the remote address of a socket connection. This API uses an asynchronous ```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\ Obtains the remote address of a socket connection. This API uses a promise to return the result. ->**NOTE** ->This API can be called only after **connect** is successfully called. +> **NOTE** +> This API can be called only after **connect** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -1155,29 +1123,28 @@ Obtains the remote address of a socket connection. This API uses a promise to re ```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 Obtains the status of the TCPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE** ->This API can be called only after **bind** or **connect** is successfully called. +> **NOTE** +> This API can be called only after **bind** or **connect** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -1199,30 +1166,26 @@ Obtains the status of the TCPSocket connection. This API uses an asynchronous ca ```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\ Obtains the status of the TCPSocket connection. This API uses a promise to return the result. ->**NOTE** ->This API can be called only after **bind** or **connect** is successfully called. +> **NOTE** +> This API can be called only after **bind** or **connect** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -1244,29 +1207,28 @@ Obtains the status of the TCPSocket connection. This API uses a promise to retur ```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 Sets other properties of the TCPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE** ->This API can be called only after **bind** or **connect** is successfully called. +> **NOTE** +> This API can be called only after **bind** or **connect** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -1290,39 +1252,35 @@ Sets other properties of the TCPSocket connection. This API uses an asynchronous ```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\ Sets other properties of the TCPSocket connection. This API uses a promise to return the result. ->**NOTE** ->This API can be called only after **bind** or **connect** is successfully called. +> **NOTE** +> This API can be called only after **bind** or **connect** is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -1351,30 +1309,29 @@ Sets other properties of the TCPSocket connection. This API uses a promise to re ```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 @@ Enables listening for message receiving events of the TCPSocket connection. This ```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 Disables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE** ->You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. +> **NOTE** +> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -1422,8 +1378,8 @@ Disables listening for message receiving events of the TCPSocket connection. Thi ```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); // You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. @@ -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 @@ Enables listening for connection or close events of the TCPSocket connection. Th ```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 Disables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE** ->You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. +> **NOTE** +> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -1482,15 +1436,15 @@ Disables listening for connection or close events of the TCPSocket connection. T ```js let tcp = socket.constructTCPSocketInstance(); -let callback1 = () =>{ - console.log("on connect success"); +let callback1 = () => { + console.log("on connect success"); } tcp.on('connect', callback1); // You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. 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); // You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. @@ -1498,7 +1452,6 @@ tcp.off('close', callback2); tcp.off('close'); ``` - ### on('error') on(type: 'error', callback: ErrorCallback): void @@ -1519,19 +1472,18 @@ Enables listening for error events of the TCPSocket connection. This API uses an ```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 Disables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE** ->You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. +> **NOTE** +> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -1546,8 +1498,8 @@ Disables listening for error events of the TCPSocket connection. This API uses a ```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); // You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. @@ -1555,7 +1507,6 @@ tcp.off('error', callback); tcp.off('error'); ``` - ## TCPConnectOptions Defines TCPSocket connection parameters. @@ -1769,12 +1720,11 @@ Obtains the status of the TLSSocket connection. This API uses a promise to retur **Example** ```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 @@ Sends a message to the server after a TLSSocket connection is established. This **Example** ```js -tls.send("xxxx").then(() =>{ +tls.send("xxxx").then(() => { console.log("send success"); }).catch(err => { console.error(err); @@ -2619,7 +2570,7 @@ Closes a TLSSocket connection. This API uses a promise to return the result. **Example** ```js -tls.close().then(() =>{ +tls.close().then(() => { console.log("close success"); }).catch(err => { console.error(err); diff --git a/en/application-dev/reference/apis/js-apis-webSocket.md b/en/application-dev/reference/apis/js-apis-webSocket.md index bd7a55c09324684d80e787174483fcc8aefd884e..dba171b9da058a60c3dde3b4c96e9476b27dba77 100644 --- a/en/application-dev/reference/apis/js-apis-webSocket.md +++ b/en/application-dev/reference/apis/js-apis-webSocket.md @@ -5,11 +5,12 @@ > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. -You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the [createWebSocket](#websocketcreatewebsocket) API to create a [WebSocket](#websocket) object and then use the [connect](#connect) API to connect to the server. If the connection is successful, the client will receive a callback of the [open](#onopen) event. Then, the client can communicate with the server using the [send](#send) API. When the server sends a message to the client, the client will receive a callback of the [message](#onmessage) event. If the client no longer needs this connection, it can call the [close](#close) API to disconnect from the server. Then, the client will receive a callback of the [close](#onclose) event. +You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the [createWebSocket](#websocketcreatewebsocket) API to create a [WebSocket](#websocket) object and then use the [connect](#connect) API to connect to the server. +If the connection is successful, the client will receive a callback of the [open](#onopen) event. Then, the client can communicate with the server using the [send](#send) API. +When the server sends a message to the client, the client will receive a callback of the [message](#onmessage) event. If the client no longer needs this connection, it can call the [close](#close) API to disconnect from the server. Then, the client will receive a callback of the [close](#onclose) event. If an error occurs in any of the preceding processes, the client will receive a callback of the [error](#onerror) event. - ## Modules to Import ```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']); - // When receiving the on('open') event, the client can use the send() API to communicate with the server. - 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']); + // When receiving the on('open') event, the client can use the send() API to communicate with the server. + 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); - // When receiving the `bye` message (the actual message name may differ) from the server, the client proactively disconnects from the server. - 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); + // When receiving the `bye` message (the actual message name may differ) from the server, the client proactively disconnects from the server. + 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 @@ Creates a WebSocket connection. You can use this API to create or close a WebSoc let ws = webSocket.createWebSocket(); ``` - ## WebSocket Defines a **WebSocket** object. Before invoking WebSocket APIs, you need to call [webSocket.createWebSocket](#websocketcreatewebsocket) to create a **WebSocket** object. @@ -93,6 +97,9 @@ connect(url: string, callback: AsyncCallback\): void Initiates a WebSocket request to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result. +> **NOTE** +> You can listen to **error** events to obtain the operation result. If an error occurs, the error code 200 will be returned. + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -117,21 +124,23 @@ Initiates a WebSocket request to establish a WebSocket connection to a given URL 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 Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result. +> **NOTE** +> You can listen to **error** events to obtain the operation result. If an error occurs, the error code 200 will be returned. + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -157,26 +166,28 @@ Initiates a WebSocket request carrying specified options to establish a WebSocke 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\ Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses a promise to return the result. +> **NOTE** +> You can listen to **error** events to obtain the operation result. If an error occurs, the error code 200 will be returned. + **Required permissions**: ohos.permission.INTERNET **System capability**: 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 @@ Sends data through a WebSocket connection. This API uses an asynchronous callbac 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 @@ Sends data through a WebSocket connection. This API uses a promise to return the 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 @@ Closes a WebSocket connection. This API uses an asynchronous callback to return ```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 @@ Closes a WebSocket connection carrying specified options such as **code** and ** ```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 @@ Closes a WebSocket connection carrying specified options such as **code** and ** ```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 @@ Enables listening for the **open** events of a WebSocket connection. This API us | type | string | Yes | Event type.
**open**: event indicating that a WebSocket connection has been opened.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | - **Example** ```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 Disables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE** ->You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. +> **NOTE** +> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -476,22 +476,21 @@ Disables listening for the **open** events of a WebSocket connection. This API u ```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); // You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. ws.off('open', callback1); ``` - ### on('message') on(type: 'message', callback: AsyncCallback\): void Enables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented. ->**NOTE** ->The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8). +> **NOTE** +> The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8). **System capability**: SystemCapability.Communication.NetStack @@ -507,20 +506,19 @@ Enables listening for the **message** events of a WebSocket connection. This API ```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 Disables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented. ->**NOTE** ->The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8). ->You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. +> **NOTE** +> The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8). +> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: 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 @@ Enables listening for the **close** events of a WebSocket connection. This API u ```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 Disables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE** ->You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. +> **NOTE** +> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: 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 @@ Enables listening for the **error** events of a WebSocket connection. This API u | Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ------------------------------- | | type | string | Yes | Event type.
**error**: event indicating the WebSocket connection has encountered an error.| -| callback | ErrorCallback | Yes | Callback used to return the result. | +| callback | ErrorCallback | Yes | Callback used to return the result.
Common error code: 200| **Example** ```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 Disables listening for the **error** events of a WebSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE** ->You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. +> **NOTE** +> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -640,7 +634,6 @@ let ws = webSocket.createWebSocket(); ws.off('error'); ``` - ## WebSocketRequestOptions Defines the optional parameters carried in the request for establishing a WebSocket connection. @@ -651,7 +644,6 @@ Defines the optional parameters carried in the request for establishing a WebSoc | ------ | ------ | ---- | ------------------------------------------------------------ | | header | Object | No | Header carrying optional parameters in the request for establishing a WebSocket connection. You can customize the parameter or leave it unspecified.| - ## WebSocketCloseOptions Defines the optional parameters carried in the request for closing a WebSocket connection. diff --git a/en/device-dev/subsystems/Readme-EN.md b/en/device-dev/subsystems/Readme-EN.md index dd126793581313bbd9f809d19ff8dbcee9bf88e0..4e26f45a16441f8b589b351b9ca1b5a451954246 100644 --- a/en/device-dev/subsystems/Readme-EN.md +++ b/en/device-dev/subsystems/Readme-EN.md @@ -119,4 +119,6 @@ - [Thermal Level Customization](subsys-thermal_level.md) - [Thermal Log Customization](subsys-thermal_log.md) - [Thermal Policy Customization](subsys-thermal_policy.md) - - [Thermal Scene Customization](subsys-thermal_scene.md) \ No newline at end of file + - [Thermal Scene Customization](subsys-thermal_scene.md) + - Power Management + - [Power Mode Customization](subsys-power-mode-customization.md) \ No newline at end of file diff --git a/en/device-dev/subsystems/subsys-power-mode-customization.md b/en/device-dev/subsystems/subsys-power-mode-customization.md new file mode 100644 index 0000000000000000000000000000000000000000..093d13bf1d1526a1d1be67790dd7043f1f8fad92 --- /dev/null +++ b/en/device-dev/subsystems/subsys-power-mode-customization.md @@ -0,0 +1,285 @@ +# Power Mode Customization + +## Overview + +### Introduction + +By default, OpenHarmony provides the power mode feature, which offers the following options: normal mode, performance mode, power-saving mode, and ultra power-saving mode. However, the power mode configuration varies according to hardware specifications of different products. To address this issue, OpenHarmony provides the power mode customization function, allowing you to customize power modes depending on your hardware specifications. + +### Basic Concepts + +OpenHarmony supports the following four power modes, each of which corresponds to the specified power and performance policy. + +- Normal mode: default power mode, in which the system brightness, screen-off time, and sleep time meet the requirements of most users. + +- Performance mode: power mode that emphasizes on the performance, such as increasing the system brightness, disabling the screen-off time, and preventing the system from entering the sleep mode. + +- Power-saving mode: power mode that emphasizes on power saving, such as decreasing the system brightness, reducing the screen-off time, and shortening the time for entering sleep mode. + +- Ultra power-saving mode: power mode that emphasizes on ultimate power saving, such as greatly decreasing the system brightness, greatly reducing the screen-off time, and greatly shortening the time for entering sleep mode. + + +### Constraints + +The configuration path for battery level customization is subject to the [configuration policy](https://gitee.com/openharmony/customization_config_policy). In this development guide, `/vendor` is used as an example of the configuration path. During actual development, you need to modify the customization path based on the product configuration policy. + +## How to Develop + +### Setting Up the Environment + +**Hardware requirements:** + +Development board running the standard system, for example, the DAYU200 or Hi3516D V300 open source suite. + +**Environment requirements:** + +For details about the requirements on the Linux environment, see [Quick Start](../quick-start/quickstart-overview.md). + +### Getting Started with Development + +The following uses [DAYU200](https://gitee.com/openharmony/vendor_hihope/tree/master/rk3568) as an example to illustrate power mode customization. + +1. Create the `power_manager` folder in the product directory [vendor/hihope/rk3568](https://gitee.com/openharmony/vendor_hihope/tree/master/rk3568). + +2. Create a target folder by referring to the [default power mode configuration folder](https://gitee.com/openharmony/powermgr_power_manager/tree/master/services/native/profile), and install it in `//vendor/hihope/rk3568/power_manager`. The content is as follows: + + ```text + profile + ├── BUILD.gn + ├── power_mode_config.xml + ``` + +3. Write the custom `power_mode_config.xml` file by referring to the [power_mode_config.xml](https://gitee.com/openharmony/powermgr_power_manager/blob/master/services/native/profile/power_mode_config.xml) file in the default power mode configuration folder. + + The **proxy** node is used to configure the power mode. + + **Table 1** Description of the proxy node + | Power Mode| ID | + | :------ | --- | + | Normal mode| 600 | + | Power-saving mode| 601 | + | Performance mode| 602 | + | Ultra power-saving mode| 603 | + + The **switch** node is used to configure items of the power mode. + + **Table 2** Description of the **switch** node + | Configuration Item| ID | Value Range| + | :------ | ----- | ----- | + | Screen-off time| 101 | **value** indicates the screen-off duration, in unit of ms. It is an integer greater than or equal to **-1**. The value **-1** indicates that the screen-off function is disabled.| + | Auto sleep time| 102 | **value** indicates the time for automatically entering the sleep mode, in unit of ms. It is an integer greater than or equal to **-1**. The value **-1** indicates that the auto sleep function is disabled. | + | Automatic brightness adjustment| 103 | **value** indicates whether to enable automatic brightness adjustment. The options are as follows:
- **-1**: disable automatic brightness adjustment.
- **1**: enable automatic brightness adjustment.| + | Automatic screen rotation| 107 | **value** indicates whether to enable automatic screen rotation. The options are as follows:
- **-1**: disable automatic screen rotation.
- **1**: enable automatic screen rotation.| + | System brightness| 115 | **value** indicates the screen brightness. It is an integer ranging from 0 to 255.| + | Vibration switch| 120 | **value** indicates whether to enable vibration. The options are as follows:
- **-1**: disable vibration.
- **1**: enable vibration.| + + The following uses the normal mode as an example: + + ```xml + + + + + + + + + + ``` + +4. Write the `BUILD.gn` file by referring to the [BUILD.gn](https://gitee.com/openharmony/powermgr_power_manager/blob/master/services/native/profile/BUILD.gn) file in the default power mode configuration folder to pack the `power_mode_config.xml` file to the `/vendor/etc/power_config` directory. The configuration is as follows: + + ```shell + import("//base/powermgr/power_manager/powermgr.gni") + import("//build/ohos.gni") + + ## Install vendor power_mode_config.xml to /vendor/etc/power_config/power_mode_config.xml + ohos_prebuilt_etc("power_mode_config_vendor") { # custom name, for example, power_mode_config_vendor. + source = "power_mode_config.xml" + relative_install_dir = "power_config" + install_images = [ chipset_base_dir ] # Required configuration for installing the power_mode_config.xml file in the vendor directory, where chipset_base_dir = "vendor". If this field is left unspecified, the power_mode_config.xml file is installed in the system directory by default. + part_name = "${product_rk3568}" # Set part_name to product_rk3568 for subsequent build. + } + + group("power_service_config") { + deps = [ ":power_mode_config_vendor" ] + } + + ``` + +5. Add the build target to `module_list` in [ohos.build](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/ohos.build) in the `/vendor/hihope/rk3568` directory. For example: + + ```json + { + "parts": { + "product_rk3568": { + "module_list": [ + "//vendor/hihope/rk3568/default_app_config:default_app_config", + "//vendor/hihope/rk3568/image_conf:custom_image_conf", + "//vendor/hihope/rk3568/power_manager/profile:power_mode_config_vendor", # Add the configuration for building of power_mode_config_vendor. + "//vendor/hihope/rk3568/preinstall-config:preinstall-config", + "//vendor/hihope/rk3568/resourceschedule:resourceschedule", + "//vendor/hihope/rk3568/etc:product_etc_conf" + ] + } + }, + "subsystem": "product_hihope" + } + ``` + + +6. Build the customized version by referring to [Quick Start](../quick-start/quickstart-overview.md). + + ```shell + ./build.sh --product-name rk3568 --ccache + ``` + +7. Burn the customized version to the DAYU200 development board. + +### Debugging and Verification + +1. After startup, run the following command to launch the shell command line: + + ```shell + hdc shell + ``` + +2. Set the power mode to the normal mode, and verify the setting. + + 1. Set the power mode to the normal mode. + + ```shell + power-shell setmode 600 + ``` + + 2. Check whether the setting of the power mode is successful. + + ```shell + Set Mode: 600 + Set Mode Success! + + ``` + 3. Obtain the auto sleep time. + + ```shell + hidumper -s 3301 -a -a + + -------------------------------[ability]------------------------------- + + + ----------------------------------PowerManagerService--------------------------------- + POWER STATE DUMP: + Current State: INACTIVE Reason: 1 Time: 33227 + ScreenOffTime: Timeout=10000ms + ··· (Only the auto sleep time configuration is displayed here. Other information is omitted.) + + ``` + + 4. Turn on the screen. If the screen turns off after 10 seconds, the setting of the auto sleep time is successful. + +3. Set the power mode to the power-saving mode, and verify the setting. + + 1. Set the power mode to the power-saving mode. + + ```shell + power-shell setmode 601 + ``` + + 2. Check whether the setting of the power mode is successful. + + ```shell + Set Mode: 601 + Set Mode Success! + + ``` + 3. Obtain the auto sleep time. + + ```shell + hidumper -s 3301 -a -a + + -------------------------------[ability]------------------------------- + + + ----------------------------------PowerManagerService--------------------------------- + POWER STATE DUMP: + Current State: INACTIVE Reason: 1 Time: 33227 + ScreenOffTime: Timeout=20000ms + ··· (Only the auto sleep time configuration is displayed here. Other information is omitted.) + + ``` + + 4. Turn on the screen. If the screen turns off after 20 seconds, the setting of the auto sleep time is successful. + +4. Set the power mode to the performance mode, and verify the setting. + + 1. Set the power mode to the performance mode. + + ```shell + power-shell setmode 602 + ``` + + 2. Check whether the setting of the power mode is successful. + + ```shell + Set Mode: 602 + Set Mode Success! + + ``` + 3. Obtain the auto sleep time. + + ```shell + hidumper -s 3301 -a -a + + -------------------------------[ability]------------------------------- + + + ----------------------------------PowerManagerService--------------------------------- + POWER STATE DUMP: + Current State: INACTIVE Reason: 1 Time: 33227 + ScreenOffTime: Timeout=30000ms + ··· (Only the auto sleep time configuration is displayed here. Other information is omitted.) + + ``` + + 4. Turn on the screen. If the screen turns off after 30 seconds, the setting of the auto sleep time is successful. + +5. Set the power mode to the ultra power-saving mode, and verify the setting. + + 1. Set the power mode to the ultra power-saving mode. + + ```shell + power-shell setmode 603 + ``` + + 2. Check whether the setting of the power mode is successful. + + ```shell + Set Mode: 603 + Set Mode Success! + + ``` + 3. Obtain the auto sleep time. + + ```shell + hidumper -s 3301 -a -a + + -------------------------------[ability]------------------------------- + + + ----------------------------------PowerManagerService--------------------------------- + POWER STATE DUMP: + Current State: INACTIVE Reason: 1 Time: 33227 + ScreenOffTime: Timeout=40000ms + ··· (Only the auto sleep time configuration is displayed here. Other information is omitted.) + + ``` + + 4. Turn on the screen. If the screen turns off after 40 seconds, the setting of the auto sleep time is successful. + +## Reference + +During development, you can refer to the [default power mode configuration](https://gitee.com/openharmony/powermgr_power_manager/tree/master/services/native/profile): + +[Default configuration](https://gitee.com/openharmony/powermgr_power_manager/blob/master/services/native/profile/power_mode_config.xml) + +Packing path: `/system/etc/power_config/power_mode_config.xml` diff --git a/en/device-dev/website.md b/en/device-dev/website.md index ab50b73700c613e03a320fd03ae94cf61de4bada..193059b2703af86a54dea9e98244bb0eb052c5eb 100644 --- a/en/device-dev/website.md +++ b/en/device-dev/website.md @@ -457,8 +457,8 @@ - [FaultLogger Development](subsystems/subsys-dfx-faultlogger.md) - [Hiview Development](subsystems/subsys-dfx-hiview.md) - Power - - Power Consumption Statistics - - [Power Consumption Statistics Customization](subsystems/subsys-power-stats-power-average-customization.md) + - Display Management + - [System Brightness Customization](subsystems/subsys-power-brightness-customization.md) - Battery Management - [Battery Level and LED Color Mapping Customization](subsystems/subsys-power-level-LED-color.md) - [Battery Temperature Protection Customization](subsystems/subsys-power-temperature-protection.md) @@ -466,6 +466,8 @@ - [Charging Current and Voltage Limit Customization](subsystems/subsys-power-charge-current-voltage-limit.md) - [Charging Type Customization](subsystems/subsys-power-charge-type-customization.md) - [Power-off Charging Animation Customization](subsystems/subsys-power-poweroff-charge-animation.md) + - Power Consumption Statistics + - [Power Consumption Statistics Customization](subsystems/subsys-power-stats-power-average-customization.md) - Thermal Management - [Charging Idle State Customization](subsystems/subsys-thermal_charging_idle_state.md) - [Thermal Control Customization](subsystems/subsys-thermal_control.md) @@ -473,7 +475,9 @@ - [Thermal Level Customization](subsystems/subsys-thermal_level.md) - [Thermal Log Customization](subsystems/subsys-thermal_log.md) - [Thermal Policy Customization](subsystems/subsys-thermal_policy.md) - - [Thermal Scene Customization](subsystems/subsys-thermal_scene.md) + - [Thermal Scene Customization](subsystems/subsys-thermal_scene.md) + - Power Management + - [Power Mode Customization](subsystems/subsys-power-mode-customization.md) - Featured Topics - HPM Part - [HPM Part Overview](hpm-part/hpm-part-about.md)