From 0dfc2a58e9bc7968deafb84b41a187a416259fa3 Mon Sep 17 00:00:00 2001 From: shawn_he Date: Mon, 13 Mar 2023 15:14:52 +0800 Subject: [PATCH] update doc Signed-off-by: shawn_he --- en/application-dev/connectivity/Readme-EN.md | 4 + .../connectivity/net-connection-manager.md | 246 +++ .../connectivity/net-ethernet.md | 140 ++ .../connectivity/net-mgmt-overview.md | 12 +- .../connectivity/net-policy-management.md | 402 +++++ .../connectivity/net-sharing.md | 130 ++ .../connectivity/socket-connection.md | 267 ++- .../reference/apis/js-apis-http.md | 523 +++++- .../reference/apis/js-apis-net-ethernet.md | 291 ++- .../reference/apis/js-apis-net-policy.md | 1558 +++++++++++++++++ .../reference/apis/js-apis-net-sharing.md | 327 +++- .../reference/apis/js-apis-socket.md | 294 +++- .../reference/apis/js-apis-webSocket.md | 118 +- .../reference/errorcodes/Readme-EN.md | 2 + .../errorcodes/errorcode-net-http.md | 527 ++++++ .../errorcodes/errorcode-net-socket.md | 351 ++++ 16 files changed, 4872 insertions(+), 320 deletions(-) create mode 100644 en/application-dev/connectivity/net-connection-manager.md create mode 100644 en/application-dev/connectivity/net-ethernet.md create mode 100644 en/application-dev/connectivity/net-policy-management.md create mode 100644 en/application-dev/connectivity/net-sharing.md create mode 100644 en/application-dev/reference/apis/js-apis-net-policy.md create mode 100644 en/application-dev/reference/errorcodes/errorcode-net-http.md create mode 100644 en/application-dev/reference/errorcodes/errorcode-net-socket.md diff --git a/en/application-dev/connectivity/Readme-EN.md b/en/application-dev/connectivity/Readme-EN.md index 578e2a3c56..7176cb8fb4 100755 --- a/en/application-dev/connectivity/Readme-EN.md +++ b/en/application-dev/connectivity/Readme-EN.md @@ -5,6 +5,10 @@ - [HTTP Data Request](http-request.md) - [WebSocket Connection](websocket-connection.md) - [Socket Connection](socket-connection.md) + - [Network Policy Management](net-policy-management.md) + - [Network Sharing](net-sharing.md) + - [Ethernet Connection](net-ethernet.md) + - [Network Connection Management](net-connection-manager.md) - IPC & RPC - [IPC & RPC Overview](ipc-rpc-overview.md) - [IPC & RPC Development](ipc-rpc-development-guideline.md) diff --git a/en/application-dev/connectivity/net-connection-manager.md b/en/application-dev/connectivity/net-connection-manager.md new file mode 100644 index 0000000000..1eddb3b5bb --- /dev/null +++ b/en/application-dev/connectivity/net-connection-manager.md @@ -0,0 +1,246 @@ +# 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. + +## **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. + +## 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 + +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| +| ---- | ---- | ---- | +| ohos.net.connection | function getDefaultNet(callback: AsyncCallback\): void; |Creates a **NetHandle** object that contains the **netId** of the default network. This API uses an asynchronous callback to return the result.| +| ohos.net.connection | function getGlobalHttpProxy10+(callback: AsyncCallback\): void;| Obtains the global HTTP proxy for the network. This API uses an asynchronous callback to return the result.| +| ohos.net.connection | function setGlobalHttpProxy10+(httpProxy: HttpProxy, callback: AsyncCallback): void;| Sets the global HTTP proxy for the network. This API uses an asynchronous callback to return the result.| +| ohos.net.connection | function getAppNet9+(callback: AsyncCallback\): void;| Obtains a **NetHandle** object that contains the **netId** of the network bound to the application. This API uses an asynchronous callback to return the result.| +| ohos.net.connection | function setAppNet9+(netHandle: NetHandle, callback: AsyncCallback\): void;| Binds an application to the specified network. The application can access the external network only through this network. This API uses an asynchronous callback to return the result.| +| ohos.net.connection | function getDefaultNetSync9+(): NetHandle; |Obtains the default active data network in synchronous mode. You can use **getNetCapabilities** to obtain information such as the network type and capabilities.| +| ohos.net.connection | function hasDefaultNet(callback: AsyncCallback\): void; |Checks whether the default network is available. This API uses an asynchronous callback to return the result.| +| ohos.net.connection | function getAllNets(callback: AsyncCallback\>): void;| Obtains the list of **NetHandle** objects of the connected network. This API uses an asynchronous callback to return the result.| +| ohos.net.connection | function getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\): void; |Obtains link information of the default network. This API uses an asynchronous callback to return the result.| +| ohos.net.connection | function getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback\): void; |Obtains the capability set of the default network. This API uses an asynchronous callback to return the result.| +| ohos.net.connection | function isDefaultNetMetered9+(callback: AsyncCallback): void; |Checks whether the data traffic usage on the current network is metered. This API uses an asynchronous callback to return the result.| +| ohos.net.connection | function reportNetConnected(netHandle: NetHandle, callback: AsyncCallback\): 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.| +| ohos.net.connection | function reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback\): 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.| +| ohos.net.connection | function getAddressesByName(host: string, callback: AsyncCallback\>): void; |Obtains all IP addresses of the specified network by resolving the domain name. This API uses an asynchronous callback to return the result.| +| ohos.net.connection | function enableAirplaneMode(callback: AsyncCallback\): void; | Enables the airplane mode. This API uses an asynchronous callback to return the result.| +| ohos.net.connection | function disableAirplaneMode(callback: AsyncCallback\): void;| Disables the airplane mode. This API uses an asynchronous callback to return the result.| +| ohos.net.connection | function createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection; | Creates a **NetConnection** object. **netSpecifier** specifies the network, and **timeout** specifies the timeout interval in ms. **timeout** is configurable only when **netSpecifier** is specified. If neither of them is present, the default network is used.| +| ohos.net.connection.NetHandle | bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\): void; | Binds a **TCPSocket** or **UDPSocket** to the current network. This API uses an asynchronous callback to return the result.| +| ohos.net.connection.NetHandle | getAddressesByName(host: string, callback: AsyncCallback\>): void; |Obtains all IP addresses of the default network by resolving the domain name. This API uses an asynchronous callback to return the result.| +| ohos.net.connection.NetHandle | getAddressByName(host: string, callback: AsyncCallback\): void; |Obtains an IP address of the specified network by resolving the domain name. This API uses an asynchronous callback to return the result.| +| ohos.net.connection.NetConnection | on(type: 'netAvailable', callback: Callback\): void; |Subscribes to **netAvailable** events.| +| ohos.net.connection.NetConnection | on(type: 'netCapabilitiesChange', callback: Callback\<{ netHandle: NetHandle, netCap: NetCapabilities }>): void; |Subscribes to **netCapabilitiesChange** events.| +| ohos.net.connection.NetConnection | on(type: 'netConnectionPropertiesChange', callback: Callback\<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void; |Subscribes to **netConnectionPropertiesChange** events.| +| ohos.net.connection.NetConnection | on(type: 'netBlockStatusChange', callback: Callback<{ netHandle: NetHandle, blocked: boolean }>): void; |Subscribes to **netBlockStatusChange** events.| +| ohos.net.connection.NetConnection | on(type: 'netLost', callback: Callback\): void; |Subscribes to **netLost** events.| +| ohos.net.connection.NetConnection | on(type: 'netUnavailable', callback: Callback\): void; |Subscribes to **netUnavailable** events.| +| ohos.net.connection.NetConnection | register(callback: AsyncCallback\): void; |Registers an observer for the default network or the network specified in **createNetConnection**.| +| ohos.net.connection.NetConnection | unregister(callback: AsyncCallback\): void; |Unregisters the observer for the default network or the network specified in **createNetConnection**.| + +## Subscribing to Status Changes of the Specified Network + +1. Import the connection namespace from **@ohos.net.connection.d.ts**. + +2. Call **createNetConnection()** to create a **NetConnection** object. You can specify the network type, capability, and timeout interval. If you do not specify parameters, the default values will be used. + +3. Call **conn.on()** to subscribe to the target event. You must pass in **type** and **callback**. + +4. Call **conn.register()** to subscribe to network status changes of the specified network. + +5. When the network is available, the callback will be invoked to return the **netAvailable** event. When the network is unavailable, the callback will be invoked to return the **netUnavailable** event. + +6. Call **conn.unregister()** to unsubscribe from the network status changes if required. + +```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) => {}); +``` + +## Obtaining the List of All Registered Networks + +### How to Develop + +1. Import the connection namespace from **@ohos.net.connection.d.ts**. + +2. Call **getAllNets** to obtain the list of all connected networks. + +```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; + } + }) +``` + +## Querying Network Capability Information and Connection Information of Specified Data Network + +### How to Develop + +1. Import the connection namespace from **@ohos.net.connection.d.ts**. + +2. Call **getDefaultNet** to obtain the default data network via **NetHandle** or call **getAllNets** to obtain the list of all connected networks via **Array\**. + +3. Call **getNetCapabilities** to obtain the network capability information of the data network specified by **NetHandle**. The capability information includes information such as the network type (cellular, Wi-Fi, or Ethernet network) and the specific network capabilities. + +4. Call **getConnectionProperties** to obtain the connection information of the data network specified by **NetHandle**. + +```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)); + }) + } +``` + +## Resolving the domain name of a network to obtain all IP addresses + +### How to Develop + +1. Import the connection namespace from **@ohos.net.connection.d.ts**. + +2. Call **getAddressesByName** to use the default network to resolve the host name to obtain the list of all IP addresses. + +```js + // Import the connection namespace. + 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)); + }) +``` diff --git a/en/application-dev/connectivity/net-ethernet.md b/en/application-dev/connectivity/net-ethernet.md new file mode 100644 index 0000000000..85c4ef4fc1 --- /dev/null +++ b/en/application-dev/connectivity/net-ethernet.md @@ -0,0 +1,140 @@ +# 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. + +> **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. + +## 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. + +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| +| ---- | ---- | ---- | +| ohos.net.ethernet | function setIfaceConfig(iface: string, ic: InterfaceConfiguration, callback: AsyncCallback\): void | Configures the network attributes of the specified Ethernet network. This API uses an asynchronous callback to return the result.| +| 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.| + +## Ethernet Connection – DHCP Mode + +1. Use a network cable to connect the device to a network port. +2. Import the **ethernet** namespace from **@ohos.net.ethernet**. +3. Call **getAllActiveIfaces** to obtain the list of all active network ports, for example, **eth0** and **eth1**. +4. Call **isIfaceActive** in user mode to check whether the **eth0** port is active. +5. Call **getIfaceConfig** in user mode to obtain the static network attributes of the **eth0** port. By default, an unconfigured Ethernet network uses the DHCP mode, in which the Ethernet network obtains the automatically assigned network attributes. + +```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); + } + }); +``` +## Ethernet Connection – Static Mode + +### How to Develop + +1. Use a network cable to connect the device to a network port. +2. Import the **ethernet** namespace from **@ohos.net.ethernet**. +3. Call **getAllActiveIfaces** in user mode to obtain the list of all active network ports, for example, **eth0** and **eth1**. +4. Call **isIfaceActive** in user mode to check whether the **eth0** port is active. +5. Call **setIfaceConfig** in user mode to set the **eth0** port to the static mode, in which you need to manually assign the network attributes (including the IP address, subnet mask, gateway, and DNS). +6. Call **getIfaceConfig** in user mode to obtain the static network attributes of the **eth0** port. + +```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); + } + }); +``` diff --git a/en/application-dev/connectivity/net-mgmt-overview.md b/en/application-dev/connectivity/net-mgmt-overview.md index 3c8eeb552b..0ad30c35cc 100644 --- a/en/application-dev/connectivity/net-mgmt-overview.md +++ b/en/application-dev/connectivity/net-mgmt-overview.md @@ -2,15 +2,19 @@ Network management functions include: -- [HTTP Data Request](http-request.md): Initiates a data request through HTTP. -- [WebSocket Connection](websocket-connection.md): Establishes a bidirectional connection between the server and client through WebSocket. -- [Socket Connection](socket-connection.md): Transmits data through Socket. +- [HTTP data request](http-request.md): Initiates a data request through HTTP. +- [WebSocket connection](websocket-connection.md): Establishes a bidirectional connection between the server and client through WebSocket. +- [Socket connection](socket-connection.md): Transmits data through Socket. +- [Network policy management](net-policy-management.md): Restricts network capabilities by setting network policies, including cellular network policy, sleep/power-saving mode policy, and background network policy, and resets network policies as needed. +- [Network sharing](net-sharing.md): Shares a device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing, and queries the network sharing state and shared mobile data volume. +- [Ethernet connection](net-ethernet.md): Provides wired network capabilities, which allow you to set the IP address, subnet mask, gateway, and Domain Name System (DNS) server of a wired network. +- [Network connection management](net-connection-manager.md): 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. ## Constraints To use the functions of the network management module, you must obtain the permissions listed in the following table. -| Permission | Description | +| Permission | Description | | -------------------------------- | -------------------------------------- | | ohos.permission.GET_NETWORK_INFO | Allows an application to obtain the network connection information. | | ohos.permission.SET_NETWORK_INFO | Allows an application to modify the network connection state. | diff --git a/en/application-dev/connectivity/net-policy-management.md b/en/application-dev/connectivity/net-policy-management.md new file mode 100644 index 0000000000..f2394e5f01 --- /dev/null +++ b/en/application-dev/connectivity/net-policy-management.md @@ -0,0 +1,402 @@ +# Network Policy Management + +## Introduction + +The Network Policy Management module allows you to restrict network capabilities by setting network policies, including cellular network policy, sleep/power-saving mode policy, and background network policy, and to reset network policies as needed. + +> **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-policy.md). + +## Basic Concepts + +- Sleep mode: A mode in which the system shuts down some idle components and peripherals to enter the low-power mode and restricts some applications from accessing the network. +- Power-saving mode: A mode in which the system disables certain functions and features to save power. When this mode is enabled, the system performance deteriorates and some applications are restricted from accessing the network. +- Traffic-saving mode: A mode in which the system restricts background applications that use the metering network. It is equivalent to the background network policy. +- Cellular network: A mobile communication network. +- Metering network: A mobile network with preconfigured traffic quota, WLAN network, or Ethernet network. + +## **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. + +## When to Use + +Typical application scenarios of network policy management are as follows: + +- Managing the metering network policy: Set the metering network quota and obtain the configured metering network policy. +- Managing network access for an application in the background: Set and obtain the status of the background network restriction switch, and check whether the application indicated by the specified UID can access the network in the background. +- Managing the metering network access policy: Set and obtain the policy for the application indicated by the specified UID to access the metering network, and obtain the UIDs of the applications for which the policy is configured. +- Restoring network policies +- Checking whether an application indicated by the specified UID can access a metering or non-metering network +- Adding a UID to or removing a UID from the sleep mode allowlist, and obtaining the sleep mode allowlist +- Adding a UID to or removing a UID from the power-saving mode allowlist, and obtaining the power-saving mode allowlist +- Updating the network notification policy + +The following describes the development procedure specific to each application scenario. + +## Available APIs + +For the complete list of APIs and example code, see [Network Policy Management](../reference/apis/js-apis-net-policy.md). + +| Type| API| Description| +| ---- | ---- | ---- | +| ohos.net.policy | function setBackgroundPolicy(isAllowed: boolean, callback: AsyncCallback\): void |Sets a background network policy. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function isBackgroundAllowed(callback: AsyncCallback\): void; |Obtains the background network policy. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function setPolicyByUid(uid: number, policy: NetUidPolicy, callback: AsyncCallback\): void; |Sets an application-specific network policy by **uid**. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function getPolicyByUid(uid: number, callback: AsyncCallback\): void;| Obtains an application-specific network policy by **uid**. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function getUidsByPolicy(policy: NetUidPolicy, callback: AsyncCallback\>): void; | Obtains the UID array of applications configured with a certain application-specific network policy. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function getNetQuotaPolicies(callback: AsyncCallback\>): void; |Obtains the network quota policies. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function setNetQuotaPolicies(quotaPolicies: Array\, callback: AsyncCallback\): void; |Sets an array of network quota policies. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function restoreAllPolicies(iccid: string, callback: AsyncCallback\): void; | Restores all the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function isUidNetAllowed(uid: number, isMetered: boolean, callback: AsyncCallback\): void; | Checks whether an application is allowed to access metering or non-metering networks. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function isUidNetAllowed(uid: number, iface: string, callback: AsyncCallback\): void; | Checks whether an application is allowed to access the given network. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function setDeviceIdleAllowList(uid: number, isAllowed: boolean, callback: AsyncCallback\): void; | Sets whether to add an application to the device idle allowlist. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function getDeviceIdleAllowList(callback: AsyncCallback\>): void; | Obtains the UID array of applications that are on the device idle allowlist. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function getBackgroundPolicyByUid(uid: number, callback: AsyncCallback\): void; | Obtains the background network policies configured for the given application. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function resetPolicies(iccid: string, callback: AsyncCallback\): void; | Restores all the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function updateRemindPolicy(netType: NetBearType, iccid: string, remindType: RemindType, callback: AsyncCallback\): void; | Updates a reminder policy. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function setPowerSaveAllowList(uid: number, isAllowed: boolean, callback: AsyncCallback\): void; | Sets whether to add an application to the power-saving allowlist. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function getPowerSaveAllowList(callback: AsyncCallback\>): void; | Obtains the UID array of applications that are on the power-saving allowlist. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function on(type: "netUidPolicyChange", callback: Callback\<{ uid: number, policy: NetUidPolicy }>): void; | Subscribes to policy changes. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function off(type: "netUidPolicyChange", callback: Callback\<{ uid: number, policy: NetUidPolicy }>): void; | Unsubscribes from policy changes. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function on(type: "netUidRuleChange", callback: Callback\<{ uid: number, rule: NetUidRule }>): void; | Subscribes to rule changes. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function off(type: "netUidRuleChange", callback: Callback\<{ uid: number, rule: NetUidRule }>): void; | Unsubscribes from rule changes. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function on(type: "netMeteredIfacesChange", callback: Callback\>): void; | Subscribes to metered **iface** changes. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function off(type: "netMeteredIfacesChange", callback: Callback\>): void; | Unsubscribes from metered **iface** changes. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function on(type: "netQuotaPolicyChange", callback: Callback\>): void; | Subscribes to network quota policy changes. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function off(type: "netQuotaPolicyChange", callback: Callback\>): void; | Unsubscribes from network quota policy changes. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function on(type: "netBackgroundPolicyChange", callback: Callback\): void; | Subscribes to background network policy changes. This API uses an asynchronous callback to return the result.| +| ohos.net.policy | function off(type: "netBackgroundPolicyChange", callback: Callback\): void; | Unsubscribes from background network policy changes. This API uses an asynchronous callback to return the result.| + +## Managing the Metering Network Policy + +1. Import the **policy** namespace from **@ohos.net.policy.d.ts**. + +2. Call **setNetQuotaPolicies** to configure the metering network policy. + +3. Call **getNetQuotaPolicies** to obtain the configured metering network policy. + +```js + // Import the policy namespace. + import policy from '@ohos.net.policy'; + + addNetQuotaPolicy(){ + let param = { + // For details about the value of netType, see [NetBearType](../reference/apis/js-apis-net-connection.md#netbeartype). + netType:Number.parseInt(this.netType), + + // Integrated circuit card identifier (ICCID) of the SIM card on the metering cellular network. It is not available for an Ethernet or Wi-Fi network. + iccid:this.iccid, + + // Used together with ICCID on the metering cellular network. It is used independently on an Ethernet or Wi-Fi network. + ident:this.ident, + + // Metering start time, for example, M1, D1, and Y1. + periodDuration:this.periodDuration, + + // Set the traffic threshold for generating an alarm to an integer greater than 0. + warningBytes:Number.parseInt(this.warningBytes), + + // Set the traffic quota to an integer greater than 0. + limitBytes:Number.parseInt(this.limitBytes), + + // Specify whether the network is a metering network. The value true means a metering network and false means a non-metering network. + metered:Boolean(Number.parseInt(this.metered)),https://gitee.com/openharmony/docs/pulls/14404 + // For details about the action triggered after the traffic limit is reached, see [LimitAction](../reference/apis/js-apis-net-policy.md#limitation). + limitAction:Number.parseInt(this.limitAction) + }; + this.netQuotaPolicyList.push(param); + }, + + // Subscribe to metered iface changes. + policy.on('netMeteredIfacesChange', (data) => { + this.log('on netMeteredIfacesChange: ' + JSON.stringify(data)); + }); + + // Subscribe to metering network policy changes. + policy.on('netQuotaPolicyChange', (data) => { + this.log('on netQuotaPolicyChange: ' + JSON.stringify(data)); + }); + + // Call setNetQuotaPolicies to configure the metering network policy. + setNetQuotaPolicies(){ + this.dialogType = DialogType.HIDE; + policy.setNetQuotaPolicies(this.netQuotaPolicyList, (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)); + }); + }, + + // Call getNetQuotaPolicies to obtain the configured metering network policy. + getNetQuotaPolicies(){ + policy.getNetQuotaPolicies((err, data) => { + this.callBack(err, data); + if(data){ + this.netQuotaPolicyList = data; + } + }); + }, + + // Unsubscribe from metered iface changes. + policy.off('netMeteredIfacesChange', (data) => { + this.log('off netMeteredIfacesChange: ' + JSON.stringify(data)); + }); + + // Unsubscribe from metering network policy changes. + policy.off('netQuotaPolicyChange', (data) => { + this.log('off netQuotaPolicyChange: ' + JSON.stringify(data)); + }); +``` + +## Managing Network Access for an Application in the Background + +### How to Develop + +1. Import the **policy** namespace from **@ohos.net.policy.d.ts**. + +2. Call **setBackgroundAllowed** to enable or disable the background network restriction switch. + +3. Call **isBackgroundAllowed** to check whether the background network restriction switch is enabled or disabled. + +4. Call **getBackgroundPolicyByUid** to check whether the application indicated b the specified UID can access the network in the background. + +```js + // Import the policy namespace. + import policy from '@ohos.net.policy' + + // Subscribe to background network policy changes. + policy.on('netBackgroundPolicyChange', (data) => { + this.log('on netBackgroundPolicyChange: ' + JSON.stringify(data)); + }); + + // Call setBackgroundAllowed to enable or disable the background network restriction switch. + setBackgroundAllowed() { + policy.setBackgroundAllowed(Boolean(Number.parseInt(this.isBoolean)), (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, + + // Call isBackgroundAllowed to check whether the background network restriction switch is enabled or disabled. + isBackgroundAllowed() { + policy.isBackgroundAllowed((err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, + + // Call getBackgroundPolicyByUid to check whether the application indicated b the specified UID can access the network in the background. + getBackgroundPolicyByUid() { + policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam), (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, + + // Unsubscribe from background network policy changes. + policy.off('netBackgroundPolicyChange', (data) => { + this.log('off netBackgroundPolicyChange: ' + JSON.stringify(data)); + }); +``` + +## Managing the Metering Network Access Policy + +### How to Develop + +1. Import the **policy** namespace from **@ohos.net.policy.d.ts**. + +2. Call **setPolicyByUid** to set whether the application indicated by the specified UID can access the network in the background. + +3. Call **getPolicyByUid** to check whether the metering network access policy for the application indicated by the specified UID. + +4. Call **getUidsByPolicy** to obtain the UIDs of the applications for which the metering network access policy is configured. + +```js + // Import the policy namespace. + import policy from '@ohos.net.policy' + + // Subscribe to policy changes of the application indicated by the specified UID. + policy.on('netUidPolicyChange', (data) => { + this.log('on netUidPolicyChange: ' + JSON.stringify(data)); + }); + + // Subscribe to rule changes of the application indicated by the specified UID. + policy.on('netUidRuleChange', (data) => { + this.log('on netUidRuleChange: ' + JSON.stringify(data)); + }); + + // Call setPolicyByUid to set whether the application indicated by the specified UID can access the network in the background. + setPolicyByUid() { + let param = { + uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy) + } + policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy), (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, + + // Call getPolicyByUid to check whether the metering network access policy for the application indicated by the specified UID. + getPolicyByUid() { + policy.getPolicyByUid(Number.parseInt(this.firstParam), (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, + + // Call getUidsByPolicy to obtain the UIDs of the applications for which the metering network access policy is configured. + getUidsByPolicy(){ + policy.getUidsByPolicy(Number.parseInt(this.currentNetUidPolicy), (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, + + // Unsubscribe from policy changes of the application indicated by the specified UID. + policy.off('netUidPolicyChange', (data) => { + this.log('off netUidPolicyChange: ' + JSON.stringify(data)); + }); + + // Unsubscribe from rule changes of the application indicated by the specified UID. + policy.off('netUidRuleChange', (data) => { + this.log('off netUidRuleChange: ' + JSON.stringify(data)); + }); + +``` + +## Restoring Network Policies + +### How to Develop + +1. Import the **policy** namespace from **@ohos.net.policy.d.ts**. + +2. Call **restoreAllPolicies** to restore all network policies. + +```js + // Import the policy namespace. + import policy from '@ohos.net.policy' + + // Call restoreAllPolicies to restore all network policies. + restoreAllPolicies(){ + policy.restoreAllPolicies(this.firstParam, (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, +``` + +## Checking Access to a Metering or Non-metering Network + +### How to Develop + +1. Import the **policy** namespace from **@ohos.net.policy.d.ts**. + +2. Call **isUidNetAllowed** to check whether the UID can access the metering or non-metering network. + +```js + // Import the policy namespace. + import policy from '@ohos.net.policy' + + // Call isUidNetAllowed to check whether the application indicated by the specified UID can access the metering or non-metering network. + isUidNetAllowedIsMetered(){ + let param = { + uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean)) + } + policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, +``` + +## Managing the Sleep Mode Allowlist + +### How to Develop + +1. Import the **policy** namespace from **@ohos.net.policy.d.ts**. + +2. Call **setDeviceIdleAllowList** to add a UID to or remove a UID from the sleep mode allowlist. + +3. Call **getDeviceIdleAllowList** to obtain the UIDs added to the sleep mode allowlist. + +```js + // Import the policy namespace. + import policy from '@ohos.net.policy' + + // Call setDeviceIdleAllowList to add a UID to or remove a UID from the sleep mode allowlist. + setDeviceIdleAllowList(){ + let param = { + uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) + } + policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, + + // Call getDeviceIdleAllowList to obtain the UIDs added to the sleep mode allowlist. + getDeviceIdleAllowList(){ + policy.getDeviceIdleAllowList((err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, +``` + +## Managing the Power-saving Mode Allowlist + +### How to Develop + +1. Import the **policy** namespace from **@ohos.net.policy.d.ts**. +2. Call **setPowerSaveAllowList** to add a UID to or remove a UID from the power-saving mode allowlist. +3. Call **getPowerSaveAllowList** to obtain the UIDs added to the power-saving mode allowlist. + +```js + // Import the policy namespace. + import policy from '@ohos.net.policy' + + // Call setPowerSaveAllowList to add a UID to or remove a UID from the power-saving mode allowlist. + setPowerSaveAllowList(){ + let param = { + uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) + } + policy.setPowerSaveAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, + + // Call getPowerSaveAllowList to obtain the UIDs added to the power-saving mode allowlist. + getPowerSaveAllowList(){ + policy.getPowerSaveAllowList((err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, +``` + +## Updating the Network Notification Policy + +### How to Develop + +1. Import the **policy** namespace from **@ohos.net.policy.d.ts**. + +2. Call **updateRemindPolicy** to update the network notification policy. + +```js + // Import the policy namespace. + import policy from '@ohos.net.policy' + + // Call updateRemindPolicy to update the network notification policy. + updateRemindPolicy() { + let param = { + netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType + } + policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType), (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, +``` diff --git a/en/application-dev/connectivity/net-sharing.md b/en/application-dev/connectivity/net-sharing.md new file mode 100644 index 0000000000..d81e8f59ec --- /dev/null +++ b/en/application-dev/connectivity/net-sharing.md @@ -0,0 +1,130 @@ +# 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. + +## **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. + +## When to Use +Typical network sharing scenarios are as follows: +- 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| +| ---- | ---- | ---- | +| ohos.net.sharing | function isSharingSupported(callback: AsyncCallback\): void; | Checks whether the system supports network sharing. This API uses an asynchronous callback to return the result.| +| ohos.net.sharing | function isSharing(callback: AsyncCallback\): void; | Checks whether network sharing is active. This API uses an asynchronous callback to return the result.| +| ohos.net.sharing | function startSharing(type: SharingIfaceType, callback: AsyncCallback\): void; | Starts network sharing. This API uses an asynchronous callback to return the result.| +| ohos.net.sharing | function stopSharing(type: SharingIfaceType, callback: AsyncCallback\): void; | Stops network sharing. This API uses an asynchronous callback to return the result.| +| ohos.net.sharing | function getStatsRxBytes(callback: AsyncCallback\): void; | Obtains the received data traffic during network sharing, in KB. This API uses an asynchronous callback to return the result.| +| ohos.net.sharing | function getStatsTxBytes(callback: AsyncCallback\): void; | Obtains the sent data traffic during network sharing, in KB. This API uses an asynchronous callback to return the result.| +| ohos.net.sharing | function getStatsTotalBytes(callback: AsyncCallback\): void; | Obtains the total data traffic during network sharing, in KB. This API uses an asynchronous callback to return the result.| +| ohos.net.sharing | function getSharingIfaces(state: SharingIfaceState, callback: AsyncCallback\>): void; | Obtains the names of network interface cards (NICs) in the specified network sharing state.. This API uses an asynchronous callback to return the result.| +| ohos.net.sharing | function getSharingState(type: SharingIfaceType, callback: AsyncCallback\): void; | Obtains the network sharing state of the specified type. This API uses an asynchronous callback to return the result.| +| ohos.net.sharing | function getSharableRegexes(type: SharingIfaceType, callback: AsyncCallback\>): void; | Obtains regular expressions of NICs of a specified type. This API uses an asynchronous callback to return the result.| +| ohos.net.sharing | function on(type: 'sharingStateChange', callback: Callback\): void; | Subscribes to network sharing state changes.| +| ohos.net.sharing | function off(type: 'sharingStateChange', callback?: Callback\): void; | Unsubscribes from network sharing state changes.| +| ohos.net.sharing | unction on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void; | Subscribes to network sharing state changes of the specified NIC.| +| ohos.net.sharing | function off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void; | Unsubscribes from network sharing state changes of the specified NIC.| +| ohos.net.sharing | function on(type: 'sharingUpstreamChange', callback: Callback\): void; | Subscribes to upstream NIC changes.| +| ohos.net.sharing | function off(type: 'sharingUpstreamChange', callback?: Callback\): void; | Unsubscribes from upstream NIC changes.| + +## Enabling Network Sharing + +1. Import the **sharing** namespace from **@ohos.net.sharing**. +2. Subscribe to network sharing state changes. +3. Call **startSharing** to start network sharing of the specified type. +4. Return the callback for successfully starting network sharing. + +```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(SharingIfaceType.SHARING_WIFI, (error) => { + console.log(JSON.stringify(error)); + }); +``` + +## Disabling network sharing + +### How to Develop + +1. Import the **sharing** namespace from **@ohos.net.sharing**. +2. Subscribe to network sharing state changes. +3. Call **stopSharing** to stop network sharing of the specified type. +4. Return the callback for successfully stopping network sharing. + +```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(SharingIfaceType.SHARING_WIFI, (error) => { + console.log(JSON.stringify(error)); + }); +``` + +## Obtaining the data traffic of the shared network + +### How to Develop + +1. Import the **sharing** namespace from **@ohos.net.sharing**. +2. Call **startSharing** to start network sharing of the specified type. +3. Call **getStatsTotalBytes** to obtain the data traffic generated during data sharing. +4. Call **stopSharing** to stop network sharing of the specified type and clear the data volume of network sharing. + +```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(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(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 da5bea318e..96c802d565 100644 --- a/en/application-dev/connectivity/socket-connection.md +++ b/en/application-dev/connectivity/socket-connection.md @@ -1,46 +1,82 @@ # Socket Connection +## Introduction -## Use Cases +The Socket Connection module allows an application to transmit data over a Socket connection through the TCP, UDP, or TLS protocol. -Your application can transmit data through Socket connections. Currently, the TCP and UDP protocols are supported. +## Basic Concepts +- Socket: An abstraction of endpoints for bidirectional communication between application processes running on different hosts in a network. +- TCP: Transmission Control Protocol, which is a byte stream–based transport layer communication protocol that is connection-oriented and reliable. +- UDP: User Datagram Protocol, which is a simple datagram-oriented transport layer communication protocol. +- TLS: Transport Layer Security, which is a protocol that ensures the data confidentiality and integrity between communication programs. + +## When to Use + +Applications transmit data over TCP, UDP, or TLS Socket connections. The main application scenarios are as follows: + +- Implementing data transmission over TCP/UDP Socket connections +- Implementing encrypted data transmission over TLS Socket connections ## Available APIs -The Socket connection function is mainly implemented by the Socket module. The following table describes the related APIs. +For the complete list of APIs and example code, see [Socket Connection](../reference/apis/js-apis-socket.md). + +Socket connection functions are mainly implemented by the **socket** module. The following table describes the related APIs. -| API| Description | +| API| Description| | -------- | -------- | -| constructUDPSocketInstance() | Creates a **UDPSocket** object. | -| constructTCPSocketInstance() | Creates a **TCPSocket** object. | -| bind() | Binds the IP address and port number. | +| constructUDPSocketInstance() | Creates a **UDPSocket** object.| +| constructTCPSocketInstance() | Creates a **TCPSocket** object.| +| bind() | Binds the IP address and port number.| | send() | Sends data.| -| close() | Closes a Socket connection. | -| getState() | Obtains the Socket connection status. | -| connect() | Connects to the specified IP address and port. This function is supported only for TCP. | -| getRemoteAddress() | Obtains the peer address of the Socket connection. This function is supported only for TCP. The **connect** API must have been called before you use this API. | -| on(type: 'message') | Enables listening for **message** events of the Socket connection. | -| off(type: 'message') | Disables listening for **message** events of the Socket connection. | -| on(type: 'close') | Enables listening for **close** events of the Socket connection. | -| off(type: 'close') | Disables listening for **close** events of the Socket connection. | -| on(type: 'error') | Enables listening for **error** events of the Socket connection. | -| off(type: 'error') | Disables listening for **error** events of the Socket connection. | -| on(type: 'listening') | Enables listening for **listening** events of the UDPSocket connection. | -| off(type: 'listening') | Disables listening for **listening** events of the UDPSocket connection. | -| on(type: 'connect') | Enables listening for **connect** events of the TCPSocket connection. | -| off(type: 'connect') | Disables listening for **connect** events of the TCPSocket connection. | +| close() | Closes a Socket connection.| +| getState() | Obtains the Socket connection status.| +| connect() | Connects to the specified IP address and port. This function is supported only for TCP.| +| getRemoteAddress() | Obtains the peer address of the Socket connection. This function is supported only for TCP. The **connect** API must have been called before you use this API.| +| on(type: 'message') | Subscribes to **message** events of the Socket connection.| +| off(type: 'message') | Unsubscribes from **message** events of the Socket connection.| +| on(type: 'close') | Subscribes to **close** events of the Socket connection.| +| off(type: 'close') | Unsubscribes from **close** events of the Socket connection.| +| on(type: 'error') | Subscribes to **error** events of the Socket connection.| +| off(type: 'error') | Unsubscribes from **error** events of the Socket connection.| +| on(type: 'listening') | Subscribes to **listening** events of the UDP Socket connection. | +| off(type: 'listening') | Unsubscribes from **listening** events of the UDP Socket connection. | +| on(type: 'connect') | Subscribes to **connect** events of the TCP Socket connection. | +| off(type: 'connect') | Unsubscribes from **connect** events of the TCP Socket connection.| +TLS Socket connection functions are mainly provided by the **tls_socket** module. The following table describes the related APIs. + +| API| Description| +| -------- | -------- | +| bind() | Binds the IP address and port number.| +| close(type: 'error') | Closes a Socket connection.| +| connect() | Sets up a connection to the specified IP address and port number.| +| getCertificate() | Obtains an object representing the local certificate.| +| getCipherSuite() | Obtains a list containing information about the negotiated cipher suite.| +| getProtocol() | Obtains a string containing the SSL/TLS protocol version negotiated for the current connection.| +| getRemoteAddress() | Obtains the peer address of the TLS Socket connection.| +| getRemoteCertificate() | Obtains an object representing a peer certificate.| +| getSignatureAlgorithms() | Obtains a list containing signature algorithms shared between the server and client, in descending order of priority.| +| getState() | Obtains the TLS Socket connection status.| +| off(type: 'close') | Unsubscribes from **close** events of the TLS Socket connection.| +| off(type: 'error') | Unsubscribes from **error** events of the TLS Socket connection.| +| off(type: 'message') | Unsubscribes from **message** events of the TLS Socket connection.| +| on(type: 'close') | Subscribes to **close** events of the TLS Socket connection.| +| on(type: 'error') | Subscribes to **error** events of the TLS Socket connection.| +| on(type: 'message') | Subscribes to **message** events of the TLS Socket connection.| +| send() | Sends data.| +| setExtraOptions() | Sets other properties of the TLS Socket connection.| -## How to Develop +## Transmitting Data over TCP/UDP Socket Connections -The implementation is similar for UDPSocket and TCPSocket. The following uses the TCPSocket as an example. +The implementation is similar for UDP Socket and TCP Socket connections. The following uses data transmission over a TCP Socket connection as an example. -1. Import the required Socket module. +1. Import the required **socket** module. 2. Create a **TCPSocket** object. -3. (Optional) Enable listening for TCPSocket events. +3. (Optional) Subscribe to TCP Socket connection events. 4. Bind the IP address and port number. The port number can be specified or randomly allocated by the system. @@ -48,15 +84,15 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th 6. Send data. -7. Enable the TCPSocket connection to be automatically closed after use. - +7. Enable the TCP Socket connection to be automatically closed after use. + ```js import socket from '@ohos.net.socket' - + // Create a TCPSocket object. let tcp = socket.constructTCPSocketInstance(); - - // Enable listening for TCPSocket events. + + // Subscribe to TCP Socket connection events. tcp.on('message', value => { console.log("on message") let buffer = value.message @@ -73,7 +109,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th tcp.on('close', () => { console.log("on close") }); - + // Bind the local IP address and port number. let bindAddress = { address: '192.168.xx.xx', @@ -86,6 +122,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th return; } console.log('bind success'); + // Set up a connection to the specified IP address and port number. let connectAddress = { address: '192.168.xx.xx', @@ -100,6 +137,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th return; } console.log('connect success'); + // Send data. tcp.send({ data: 'Hello, server!' @@ -112,7 +150,8 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th }) }); }); - // Enable the TCPSocket connection to be automatically closed after use. Then, disable listening for TCPSocket events. + + // Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events. setTimeout(() => { tcp.close((err) => { console.log('close socket.') @@ -122,3 +161,167 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th tcp.off('close'); }, 30 * 1000); ``` + +## Implementing Encrypted Data Transmission over TLS Socket Connections + +### How to Develop + +TLS Socket connection process on the client: + +1. Import the required **socket** module. + +2. Bind the IP address and port number of the server. + +3. For two-way authentication, upload the client CA certificate and digital certificate. For one-way authentication, upload the client CA certificate. + +4. Create a **TLSSocket** object. + +5. (Optional) Subscribe to TLS Socket connection events. + +6. Send data. + +7. Enable the TLS Socket connection to be automatically closed after use. + +```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. + tcp.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) + }); + tcp.on('connect', () => { + console.log("on connect") + }); + tcp.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 TLS Socket connection to be automatically closed after use. Then, disable listening for TLS Socket connection events. + tls.close((err) => { + if (err) { + console.log("close callback error = " + err); + } else { + console.log("close success"); + } + tls.off('message'); + tls.off('connect'); + tls.off('close'); + }); + + // Create a TLS Socket connection (for one-way authentication). + let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication + + // Subscribe to TLS Socket connection events. + tcp.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) + }); + tcp.on('connect', () => { + console.log("on connect") + }); + tcp.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 TLS Socket connection to be automatically closed after use. Then, disable listening for TLS Socket connection events. + tls.close((err) => { + if (err) { + console.log("close callback error = " + err); + } else { + console.log("close success"); + } + tls.off('message'); + tls.off('connect'); + tls.off('close'); + }); +``` + +## Samples + +The following samples are provided to help you better understand how to develop Socket connection features: +- [`Socket`: Socket Connection (ArkTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Network/Socket) +- [UDP Socket (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/UdpDemoOH) +- [TCP Socket (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/TcpSocketDemo) diff --git a/en/application-dev/reference/apis/js-apis-http.md b/en/application-dev/reference/apis/js-apis-http.md index 1a78a92b32..f88c44972c 100644 --- a/en/application-dev/reference/apis/js-apis-http.md +++ b/en/application-dev/reference/apis/js-apis-http.md @@ -2,8 +2,10 @@ 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**
-> 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. +>**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. +> ## Modules to Import @@ -11,9 +13,10 @@ The **http** module provides the HTTP data request capability. An application ca import http from '@ohos.net.http'; ``` -## Example +## Examples ```js +// Import the HTTP namespace. import http from '@ohos.net.http'; // Each httpRequest corresponds to an HTTP request task and cannot be reused. @@ -24,7 +27,7 @@ httpRequest.on('headersReceive', (header) => { console.info('header: ' + JSON.stringify(header)); }); httpRequest.request( - // Customize EXAMPLE_URL on your own. It is up to you whether to add parameters to the URL. + // 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. @@ -42,16 +45,19 @@ httpRequest.request( 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:' + data.result); - console.info('code:' + data.responseCode); + 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:' + data.cookies); // 8+ + 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(); } @@ -70,7 +76,7 @@ Creates an HTTP request. You can use this API to initiate or destroy an HTTP req **Return value** | Type | Description | -| ---------- | ----------------------------------------------------------- | +| :---------- | :----------------------------------------------------------- | | HttpRequest | An **HttpRequest** object, which contains the **request**, **destroy**, **on**, or **off** method.| **Example** @@ -101,6 +107,22 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback | url | string | Yes | URL for initiating an HTTP request.| | callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | Yes | Callback used to return the result. | +**Error codes** + +| ID | Error Message | +|---------|-------------------------------------------------------| +| 401 | Parameter error. | +| 201 | Permission denied. | +| 2300003 | URL using bad/illegal format or missing URL. | +| 2300007 | Couldn't connect to server. | +| 2300028 | Timeout was reached. | +| 2300052 | Server returned nothing (no headers, no data). | +| 2300999 | Unknown Other Error. | + +>**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 @@ -118,7 +140,7 @@ httpRequest.request("EXAMPLE_URL", (err, data) => { ### request -request\(url: string, options: HttpRequestOptions, callback: AsyncCallback\):void +request\(url: string, options: HttpRequestOptions, callback: AsyncCallback\\):void Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result. @@ -134,6 +156,46 @@ Initiates an HTTP request containing specified options to a given URL. This API | options | HttpRequestOptions | Yes | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| | callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | Yes | Callback used to return the result. | +**Error codes** + +| ID | Error Message | +|---------|-------------------------------------------------------| +| 401 | Parameter error. | +| 201 | Permission denied. | +| 2300001 | Unsupported protocol. | +| 2300003 | URL using bad/illegal format or missing URL. | +| 2300005 | Couldn't resolve proxy name. | +| 2300006 | Couldn't resolve host name. | +| 2300007 | Couldn't connect to server. | +| 2300008 | Weird server reply. | +| 2300009 | Access denied to remote resource. | +| 2300016 | Error in the HTTP2 framing layer. | +| 2300018 | Transferred a partial file. | +| 2300023 | Failed writing received data to disk/application. | +| 2300025 | Upload failed. | +| 2300026 | Failed to open/read local data from file/application. | +| 2300027 | Out of memory. | +| 2300028 | Timeout was reached. | +| 2300047 | Number of redirects hit maximum amount. | +| 2300052 | Server returned nothing (no headers, no data). | +| 2300055 | Failed sending data to the peer. | +| 2300056 | Failure when receiving data from the peer. | +| 2300058 | Problem with the local SSL certificate. | +| 2300059 | Couldn't use specified SSL cipher. | +| 2300060 | SSL peer certificate or SSH remote key was not OK. | +| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.| +| 2300063 | Maximum file size exceeded. | +| 2300070 | Disk full or allocation exceeded. | +| 2300073 | Remote file already exists. | +| 2300077 | Problem with the SSL CA cert (path? access rights?). | +| 2300078 | Remote file not found. | +| 2300094 | An authentication function returned an error. | +| 2300999 | Unknown Other Error. | + +>**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 @@ -161,9 +223,9 @@ httpRequest.request("EXAMPLE_URL", ### request -request\(url: string, options? : HttpRequestOptions\): Promise +request\(url: string, options? : HttpRequestOptions\): Promise\ -Initiates an HTTP request to a given URL. This API uses a promise to return the result. +Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result. **Required permissions**: ohos.permission.INTERNET @@ -179,9 +241,48 @@ Initiates an HTTP request to a given URL. This API uses a promise to return the **Return value** | Type | Description | -| ------------------------------------- | -------------------------------- | +| :------------------------------------- | :-------------------------------- | | Promise<[HttpResponse](#httpresponse)> | Promise used to return the result.| +**Error codes** + +| ID | Error Message | +|---------|-------------------------------------------------------| +| 401 | Parameter error. | +| 201 | Permission denied. | +| 2300001 | Unsupported protocol. | +| 2300003 | URL using bad/illegal format or missing URL. | +| 2300005 | Couldn't resolve proxy name. | +| 2300006 | Couldn't resolve host name. | +| 2300007 | Couldn't connect to server. | +| 2300008 | Weird server reply. | +| 2300009 | Access denied to remote resource. | +| 2300016 | Error in the HTTP2 framing layer. | +| 2300018 | Transferred a partial file. | +| 2300023 | Failed writing received data to disk/application. | +| 2300025 | Upload failed. | +| 2300026 | Failed to open/read local data from file/application. | +| 2300027 | Out of memory. | +| 2300028 | Timeout was reached. | +| 2300047 | Number of redirects hit maximum amount. | +| 2300052 | Server returned nothing (no headers, no data). | +| 2300055 | Failed sending data to the peer. | +| 2300056 | Failure when receiving data from the peer. | +| 2300058 | Problem with the local SSL certificate. | +| 2300059 | Couldn't use specified SSL cipher. | +| 2300060 | SSL peer certificate or SSH remote key was not OK. | +| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.| +| 2300063 | Maximum file size exceeded. | +| 2300070 | Disk full or allocation exceeded. | +| 2300073 | Remote file already exists. | +| 2300077 | Problem with the SSL CA cert (path? access rights?). | +| 2300078 | Remote file not found. | +| 2300094 | An authentication function returned an error. | +| 2300999 | Unknown Other Error. | + +>**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** @@ -220,6 +321,209 @@ Destroys an HTTP request. httpRequest.destroy(); ``` +### request210+ + +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. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- | +| url | string | Yes | URL for initiating an HTTP request. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Error codes** + +| ID | Error Message | +|---------|-------------------------------------------------------| +| 401 | Parameter error. | +| 201 | Permission denied. | +| 2300003 | URL using bad/illegal format or missing URL. | +| 2300007 | Couldn't connect to server. | +| 2300028 | Timeout was reached. | +| 2300052 | Server returned nothing (no headers, no data). | +| 2300999 | Unknown Other Error. | + +>**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 +httpRequest.request2("EXAMPLE_URL", (err) => { + if (!err) { + console.info(request2 OK!); + } else { + console.info("request2 ERROR : err = " + JSON.stringify(err)); + } +}) +``` + +### request210+ + +request2(url: string, options: HttpRequestOptions, callback: AsyncCallback): void + +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 + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- | +| url | string | Yes | URL for initiating an HTTP request. | +| options | HttpRequestOptions | Yes | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Error codes** + +| ID | Error Message | +|---------|-------------------------------------------------------| +| 401 | Parameter error. | +| 201 | Permission denied. | +| 2300001 | Unsupported protocol. | +| 2300003 | URL using bad/illegal format or missing URL. | +| 2300005 | Couldn't resolve proxy name. | +| 2300006 | Couldn't resolve host name. | +| 2300007 | Couldn't connect to server. | +| 2300008 | Weird server reply. | +| 2300009 | Access denied to remote resource. | +| 2300016 | Error in the HTTP2 framing layer. | +| 2300018 | Transferred a partial file. | +| 2300023 | Failed writing received data to disk/application. | +| 2300025 | Upload failed. | +| 2300026 | Failed to open/read local data from file/application. | +| 2300027 | Out of memory. | +| 2300028 | Timeout was reached. | +| 2300047 | Number of redirects hit maximum amount. | +| 2300052 | Server returned nothing (no headers, no data). | +| 2300055 | Failed sending data to the peer. | +| 2300056 | Failure when receiving data from the peer. | +| 2300058 | Problem with the local SSL certificate. | +| 2300059 | Couldn't use specified SSL cipher. | +| 2300060 | SSL peer certificate or SSH remote key was not OK. | +| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.| +| 2300063 | Maximum file size exceeded. | +| 2300070 | Disk full or allocation exceeded. | +| 2300073 | Remote file already exists. | +| 2300077 | Problem with the SSL CA cert (path? access rights?). | +| 2300078 | Remote file not found. | +| 2300094 | An authentication function returned an error. | +| 2300999 | Unknown Other Error. | + +>**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 +httpRequest.request2("EXAMPLE_URL", +{ + method: http.RequestMethod.GET, + header: { + 'Content-Type': 'application/json' + }, + readTimeout: 60000, + connectTimeout: 60000 +}, (err) => { + if (!err) { + console.info(request2 OK!); + } else { + console.info("request2 ERROR : err = " + JSON.stringify(err)); + } +}) +``` +### request210+ + +request2\(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, which is a streaming response. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------ | ---- | ----------------------------------------------- | +| url | string | Yes | URL for initiating an HTTP request. | +| options | HttpRequestOptions | No | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| + +**Return value** + +| Type | Description | +| :------------------------------------- | :-------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID | Error Message | +|---------|-------------------------------------------------------| +| 401 | Parameter error. | +| 201 | Permission denied. | +| 2300001 | Unsupported protocol. | +| 2300003 | URL using bad/illegal format or missing URL. | +| 2300005 | Couldn't resolve proxy name. | +| 2300006 | Couldn't resolve host name. | +| 2300007 | Couldn't connect to server. | +| 2300008 | Weird server reply. | +| 2300009 | Access denied to remote resource. | +| 2300016 | Error in the HTTP2 framing layer. | +| 2300018 | Transferred a partial file. | +| 2300023 | Failed writing received data to disk/application. | +| 2300025 | Upload failed. | +| 2300026 | Failed to open/read local data from file/application. | +| 2300027 | Out of memory. | +| 2300028 | Timeout was reached. | +| 2300047 | Number of redirects hit maximum amount. | +| 2300052 | Server returned nothing (no headers, no data). | +| 2300055 | Failed sending data to the peer. | +| 2300056 | Failure when receiving data from the peer. | +| 2300058 | Problem with the local SSL certificate. | +| 2300059 | Couldn't use specified SSL cipher. | +| 2300060 | SSL peer certificate or SSH remote key was not OK. | +| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.| +| 2300063 | Maximum file size exceeded. | +| 2300070 | Disk full or allocation exceeded. | +| 2300073 | Remote file already exists. | +| 2300077 | Problem with the SSL CA cert (path? access rights?). | +| 2300078 | Remote file not found. | +| 2300094 | An authentication function returned an error. | +| 2300999 | Unknown Other Error. | + +>**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: + +**Example** + +```js +let promise = httpRequest.request("EXAMPLE_URL", { + method: http.RequestMethod.GET, + connectTimeout: 60000, + readTimeout: 60000, + header: { + 'Content-Type': 'application/json' + } +}); +promise.then(() => { + console.info(request2 OK!); +}).catch((err) => { + console.info("request2 ERROR : err = " + JSON.stringify(err)); +}); +``` + ### on\('headerReceive'\) on\(type: 'headerReceive', callback: AsyncCallback\): void @@ -346,7 +650,148 @@ httpRequest.once('headersReceive', (header) => { console.info('header: ' + JSON.stringify(header)); }); ``` +### on\('dataReceive'\)10+ + +on\(type: 'dataReceive', callback: Callback\\): void + +Registers an observer for events indicating receiving of HTTP streaming responses. +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | --------------------------------- | +| type | string | Yes | Event type. The value is **dataReceive**.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +httpRequest.on('dataReceive', (data) => { + console.info('dataReceive length: ' + JSON.stringify(data.byteLength)); +}); +``` + +### off\('dataReceive'\)10+ + +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. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------ | ---- | -------------------------------------- | +| type | string | Yes | Event type. The value is **dataReceive**.| +| callback | Callback\ | No | Callback used to return the result. | + +**Example** + +```js +httpRequest.off('dataReceive'); +``` + +### on\('dataEnd'\)10+ + +on\(type: 'dataEnd', callback: Callback\\): void + +Registers an observer for events indicating completion of receiving HTTP streaming responses. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | --------------------------------- | +| type | string | Yes | Event type. The value is **dataEnd**.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +httpRequest.on('dataReceive', () => { + console.info('Receive dataEnd! '); +}); +``` + +### off\('dataEnd'\)10+ + +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. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------ | ---- | -------------------------------------- | +| type | string | Yes | Event type. The value is **dataEnd**.| +| callback | Callback\ | No | Callback used to return the result. | + +**Example** + +```js +httpRequest.off('dataEnd'); +``` + +### on\('dataProgress'\)10+ + + on\(type: 'dataProgress', callback: Callback\<{ receiveSize: number, totalSize: number }\>\): void + +Registers an observer for events indicating progress of receiving HTTP streaming responses. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| 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. | + +**Example** + +```js +httpRequest.on('dataProgress', (data) => { + if (!err) { + console.info('dataProgress:' + JSON.stringify(data)); + } +}); +``` + +### off\('dataProgress'\)10+ + +off(type: 'dataProgress', callback?: Callback\<{ receiveSize: number, totalSize: number }\>): void + +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. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------ | ---- | -------------------------------------- | +| type | string | Yes | Event type. The value is **dataProgress**.| +| callback | Callback\<{ receiveSize: number, totalSize: number }\> | No | Callback used to return the result. | + +**Example** + +```js +httpRequest.off('dataProgress'); +``` ## HttpRequestOptions Specifies the type and value range of the optional parameters in the HTTP request. @@ -357,13 +802,14 @@ Specifies the type and value range of the optional parameters in the HTTP reques | -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | | 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.| +| expectDataType9+ | [HttpDataType](#httpdatatype9) | No | Type of the return data. 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**. | -| 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. | -| usingProtocol9+ | [HttpProtocol](#httpprotocol9) | No | Protocol. The default value is automatically specified by the system. | +| 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. | +| usingProtocol9+ | [HttpProtocol](#httpprotocol9) | No | Protocol. The default value is automatically specified by the system. | +| usingProxy10+ | boolean \| Object | No | Whether to use HTTP proxy. The default value is **false**, which means not to use HTTP proxy.
- If **usingProxy** is of the **Boolean** type and the value is **true**, network proxy is used by default.
- If **usingProxy** is of the **object** type, the specified network proxy is used. | ## RequestMethod @@ -372,7 +818,7 @@ Defines an HTTP request method. **System capability**: SystemCapability.Communication.NetStack | Name | Value | Description | -| ------ | ------- | ------------------ | +| :------ | ------- | :------------------ | | OPTIONS | "OPTIONS" | OPTIONS method.| | GET | "GET" | GET method. | | HEAD | "HEAD" | HEAD method. | @@ -390,7 +836,7 @@ Enumerates the response codes for an HTTP request. | Name | Value | Description | | ----------------- | ---- | ------------------------------------------------------------ | -| OK | 200 | The request is successful. The request has been processed successfully. This return code is generally used for GET and POST requests. | +| OK | 200 | "OK." The request has been processed successfully. This return code is generally used for GET and POST requests. | | CREATED | 201 | "Created." The request has been successfully sent and a new resource is created. | | ACCEPTED | 202 | "Accepted." The request has been accepted, but the processing has not been completed. | | NOT_AUTHORITATIVE | 203 | "Non-Authoritative Information." The request is successful. | @@ -436,9 +882,9 @@ Defines the response to an HTTP request. | -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | | 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| | 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**. For details, see [Error Codes](#error-codes).| +| 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'];| -| cookies8+ | Array\ | Yes | Cookies returned by the server. | +| cookies8+ | string | Yes | Cookies returned by the server. | ## http.createHttpResponseCache9+ @@ -457,7 +903,7 @@ Creates a default object to store responses to HTTP access requests. **Return value** | Type | Description | -| ---------- | ----------------------------------------------------------- | +| :---------- | :----------------------------------------------------------- | | [HttpResponseCache](#httpresponsecache9) | Object that stores the response to the HTTP request.| **Example** @@ -490,10 +936,10 @@ Flushes data in the cache to the file system so that the cached data can be acce ```js httpResponseCache.flush(err => { if (err) { - console.log('flush fail'); + console.info('flush fail'); return; } - console.log('flush success'); + console.info('flush success'); }); ``` @@ -515,9 +961,9 @@ Flushes data in the cache to the file system so that the cached data can be acce ```js httpResponseCache.flush().then(() => { - console.log('flush success'); + console.info('flush success'); }).catch(err => { - console.log('flush fail'); + console.info('flush fail'); }); ``` @@ -540,10 +986,10 @@ Disables the cache and deletes the data in it. This API uses an asynchronous cal ```js httpResponseCache.delete(err => { if (err) { - console.log('delete fail'); + console.info('delete fail'); return; } - console.log('delete success'); + console.info('delete success'); }); ``` ### delete9+ @@ -558,31 +1004,18 @@ Disables the cache and deletes the data in it. This API uses a promise to return | Type | Description | | --------------------------------- | ------------------------------------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Example** ```js httpResponseCache.delete().then(() => { - console.log('delete success'); + console.info('delete success'); }).catch(err => { - console.log('delete fail'); + console.info('delete fail'); }); ``` -## Error Codes - -| Error Code| Description | -| ------ | ------------------------------------------------------------ | -| -1 | Incorrect parameter. Check whether the number and type of parameters are correct. | -| 3 | Incorrect URL format. Check whether the format and syntax of the URL are correct. | -| 4 | Built-in request function, protocol, or option not found during build. If a function or option is not enabled or explicitly disabled, you need to rebuild a libcurl in order to access its functions. | -| 5 | Unable to resolve the proxy because of a failure to resolve the specified proxy server. You are advised perform the following: 1. Check whether the URL is correct. 2. Check whether the network connection is normal and whether the network can communicate with external networks. 3. Check whether the network access permission is available. | -| 6 | Unable to resolve the host because of a failure to resolve the specified remote host. You are advised perform the following: 1. Check whether the URL is correct. 2. Check whether the network connection is normal and whether the network can communicate with external networks. 3. Check whether the network access permission is available. | -| 7 | Unable to connect to the proxy or host. You are advised perform the following: 1. Check whether the port number is correct. 2. Check whether the HTTP proxy is enabled on the local host. | - -For details about the error codes, see [Curl Error Codes] (https://curl.se/libcurl/c/libcurl-errors.html). - ## HttpDataType9+ Enumerates HTTP data types. @@ -602,6 +1035,6 @@ Enumerates HTTP protocol versions. **System capability**: SystemCapability.Communication.NetStack | Name | Description | -| -------- | ----------- | +| :-------- | :----------- | | HTTP1_1 | HTTP1.1 | | HTTP2 | HTTP2 | 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 d41845ec18..3445952a9c 100644 --- a/en/application-dev/reference/apis/js-apis-net-ethernet.md +++ b/en/application-dev/reference/apis/js-apis-net-ethernet.md @@ -1,8 +1,8 @@ -# @ohos.net.ethernet (Ethernet Connection Management) +# # @ohos.net.ethernet (Ethernet Connection Management) The **ethernet** module provides wired network capabilities, which allow users to set the IP address, subnet mask, gateway, and Domain Name System (DNS) server of a wired network. -> **NOTE**
+> **NOTE** > 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. ## Modules to Import @@ -17,30 +17,51 @@ setIfaceConfig(iface: string, ic: InterfaceConfiguration, callback: AsyncCallbac Sets the network interface configuration. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.Ethernet **Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------- | ---- | ------------------------------------------ | -| iface | string | Yes | Name of the network interface. | +| iface | string | Yes | Interface name. | | ic | [InterfaceConfiguration](#interfaceconfiguration) | Yes | Network interface configuration to set. | | callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the return result is empty. If the operation fails, an error code is returned.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------------------| +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service.| +| 2200003 | System internal error. | +| 2201005 | The device information does not exist. | +| 2201006 | Device disconnected. | +| 2201007 | Failed to write the user configuration. | + **Example** ```js -ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.1.123", routeAddr:"192.168.1.1", - gateAddr:"192.168.1.1", maskAddr:"255.255.255.0", dnsAddr0:"1.1.1.1", dnsAddr1:"2.2.2.2"}, - (error) => { - if (error) { - console.log("setIfaceConfig callback error = " + error); - } else { - console.log("setIfaceConfig callback ok "); - } - }); +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" +}, (error) => { + if (error) { + console.log("setIfaceConfig callback error = " + JSON.stringify(error)); + } else { + console.log("setIfaceConfig callback ok "); + } +}); ``` ## ethernet.setIfaceConfig @@ -49,31 +70,53 @@ setIfaceConfig(iface: string, ic: InterfaceConfiguration): Promise\ Sets the network interface configuration. This API uses a promise to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.Ethernet **Parameters** | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------- | ---- | ------------------------ | -| iface | string | Yes | Name of the network interface. | +| iface | string | Yes | Interface name. | | ic | [InterfaceConfiguration](#interfaceconfiguration) | Yes | Network interface configuration to set.| **Return value** | Type | Description | | ------------------- | ----------------------------------------------------------- | -| Promise\ | Promise that returns no value.| +| Promise\ | Promise used to return the result. If the operation is successful, the return result is empty. If the operation fails, an error code is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------------------| +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service.| +| 2200003 | System internal error. | +| 2201005 | The device information does not exist. | +| 2201006 | Device disconnected. | +| 2201007 | Failed to write the user configuration. | **Example** ```js -ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.1.123", routeAddr:"192.168.1.1", - gateAddr:"192.168.1.1", maskAddr:"255.255.255.0", dnsAddr0:"1.1.1.1", dnsAddr1:"2.2.2.2"}).then(() => { +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" +}).then(() => { console.log("setIfaceConfig promiss ok "); -}).catch((error) => { - console.log("setIfaceConfig promiss error = " + error); +}).catch(error => { + console.log("setIfaceConfig promiss error = " + JSON.stringify(error)); }); ``` @@ -83,31 +126,44 @@ getIfaceConfig(iface: string, callback: AsyncCallback\): Obtains the configuration of a network interface. 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.Core +**System capability**: SystemCapability.Communication.NetManager.Ethernet **Parameters** | Name | Type | Mandatory | Description | | -------- | ----------------------------------------------- | ----- | ------------ | -| iface | string | Yes | Name of the network interface.| -| callback | AsyncCallback\<[InterfaceConfiguration](#interfaceconfiguration)> | Yes | Callback used to return the configuration. | +| iface | string | Yes | Interface name.| +| callback | AsyncCallback\<[InterfaceConfiguration](#interfaceconfiguration)> | Yes | Callback used to return the result. | + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------------------| +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service.| +| 2200003 | System internal error. | +| 2201005 | The device information does not exist. | **Example** ```js ethernet.getIfaceConfig("eth0", (error, value) => { if (error) { - console.log("getIfaceConfig callback error = " + error); + console.log("getIfaceConfig callback error = " + JSON.stringify(error)); } else { - console.log("getIfaceConfig callback mode = " + value.mode); - console.log("getIfaceConfig callback ipAddr = " + value.ipAddr); - console.log("getIfaceConfig callback routeAddr = " + value.routeAddr); - console.log("getIfaceConfig callback gateAddr = " + value.gateAddr); - console.log("getIfaceConfig callback maskAddr = " + value.maskAddr); - console.log("getIfaceConfig callback dns0Addr = " + value.dns0Addr); - console.log("getIfaceConfig callback dns1Addr = " + value.dns1Addr); + 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)); } }); ``` @@ -118,64 +174,90 @@ getIfaceConfig(iface: string): Promise\ Obtains the configuration of a network interface. This API uses a promise to return the result. +**System API**: This is a system API. + **Required permission**: ohos.permission.GET_NETWORK_INFO -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.Ethernet **Parameters** | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ------------ | -| iface | string | Yes | Name of the network interface.| +| iface | string | Yes | Interface name.| **Return value** | Type | Description | | --------------------------------- | ---------------------------------- | -| Promise\<[InterfaceConfiguration](#interfaceconfiguration)> | Promise used to return the configuration. | +| Promise\<[InterfaceConfiguration](#interfaceconfiguration)> | Promise used to return the result. | + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------------------| +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service.| +| 2200003 | System internal error. | +| 2201005 | The device information does not exist. | **Example** ```js ethernet.getIfaceConfig("eth0").then((data) => { - console.log("getIfaceConfig promiss mode = " + data.mode); - console.log("getIfaceConfig promiss ipAddr = " + data.ipAddr); - console.log("getIfaceConfig promiss routeAddr = " + data.routeAddr); - console.log("getIfaceConfig promiss gateAddr = " + data.gateAddr); - console.log("getIfaceConfig promiss maskAddr = " + data.maskAddr); - console.log("getIfaceConfig promiss dns0Addr = " + data.dns0Addr); - console.log("getIfaceConfig promiss dns1Addr = " + data.dns1Addr); -}).catch((error) => { - console.log("getIfaceConfig promiss error = " + error); + console.log("getIfaceConfig promiss mode = " + JSON.stringify(data.mode)); + console.log("getIfaceConfig promiss ipAddr = " + JSON.stringify(data.ipAddr)); + console.log("getIfaceConfig promiss route = " + JSON.stringify(data.route)); + console.log("getIfaceConfig promiss gateway = " + JSON.stringify(data.gateway)); + console.log("getIfaceConfig promiss netMask = " + JSON.stringify(data.netMask)); + console.log("getIfaceConfig promiss dnsServers = " + JSON.stringify(data.dnsServers)); + console.log("getIfaceConfig promiss domain = " + JSON.stringify(data.domain)); +}).catch(error => { + console.log("getIfaceConfig promiss error = " + JSON.stringify(error)); }); ``` ## ethernet.isIfaceActive -isIfaceActive(iface?: string, callback: AsyncCallback\): void +isIfaceActive(iface: string, callback: AsyncCallback\): void Checks whether a network interface is active. 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.Core +**System capability**: SystemCapability.Communication.NetManager.Ethernet **Parameters** | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | -------------------------------------------------- | -| iface | string | Yes | Name of the network interface. If this parameter is left empty, the API checks for any active network interface. | +| iface | string | Yes | Interface name. If this parameter is left empty, the API checks for any active network interface. | | callback | AsyncCallback\ | Yes | Callback used to return the result. The value **1** means that the network interface is active, **0** means that the network interface is inactive, and any other value means that an error has occurred.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------------------| +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service.| +| 2200003 | System internal error. | +| 2201005 | The device information does not exist. | + **Example** ```js ethernet.isIfaceActive("eth0", (error, value) => { - if (error) { - console.log("whether2Activate callback error = " + error); - } else { - console.log("whether2Activate callback = " + value); - } + if (error) { + console.log("whether2Activate callback error = " + JSON.stringify(error)); + } else { + console.log("whether2Activate callback = " + JSON.stringify(value)); + } }); ``` @@ -185,15 +267,17 @@ isIfaceActive(iface: string): Promise\ Checks whether a network interface is active. This API uses a promise to return the result. +**System API**: This is a system API. + **Required permission**: ohos.permission.GET_NETWORK_INFO -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.Ethernet **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | -| iface | string | Yes | Name of the network interface. If this parameter is left empty, the API checks for any active network interface.| +| iface | string | Yes | Interface name. If this parameter is left empty, the API checks for any active network interface.| **Return value** @@ -201,13 +285,24 @@ Checks whether a network interface is active. This API uses a promise to return | ----------------| ------------------------------------------------------------------ | | Promise\ | Promise used to return the result. The value **1** means that the network interface is active, **0** means that the network interface is inactive, and any other value means that an error has occurred.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------------------| +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service.| +| 2200003 | System internal error. | +| 2201005 | The device information does not exist. | + **Example** ```js ethernet.isIfaceActive("eth0").then((data) => { - console.log("isIfaceActive promiss = " + data); -}).catch((error) => { - console.log("isIfaceActive promiss error = " + error); + console.log("isIfaceActive promiss = " + JSON.stringify(data)); +}).catch(error => { + console.log("isIfaceActive promiss error = " + JSON.stringify(error)); }); ``` @@ -215,30 +310,40 @@ ethernet.isIfaceActive("eth0").then((data) => { getAllActiveIfaces(callback: AsyncCallback\>): void -Obtains all active network interfaces. This API uses an asynchronous callback to return the result. +Obtains the list of all active network interfaces. 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.Core +**System capability**: SystemCapability.Communication.NetManager.Ethernet **Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------------------ | ---- | ------------------------------ | -| callback | AsyncCallback\> | Yes | Callback used to return all the active network interface names obtained.| +| callback | AsyncCallback\> | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------------------| +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service.| +| 2200003 | System internal error. | **Example** ```js ethernet.getAllActiveIfaces((error, value) => { - if (error) { - console.log("getAllActiveIfaces callback error = " + error); - } else { - console.log("getAllActiveIfaces callback value.length = " + value.length); - for (let i = 0; i < value.length; i++) { - console.log("getAllActiveIfaces callback = " + 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])); + } } - } }); ``` @@ -246,30 +351,38 @@ ethernet.getAllActiveIfaces((error, value) => { getAllActiveIfaces(): Promise\> -Obtains all active network interfaces. This API uses a promise to return the result. +Obtains the list of all active network interfaces. This API uses a promise to return the result. -**Required permission**: ohos.permission.GET_NETWORK_INFO +**System API**: This is a system API. -**System capability**: SystemCapability.Communication.NetManager.Core +**Required permission**: ohos.permission.GET_NETWORK_INFO -**Parameters** +**System capability**: SystemCapability.Communication.NetManager.Ethernet **Return value** | Type | Description | | ------------------------------ | ----------------------------------------------- | -| Promise\> | Promise used to return all the active network interface names obtained.| +| Promise\> | Promise used to return the result. | + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------------------| +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service.| +| 2200003 | System internal error. | **Example** ```js ethernet.getAllActiveIfaces().then((data) => { - console.log("getAllActiveIfaces promiss data.length = " + data.length); - for (let i = 0; i < data.length; i++) { - console.log("getAllActiveIfaces promiss = " + data[i]); - } -}).catch((error) => { - console.log("getAllActiveIfaces promiss error = " + error); + console.log("getAllActiveIfaces promiss data.length = " + JSON.stringify(data.length)); + for (let i = 0; i < data.length; i++) { + console.log("getAllActiveIfaces promiss = " + JSON.stringify(data[i])); + } +}).catch(error => { + console.log("getAllActiveIfaces promiss error = " + JSON.stringify(error)); }); ``` @@ -277,22 +390,26 @@ ethernet.getAllActiveIfaces().then((data) => { Defines the network configuration for the Ethernet connection. -**System capability**: SystemCapability.Communication.NetManager.Core +**System API**: This is a system API. -| Name | Type | Mandatory | Description | -| -------- | ------- | --------- | ----------- | -| mode | [IPSetMode](#ipsetmode) | Yes | Configuration mode of the Ethernet connection.| -| ipAddr | string | Yes | Static IP address of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in Dynamic Host Configuration Protocol (DHCP) mode.| -| route | string | Yes | Route of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.| -| gateway | string | Yes | Gateway of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.| -| netMask | string | Yes | Subnet mask of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.| -| dnsServers | string | Yes | DNS server addresses of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode. Multiple addresses are separated by commas (,).| +**System capability**: SystemCapability.Communication.NetManager.Ethernet + +| Name | Type | Mandatory| Description | +| ------------ | ----------------------- | ---|------------------------------------------------------------ | +| mode | [IPSetMode](#ipsetmode) | Yes| Configuration mode of the Ethernet connection.| +| ipAddr | string | Yes| Static IP address of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in Dynamic Host Configuration Protocol (DHCP) mode.| +| route | string | Yes| Route of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in DHCP mode.| +| gateway | string | Yes| Gateway of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in DHCP mode.| +| netMask | string | Yes| Subnet mask of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in DHCP mode.| +| dnsServers | string | Yes| DNS server addresses of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode. Multiple addresses are separated by commas (,).| ## IPSetMode Defines the configuration mode of the Ethernet connection. -**System capability**: SystemCapability.Communication.NetManager.Core +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.NetManager.Ethernet | Name | Value | Description | | ------------------------ | ---- | ---------------------- | diff --git a/en/application-dev/reference/apis/js-apis-net-policy.md b/en/application-dev/reference/apis/js-apis-net-policy.md new file mode 100644 index 0000000000..375ee31e24 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-net-policy.md @@ -0,0 +1,1558 @@ +# @ohos.net.policy (Network Policy Management) + +The **policy** module provides APIs for managing network policies, through which you can control and manage the data volume used. + +> **NOTE** +> +> 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. + +## Modules to Import + +```js +import policy from '@ohos.net.policy' +``` + +## policy.setBackgroundPolicy + +setBackgroundPolicy(isAllowed: boolean, callback: AsyncCallback\): void + +Sets a background network policy. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| isAllowed | boolean | Yes | Whether applications running in the background are allowed to use mobile data.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))), (error, data) => { + this.callBack(error, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}); +``` + +## policy.setBackgroundPolicy + +setBackgroundPolicy(isAllowed: boolean): Promise\ + +Sets a background network policy. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| isAllowed | boolean | Yes | Whether applications running in the background are allowed to use mobile data.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.| + +**Example** + +```js +policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## policy.isBackgroundAllowed + +isBackgroundAllowed(callback: AsyncCallback\): void + +Obtains the background network policy. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **true** is returned, which means that applications running in the background are allowed to use mobile data. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +policy.isBackgroundAllowed((error, data) => { + this.callBack(error, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}); +``` + +## policy.isBackgroundAllowed + +isBackgroundAllowed(): Promise\; + +Obtains the background network policy. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result. If the operation is successful, **true** is returned, which means that applications running in the background are allowed to use mobile data. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +policy.isBackgroundAllowed().then(function(error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.setPolicyByUid + +setPolicyByUid(uid: number, policy: NetUidPolicy, callback: AsyncCallback\): void + +Sets an application-specific network policy. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes | Unique ID of the application.| +| policy | [NetUidPolicy](#netuidpolicy) | Yes| Application-specific network policy to set.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +let param = { + 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); +}); +``` + +## policy.setPolicyByUid + +setPolicyByUid(uid: number, policy: NetUidPolicy): Promise\; + +Sets an application-specific network policy. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes | Unique ID of the application.| +| policy | [NetUidPolicy](#netuidpolicy) | Yes| Application-specific network policy to set.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +let param = { + 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.getPolicyByUid + +getPolicyByUid(uid: number, callback: AsyncCallback\): void + +Obtains an application-specific network policy by **uid**. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| callback | AsyncCallback\<[NetUidPolicy](#netuidpolicy)> | Yes | Callback used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +policy.getPolicyByUid(Number.parseInt(this.firstParam), (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.getPolicyByUid + +getPolicyByUid(uid: number): Promise\; + +Obtains an application-specific network policy by **uid**. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\<[NetUidPolicy](#netuidpolicy)> | Promise used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +policy.getPolicyByUid(Number.parseInt(this.firstParam)).then(function(error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.getUidsByPolicy + +getUidsByPolicy(policy: NetUidPolicy, callback: AsyncCallback\>): void + +Obtains the UID array of applications configured with a certain application-specific network policy. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| policy | [NetUidPolicy](#netuidpolicy) | Yes| Target application-specific network policy.| +| callback | AsyncCallback\> | Yes | Callback used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +policy.getUidsByPolicy(Number.parseInt(this.currentNetUidPolicy), (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.getUidsByPolicy + +function getUidsByPolicy(policy: NetUidPolicy): Promise\>; + +Obtains the UID array of applications configured with a certain application-specific network policy. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| policy | [NetUidPolicy](#netuidpolicy) | Yes| Target application-specific network policy.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\> | Promise used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function(error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.getNetQuotaPolicies + +getNetQuotaPolicies(callback: AsyncCallback\>): void + +Obtains the network quota policies. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\> | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +policy.getNetQuotaPolicies((error, data) => { + this.callBack(error, data); +}); +``` + +## policy.getNetQuotaPolicies + +getNetQuotaPolicies(): Promise\>; + +Obtains the network quota policies. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\> | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +policy.getNetQuotaPolicies().then(function(error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.setNetQuotaPolicies + +setNetQuotaPolicies(quotaPolicies: Array\, callback: AsyncCallback\): void + +Sets an array of network quota policies. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| quotaPolicies | Array\<[NetQuotaPolicy](#netquotapolicy)> | Yes| An array of network quota policies to set.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**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}; +this.netQuotaPolicyList.push(param); + +policy.setNetQuotaPolicies(this.netQuotaPolicyList, (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.setNetQuotaPolicies + +setNetQuotaPolicies(quotaPolicies: Array\): Promise\; + +Sets an array of network quota policies. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| quotaPolicies | Array\<[NetQuotaPolicy](#netquotapolicy)> | Yes| An array of network quota policies to set.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**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}; +this.netQuotaPolicyList.push(param); + +policy.setNetQuotaPolicies(this.netQuotaPolicyList).then(function(error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## policy.restoreAllPolicies + +restoreAllPolicies(iccid: string, callback: AsyncCallback\): void + +Restores all the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| iccid | string | Yes| SIM card ID.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +this.firstParam = iccid; +policy.restoreAllPolicies(this.firstParam, (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.restoreAllPolicies + +restoreAllPolicies(iccid: string): Promise\; + +Restores all the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| iccid | string | Yes| SIM card ID.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +this.firstParam = iccid; +policy.restoreAllPolicies(this.firstParam).then(function(error, data){ + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.isUidNetAllowed + +isUidNetAllowed(uid: number, isMetered: boolean, callback: AsyncCallback\): void + +Checks whether an application is allowed to access metered networks. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| isMetered | boolean | Yes| Whether the network is a metered network.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that the application is allowed to access metered networks, and **false** means the opposite.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js + +let param = { + 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); +}); +``` + +## policy.isUidNetAllowed + +isUidNetAllowed(uid: number, isMetered: boolean): Promise\; + +Checks whether an application is allowed to access metered networks. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| isMetered | boolean | Yes| Whether the network is a metered network.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js + +let param = { + 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 + +isUidNetAllowed(uid: number, iface: string, callback: AsyncCallback\): void + +Checks whether an application is allowed to access the given network. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| iface | string | Yes| Name of the target network.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that the application is allowed to access the given network, and **false** means the opposite.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js + +let param = { + uid: Number.parseInt(this.firstParam), iface: this.secondParam +} +policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam, (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.isUidNetAllowed + +isUidNetAllowed(uid: number, iface: string): Promise\; + +Checks whether an application is allowed to access the given network. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| iface | string | Yes| Name of the target network.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +let param = { + 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.setDeviceIdleAllowList + +setDeviceIdleAllowList(uid: number, isAllowed: boolean, callback: AsyncCallback\): void + +Sets whether to add an application to the device idle allowlist. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| isAllowed | boolean | Yes| Whether to add the application to the allowlist.| +| callback | callback: AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +let param = { + 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); +}); +``` + +## policy.setDeviceIdleAllowList + +setDeviceIdleAllowList(uid: number, isAllowed: boolean): Promise\; + +Sets whether to add an application to the device idle allowlist. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| isAllowed | boolean | Yes| Whether to add the application to the allowlist.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +let param = { + 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.getDeviceIdleAllowList + +getDeviceIdleAllowList(callback: AsyncCallback\>): void + +Obtains the UID array of applications that are on the device idle allowlist. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\> | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +policy.getDeviceIdleAllowList((error, data) => { + this.callBack(error, data); +}); +``` + +## policy.getDeviceIdleAllowList + +getDeviceIdleAllowList(): Promise\>; + +Obtains the UID array of applications that are on the device idle allowlist. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\> | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +policy.getDeviceIdleAllowList().then(function(error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## policy.getBackgroundPolicyByUid + +getBackgroundPolicyByUid(uid: number, callback: AsyncCallback\): void + +Obtains the background network policies configured for the given application. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| callback | AsyncCallback\<[NetBackgroundPolicy](#netbackgroundpolicy)> | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +this.firstParam = uid +policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam), (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.getBackgroundPolicyByUid + +getBackgroundPolicyByUid(uid: number): Promise\; + +Obtains the background network policies configured for the given application. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\<[NetBackgroundPolicy](#netbackgroundpolicy)> | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```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.resetPolicies + +resetPolicies(iccid: string, callback: AsyncCallback\): void + +Restores all the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| iccid | string | Yes| SIM card ID.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +this.firstParam = iccid +policy.resetPolicies(this.firstParam, (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.resetPolicies + +resetPolicies(iccid: string): Promise\; + +Restores all the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| iccid | string | Yes| SIM card ID.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +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.updateRemindPolicy + +updateRemindPolicy(netType: NetBearType, iccid: string, remindType: RemindType, callback: AsyncCallback\): void + +Updates a reminder policy. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| netType | [NetBearType](js-apis-net-connection.md#netbeartype) | Yes| Network type.| +| iccid | string | Yes| SIM card ID.| +| remindType | [RemindType](#remindtype) | Yes| Reminder type.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +let param = { + 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); +}); +``` + +## policy.updateRemindPolicy + +updateRemindPolicy(netType: NetBearType, iccid: string, remindType: RemindType): Promise\; + +Updates a reminder policy. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| netType | [NetBearType](js-apis-net-connection.md#netbeartype) | Yes| Network type.| +| iccid | string | Yes| SIM card ID.| +| remindType | [RemindType](#remindtype) | Yes| Reminder type.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +let param = { + 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.setPowerSaveAllowList + +setPowerSaveAllowList(uid: number, isAllowed: boolean, callback: AsyncCallback\): void + +Sets whether to add an application to the power-saving allowlist. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| isAllowed | boolean | Yes| Whether to add the application to the allowlist.| +| callback | callback: AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +let param = { + 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); +}); +``` + +## policy.setPowerSaveAllowList + +setPowerSaveAllowList(uid: number, isAllowed: boolean): Promise\; + +Sets whether to add an application to the power-saving allowlist. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| isAllowed | boolean | Yes| Whether to add the application to the allowlist.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +let param = { + 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.getPowerSaveAllowList + +getPowerSaveAllowList(callback: AsyncCallback\>): void + +Obtains the UID array of applications that are on the power-saving allowlist. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\> | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +policy.getPowerSaveAllowList((error, data) => { + this.callBack(error, data); +}); +``` + +## policy.getPowerSaveAllowList + +getPowerSaveAllowList(): Promise\>; + +Obtains the UID array of applications that are on the device idle allowlist. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\> | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**Example** + +```js +policy.getPowerSaveAllowList().then(function(error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## policy.on + +Functions as the handle to a network policy. + +### on('netUidPolicyChange') + +on(type: "netUidPolicyChange", callback: Callback\<{ uid: number, policy: NetUidPolicy }>): void + +Subscribes to policy changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netUidPolicyChange | Yes| Event type. The value **netUidPolicyChange** indicates a policy change event.| +| callback | Callback\<{ uid: number, policy: [NetUidPolicy](#netuidpolicy) }> | Yes | Callback used to return the result. It is called when the registered network policy changes.| + +**Example** + +```js +policy.on('netUidPolicyChange', (data) => { + this.log('on netUidPolicyChange: ' + JSON.stringify(data)); +}) +``` + +### on('netUidRuleChange') + +on(type: "netUidRuleChange", callback: Callback\<{ uid: number, rule: NetUidRule }>): void + +Subscribes to rule changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netUidRuleChange | Yes| Event type. The value **netUidRuleChange** indicates a rule change event.| +| callback | Callback\<{ uid: number, rule: [NetUidRule](#netuidrule) }> | Yes | Callback used to return the result. It is called when the registered rule changes.| + +**Example** + +```js +policy.on('netUidRuleChange', (data) => { + this.log('on netUidRuleChange: ' + JSON.stringify(data)); +}) +``` + +### on('netMeteredIfacesChange') + +on(type: "netMeteredIfacesChange", callback: Callback\>): void + +Subscribes to metered **iface** changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netMeteredIfacesChange | Yes| Event type. The value **netMeteredIfacesChange** indicates a metered **iface** change event.| +| callback | Callback\> | Yes | Callback used to return the result. It is called when the registered metered **iface** changes.| + +**Example** + +```js +policy.on('netMeteredIfacesChange', (data) => { + this.log('on netMeteredIfacesChange: ' + JSON.stringify(data)); +}) +``` + +### on('netQuotaPolicyChange') + +on(type: "netQuotaPolicyChange", callback: Callback\>): void + +Subscribes to network quota policy changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netQuotaPolicyChange | Yes| Event type. The value **netQuotaPolicyChange** indicates a network quota policy change event.| +| callback | Callback\> | Yes | Callback used to return the result. It is called when the registered network quota policy changes.| + +**Example** + +```js +policy.on('netQuotaPolicyChange', (data) => { + this.log('on netQuotaPolicyChange: ' + JSON.stringify(data)); +}) +``` + +### on('netBackgroundPolicyChange') + +on(type: "netBackgroundPolicyChange", callback: Callback\): void + +Subscribes to background network policy changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netBackgroundPolicyChange | Yes| Event type. The value **netBackgroundPolicyChange** indicates a background network policy change event.| +| callback | Callback\ | Yes | Callback used to return the result. It is called when the registered background network policy changes.| + +**Example** + +```js +policy.on('netBackgroundPolicyChange', (data) => { + this.log('on netBackgroundPolicyChange: ' + JSON.stringify(data)); +}) +``` + +## NetBackgroundPolicy + +Enumerates the background network policies. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value | Description | +| ------------------------ | ---- | ---------------------- | +| NET_BACKGROUND_POLICY_NONE | 0 | Default policy.| +| NET_BACKGROUND_POLICY_ENABLE | 1 | Applications running in the background are allowed to access metered networks.| +| NET_BACKGROUND_POLICY_DISABLE | 2 | Applications running in the background are not allowed to access metered networks.| +| NET_BACKGROUND_POLICY_ALLOW_LIST | 3 | Only applications on the allowlist are allowed to access metered networks when they are running in the background.| + +## NetQuotaPolicy + +Defines a network quota policy. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Type | Description | +| ----------------------- | ----------------------------------- | ------------------------------------------------------------ | +| netType | [NetBearType](js-apis-net-connection.md#netbeartype) | Network type.| +| iccid | string | Identifier of the SIM card on the metered cellular network. It is not used for Wi-Fi networks.| +| ident | string | Identifier of the SIM card on the metered cellular network. It is used for Wi-Fi networks. It is used together with **iccid**.| +| periodDuration | string | Start time of metering.| +| warningBytes | number | Data volume threshold for generating an alarm.| +| limitBytes | number | Data volume quota.| +| lastWarningRemind | string | Last time when an alarm was generated.| +| lastLimitRemind | string | Last time when the quota was exhausted.| +| metered | string | Whether the network is a metered network.| +| limitAction | [LimitAction](#limitaction) | Action to take when the data volume quota is reached.| + +## LimitAction + +Enumerates the actions that can be taken when the data volume quota is reached. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value| Description | +| ---------------------- | ----- | ------------ | +| LIMIT_ACTION_NONE | -1 | Default policy.| +| LIMIT_ACTION_DISABLE | 0 | Internet access is disabled.| +| LIMIT_ACTION_AUTO_BILL| 1 | Users will be automatically charged for the data volume they use.| + +## NetUidRule + +Enumerates the metered network rules. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value| Description | +| ---------------------- | ----- | ------------ | +| NET_RULE_NONE | 0 | Default rule.| +| NET_RULE_ALLOW_METERED_FOREGROUND | 1 | Applications running in the foreground are allowed to access metered networks.| +| NET_RULE_ALLOW_METERED | 2 | Applications are allowed to access metered networks.| +| NET_RULE_REJECT_METERED | 4 | Applications are not allowed to access metered networks.| +| NET_RULE_ALLOW_ALL | 32 | Applications are allowed to access all networks (metered or non-metered).| +| NET_RULE_REJECT_ALL | 64 | Applications are not allowed to access any networks (metered or non-metered).| + +## RemindType + +Enumerates the reminder types. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value| Description | +| ---------------------- | - | ------- | +| REMIND_TYPE_WARNING | 1 | Warning.| +| REMIND_TYPE_LIMIT | 2 | Limit.| + +## NetUidPolicy + +Enumerates the application-specific network policies. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value| Description | +| ---------------------- | ----- | ------------ | +| NET_POLICY_NONE | 0 | Default network policy.| +| NET_POLICY_ALLOW_METERED_BACKGROUND | 1 | Applications running in the background are allowed to access metered networks.| +| NET_POLICY_REJECT_METERED_BACKGROUND | 2 | Applications running in the background are not allowed to access metered networks.| 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 144ffa9c6e..f468213118 100644 --- a/en/application-dev/reference/apis/js-apis-net-sharing.md +++ b/en/application-dev/reference/apis/js-apis-net-sharing.md @@ -1,8 +1,9 @@ -# @ohos.net.sharing (Network Sharing) +# # @ohos.net.sharing (Network Sharing) The **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**
+> **NOTE** +> > 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. ## Modules to Import @@ -29,6 +30,15 @@ Checks whether network sharing is supported. This API uses an asynchronous callb | -------- | --------------------------------------- | ---- | ---------- | | callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that network sharing is supported, and **false** means the opposite.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | +| 2202011 | Cannot get network sharing configuration. | + **Example** ```js @@ -56,6 +66,15 @@ Checks whether network sharing is supported. This API uses a promise to return t | --------------------------------- | ------------------------------------- | | Promise\ | Promise used to return the result. The value **true** means that network sharing is supported, and **false** means the opposite.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | +| 2202011 | Cannot get network sharing configuration. | + **Example** ```js @@ -84,6 +103,14 @@ Checks whether network sharing is in progress. This API uses an asynchronous cal | -------- | --------------------------------------- | ---- | ---------- | | callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that network sharing is in progress, and **false** means the opposite.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **Example** ```js @@ -99,10 +126,10 @@ isSharing(): Promise\ Checks whether network sharing is in progress. This API uses a promise to return the result. -**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL - **System API**: This is a system API. +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + **System capability**: SystemCapability.Communication.NetManager.NetSharing **Return value** @@ -111,6 +138,14 @@ Checks whether network sharing is in progress. This API uses a promise to return | --------------------------------- | ------------------------------------- | | Promise\ | Promise used to return the result. The value **true** means that network sharing is in progress, and **false** means the opposite.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **Example** ```js @@ -127,10 +162,10 @@ startSharing(type: SharingIfaceType, callback: AsyncCallback\): void Starts network sharing of a specified type. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL - **System API**: This is a system API. +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + **System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -140,11 +175,27 @@ Starts network sharing of a specified type. This API uses an asynchronous callba | type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| | callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | +| 2202004 | Try to share an unavailable iface. | +| 2202005 | WiFi sharing failed. | +| 2202006 | Bluetooth sharing failed. | +| 2202009 | Network share enable forwarding error. | +| 2202011 | Cannot get network sharing configuration. | + **Example** ```js import SharingIfaceType from '@ohos.net.sharing' -sharing.startSharing(SharingIfaceType.SHARING_WIFI, (error) => { +let SHARING_WIFI=0; +sharing.startSharing(SHARING_WIFI, (error) => { console.log(JSON.stringify(error)); }); ``` @@ -173,11 +224,27 @@ Starts network sharing of a specified type. This API uses a promise to return th | --------------------------------- | ------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | +| 2202004 | Try to share an unavailable iface. | +| 2202005 | WiFi sharing failed. | +| 2202006 | Bluetooth sharing failed. | +| 2202009 | Network share enable forwarding error. | +| 2202011 | Cannot get network sharing configuration. | + **Example** ```js import SharingIfaceType from '@ohos.net.sharing' -sharing.startSharing(SharingIfaceType.SHARING_WIFI).then(() => { +let SHARING_WIFI=0; +sharing.startSharing(SHARING_WIFI).then(() => { console.log("start wifi sharing successful"); }).catch(error => { console.log("start wifi sharing failed"); @@ -203,11 +270,25 @@ Stops network sharing of a specified type. This API uses an asynchronous callbac | type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| | callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | +| 2202005 | WiFi sharing failed. | +| 2202006 | Bluetooth sharing failed. | +| 2202011 | Cannot get network sharing configuration. | + **Example** ```js import SharingIfaceType from '@ohos.net.sharing' -sharing.stopSharing(SharingIfaceType.SHARING_WIFI, (error) => { +let SHARING_WIFI=0; +sharing.stopSharing(SHARING_WIFI, (error) => { console.log(JSON.stringify(error)); }); ``` @@ -236,11 +317,25 @@ Stops network sharing of a specified type. This API uses a promise to return the | --------------------------------- | ------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | +| 2202005 | WiFi sharing failed. | +| 2202006 | Bluetooth sharing failed. | +| 2202011 | Cannot get network sharing configuration. | + **Example** ```js import SharingIfaceType from '@ohos.net.sharing' -sharing.stopSharing(SharingIfaceType.SHARING_WIFI).then(() => { +let SHARING_WIFI=0; +sharing.stopSharing(SHARING_WIFI).then(() => { console.log("stop wifi sharing successful"); }).catch(error => { console.log("stop wifi sharing failed"); @@ -265,6 +360,14 @@ Obtains the volume of mobile data traffic received via network sharing. This API | -------- | --------------------------------------- | ---- | ---------- | | callback | AsyncCallback\ | Yes | Callback used to return the data volume, in KB.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **Example** ```js @@ -292,6 +395,14 @@ Obtains the volume of mobile data traffic received via network sharing. This API | --------------------------------- | ------------------------------------- | | Promise\ | Promise used to return the data volume, in KB.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **Example** ```js @@ -320,6 +431,14 @@ Obtains the volume of mobile data traffic sent via network sharing. This API use | -------- | --------------------------------------- | ---- | ---------- | | callback | AsyncCallback\ | Yes | Callback used to return the data volume, in KB.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **Example** ```js @@ -347,6 +466,14 @@ Obtains the volume of mobile data traffic sent via network sharing. This API use | --------------------------------- | ------------------------------------- | | Promise\ | Promise used to return the data volume, in KB.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **Example** ```js @@ -375,6 +502,14 @@ Obtains the volume of mobile data traffic sent and received via network sharing. | -------- | --------------------------------------- | ---- | ---------- | | callback | AsyncCallback\ | Yes | Callback used to return the data volume, in KB.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **Example** ```js @@ -402,6 +537,14 @@ Obtains the volume of mobile data traffic sent and received via network sharing. | --------------------------------- | ------------------------------------- | | Promise\ | Promise used to return the data volume, in KB.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **Example** ```js @@ -428,14 +571,25 @@ Obtains the names of NICs in the specified network sharing state. This API uses | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ---------- | -| state | [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.| +| state | [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.| | callback | AsyncCallback\> | Yes | Callback used to return an array of NIC names.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **Example** ```js -import SharingIfaceType from '@ohos.net.sharing' -sharing.getSharingIfaces(SharingIfaceState.SHARING_NIC_CAN_SERVER, (error, data) => { +import SharingIfaceState from '@ohos.net.sharing' +let SHARING_BLUETOOTH=2; +sharing.getSharingIfaces(SHARING_BLUETOOTH, (error, data) => { console.log(JSON.stringify(error)); console.log(JSON.stringify(data)); }); @@ -457,7 +611,7 @@ Obtains the names of NICs in the specified network sharing state. This API uses | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ---------- | -| state | [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.| +| state | [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.| **Return value** @@ -465,11 +619,22 @@ Obtains the names of NICs in the specified network sharing state. This API uses | --------------------------------- | ------------------------------------- | | Promise\> | Promise used to return an array of NIC names.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **Example** ```js import SharingIfaceState from '@ohos.net.sharing' -sharing.getSharingIfaces(SharingIfaceState.SHARING_NIC_CAN_SERVER).then(data => { +let SHARING_BLUETOOTH=2; +sharing.getSharingIfaces(SHARING_BLUETOOTH).then(data => { console.log(JSON.stringify(data)); }).catch(error => { console.log(JSON.stringify(error)); @@ -495,11 +660,22 @@ Obtains the network sharing state of the specified type. This API uses an asynch | type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| | callback | AsyncCallback\<[SharingIfaceState](#sharingifacestate)> | Yes | Callback used to return the network sharing state.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **Example** ```js -import SharingIfaceState from '@ohos.net.sharing' -sharing.getSharingState(SharingIfaceType.SHARING_WIFI, (error, data) => { +import SharingIfaceType from '@ohos.net.sharing' +let SHARING_WIFI=0; +sharing.getSharingState(SHARING_WIFI, (error, data) => { console.log(JSON.stringify(error)); console.log(JSON.stringify(data)); }); @@ -523,6 +699,16 @@ Obtains the network sharing state of the specified type. This API uses a promise | -------- | --------------------------------------- | ---- | ---------- | | type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **Return value** | Type | Description | @@ -533,7 +719,8 @@ Obtains the network sharing state of the specified type. This API uses a promise ```js import SharingIfaceType from '@ohos.net.sharing' -sharing.getSharingState(SharingIfaceType.SHARING_WIFI).then(data => { +let SHARING_WIFI=0; +sharing.getSharingState(SHARING_WIFI).then(data => { console.log(JSON.stringify(data)); }).catch(error => { console.log(JSON.stringify(error)); @@ -559,11 +746,22 @@ Obtains regular expressions of NICs of a specified type. This API uses an asynch | type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| | callback | AsyncCallback\> | Yes | Callback used to return an array of regular expressions.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **Example** ```js import SharingIfaceType from '@ohos.net.sharing' -sharing.getSharableRegexes(SharingIfaceType.SHARING_WIFI, (error, data) => { +let SHARING_WIFI=0; +sharing.getSharableRegexes(SHARING_WIFI, (error, data) => { console.log(JSON.stringify(error)); console.log(JSON.stringify(data)); }); @@ -593,11 +791,22 @@ Obtains regular expressions of NICs of a specified type. This API uses a promise | --------------------------------- | ------------------------------------- | | Promise\> | Promise used to return an array of regular expressions.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **Example** ```js import SharingIfaceType from '@ohos.net.sharing' -sharing.getSharableRegexes(SharingIfaceType.SHARING_WIFI).then(data => { +let SHARING_WIFI=0; +sharing.getSharableRegexes(SHARING_WIFI).then(data => { console.log(JSON.stringify(data)); }).catch(error => { console.log(JSON.stringify(error)); @@ -621,14 +830,20 @@ Subscribes to network sharing state changes. This API uses an asynchronous callb | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ---------- | | type | string | Yes | Event name.| -| callback | AsyncCallback\ | Yes | Callback used to return the network sharing state.| +| callback | AsyncCallback\ | Yes | Callback invoked when the network sharing state changes.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | **Example** ```js -sharing.on('sharingStateChange', (error, data) => { - console.log(JSON.stringify(error)); - console.log(JSON.stringify(data)); + sharing.on('sharingStateChange', (data) => { + console.log('on sharingStateChange: ' + JSON.stringify(data)); }); ``` @@ -649,13 +864,19 @@ Unsubscribes from network sharing state changes. This API uses an asynchronous c | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ---------- | | type | string | Yes | Event name.| -| callback | AsyncCallback\ | No | Callback used for unsubscription.| +| callback | AsyncCallback\ | No | Callback invoked when the network sharing state changes.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | **Example** ```js -sharing.off('sharingStateChange', (error, data) => { - console.log(JSON.stringify(error)); +sharing.off('sharingStateChange', (data) => { console.log(JSON.stringify(data)); }); ``` @@ -679,12 +900,18 @@ Subscribes to network sharing state changes of a specified NIC. This API uses an | type | string | Yes | Event name.| | callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | Yes | Callback invoked when the network sharing state of the specified NIC changes.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | + **Example** ```js -sharing.on('interfaceSharingStateChange', (error, data) => { - console.log(JSON.stringify(error)); - console.log(JSON.stringify(data)); + sharing.on('interfaceSharingStateChange', (data) => { + console.log('on interfaceSharingStateChange: ' + JSON.stringify(data)); }); ``` @@ -705,13 +932,19 @@ Unsubscribes from network sharing status changes of a specified NIC. This API us | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ---------- | | type | string | Yes | Event name.| -| callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | No | Callback used for unsubscription.| +| callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | No | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | **Example** ```js -sharing.off('interfaceSharingStateChange', (error, data) => { - console.log(JSON.stringify(error)); +sharing.off('interfaceSharingStateChange', (data) => { console.log(JSON.stringify(data)); }); ``` @@ -735,12 +968,18 @@ Subscribes to upstream network changes. This API uses an asynchronous callback t | type | string | Yes | Event name.| | callback | AsyncCallback\ | Yes | Callback invoked when the upstream network changes.| +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | + **Example** ```js -sharing.on('sharingUpstreamChange', (error, data) => { - console.log(JSON.stringify(error)); - console.log(JSON.stringify(data)); + sharing.on('sharingUpstreamChange', (data) => { + console.log('on sharingUpstreamChange: ' + JSON.stringify(data)); }); ``` @@ -761,13 +1000,19 @@ Unsubscribes from upstream network changes. This API uses an asynchronous callba | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ---------- | | type | string | Yes | Event name.| -| callback | AsyncCallback\ | No | Callback used for unsubscription.| +| callback | AsyncCallback\ | No | Callback used for unsubscription from upstream network changes.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | **Example** ```js -sharing.off('sharingUpstreamChange', (error, data) => { - console.log(JSON.stringify(error)); +sharing.off('sharingUpstreamChange', (data) => { console.log(JSON.stringify(data)); }); ``` @@ -788,7 +1033,7 @@ Enumerates the network sharing states of an NIC. ## SharingIfaceType -Enumerates the network sharing types of an NIC. +Enumerates the network sharing types of an NIC. **System API**: This is a system API. @@ -797,5 +1042,5 @@ Enumerates the network sharing types of an NIC. | Name | Value | Description | | ------------------------ | ---- | ---------------------- | | SHARING_WIFI | 0 | Wi-Fi hotspot sharing.| -| SHARING_USB | 1 | USB sharing (not supported currently).| +| SHARING_USB | 1 | USB sharing.| | SHARING_BLUETOOTH | 2 | Bluetooth sharing.| diff --git a/en/application-dev/reference/apis/js-apis-socket.md b/en/application-dev/reference/apis/js-apis-socket.md index bd14137464..271a662c7f 100644 --- a/en/application-dev/reference/apis/js-apis-socket.md +++ b/en/application-dev/reference/apis/js-apis-socket.md @@ -1,8 +1,7 @@ -# @ohos.net.socket (Socket Connection) +# # @ohos.net.socket (Socket Connection) -The **socket** module implements socket connection management and operation. - -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -22,7 +21,7 @@ Creates a **UDPSocket** object. **Return value** | Type | Description | -| --------------------------------- | ---------------------- | +| :--------------------------------- | :---------------------- | | [UDPSocket](#udpsocket) | **UDPSocket** object.| @@ -54,6 +53,13 @@ Binds the IP address and port number. The port number can be specified or random | address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -84,11 +90,17 @@ Binds the IP address and port number. The port number can be specified or random | ------- | ---------------------------------- | ---- | ------------------------------------------------------ | | address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | **Return value** | Type | Description | -| -------------- | ----------------------------------------- | +| :-------------- | :----------------------------------------- | | Promise\ | Promise used to return the result.| **Example** @@ -123,6 +135,13 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p | options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -162,10 +181,17 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p | ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | | options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Return value** | Type | Description | -| -------------- | --------------------------------------------- | +| :-------------- | :--------------------------------------------- | | Promise\ | Promise used to return the result.| **Example** @@ -231,7 +257,7 @@ Closes a UDPSocket connection. This API uses a promise to return the result. **Return value** | Type | Description | -| -------------- | ----------------------------------------- | +| :-------------- | :----------------------------------------- | | Promise\ | Promise used to return the result.| **Example** @@ -253,7 +279,7 @@ getState\(callback: AsyncCallback\): void Obtains the status of the UDPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE**
+>**NOTE** >This API can be called only after [bind](#bind) is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -266,6 +292,12 @@ Obtains the status of the UDPSocket connection. This API uses an asynchronous ca | -------- | ------------------------------------------------------ | ---- | ---------- | | callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | Yes | Callback used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 201 | Permission denied. | + **Example** ```js @@ -293,7 +325,7 @@ getState\(\): Promise Obtains the status of the UDPSocket connection. This API uses a promise to return the result. ->**NOTE**
+>**NOTE** >This API can be called only after [bind](#bind) is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -303,7 +335,7 @@ Obtains the status of the UDPSocket connection. This API uses a promise to retur **Return value** | Type | Description | -| ----------------------------------------------- | ----------------------------------------- | +| :----------------------------------------------- | :----------------------------------------- | | Promise<[SocketStateBase](#socketstatebase)> | Promise used to return the result.| **Example** @@ -330,9 +362,9 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { setExtraOptions\(options: UDPExtraOptions, callback: AsyncCallback\): void -Sets other properties of the UDPSocket connection. This API uses an asynchronous callback to return the result. +Sets other attributes of the UDPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE**
+>**NOTE** >This API can be called only after [bind](#bind) is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -346,6 +378,12 @@ Sets other properties of the UDPSocket connection. This API uses an asynchronous | options | [UDPExtraOptions](#udpextraoptions) | Yes | Other properties of the UDPSocket connection. For details, see [UDPExtraOptions](#udpextraoptions).| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | **Example** @@ -378,9 +416,9 @@ udp.bind({address:'192.168.xx.xxx', port:xxxx, family:1}, err=> { setExtraOptions\(options: UDPExtraOptions\): Promise -Sets other properties of the UDPSocket connection. This API uses a promise to return the result. +Sets other attributes of the UDPSocket connection. This API uses a promise to return the result. ->**NOTE**
+>**NOTE** >This API can be called only after [bind](#bind) is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -396,9 +434,16 @@ Sets other properties of the UDPSocket connection. This API uses a promise to re **Return value** | Type | Description | -| -------------- | --------------------------------------------------- | +| :-------------- | :--------------------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -455,7 +500,7 @@ off\(type: 'message', callback?: Callback<\{message: ArrayBuffer, remoteInfo: So Disables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE**
+>**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 @@ -475,7 +520,7 @@ 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. +// 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('message', callback); udp.off('message'); ``` @@ -515,7 +560,7 @@ 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**
+>**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 @@ -535,14 +580,14 @@ 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. +// 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"); } 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. +// 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('close', callback2); udp.off('close'); ``` @@ -563,7 +608,6 @@ Enables listening for error events of the UDPSocket connection. This API uses an | type | string | Yes | Type of the event to subscribe to.
**error**: error event| | callback | ErrorCallback | Yes | Callback used to return the result. | - **Example** ```js @@ -580,7 +624,7 @@ 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**
+>**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 @@ -600,7 +644,7 @@ 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. +// 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('error', callback); udp.off('error'); ``` @@ -668,6 +712,12 @@ Defines information about the socket connection. | port | number | Yes | Port number. The value ranges from **0** to **65535**. | | size | number | Yes | Length of the server response message, in bytes. | +## Description of UDP Error Codes + +The UDP error code mapping is in the format of 2301000 + Linux kernel error code. + +For details about error codes, see [Socket Error Codes](../errorcodes/errorcode-net-socket.md). + ## socket.constructTCPSocketInstance constructTCPSocketInstance\(\): TCPSocket @@ -679,7 +729,7 @@ Creates a **TCPSocket** object. **Return value** | Type | Description | - | --------------------------------- | ---------------------- | + | :--------------------------------- | :---------------------- | | [TCPSocket](#tcpsocket) | **TCPSocket** object.| **Example** @@ -710,6 +760,12 @@ Binds the IP address and port number. The port number can be specified or random | address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | **Example** @@ -744,9 +800,16 @@ Binds the IP address and port number. The port number can be specified or random **Return value** | Type | Description | -| -------------- | ------------------------------------------------------- | +| :-------------- | :------------------------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -777,6 +840,13 @@ Sets up a connection to the specified IP address and port number. This API uses | options | [TCPConnectOptions](#tcpconnectoptions) | Yes | TCPSocket connection parameters. For details, see [TCPConnectOptions](#tcpconnectoptions).| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -810,9 +880,16 @@ Sets up a connection to the specified IP address and port number. This API uses **Return value** | Type | Description | -| -------------- | --------------------------------------------------------- | +| :-------------- | :--------------------------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -832,7 +909,7 @@ send\(options: TCPSendOptions, callback: AsyncCallback\): void Sends data over a TCPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE**
+>**NOTE** >This API can be called only after [connect](#connect) is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -846,6 +923,13 @@ Sends data over a TCPSocket connection. This API uses an asynchronous callback t | options | [TCPSendOptions](#tcpsendoptions) | Yes | Parameters for sending data over the TCPSocket connection. For details, see [TCPSendOptions](#tcpsendoptions).| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -874,7 +958,7 @@ send\(options: TCPSendOptions\): Promise Sends data over a TCPSocket connection. This API uses a promise to return the result. ->**NOTE**
+>**NOTE** >This API can be called only after [connect](#connect) is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -890,9 +974,16 @@ Sends data over a TCPSocket connection. This API uses a promise to return the re **Return value** | Type | Description | -| -------------- | ------------------------------------------------- | +| :-------------- | :------------------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -930,6 +1021,11 @@ Closes a TCPSocket connection. This API uses an asynchronous callback to return | -------- | --------------------- | ---- | ---------- | | callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 201 | Permission denied. | **Example** @@ -958,9 +1054,15 @@ Closes a TCPSocket connection. This API uses a promise to return the result. **Return value** | Type | Description | -| -------------- | ----------------------------------------- | +| :-------------- | :----------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 201 | Permission denied. | + **Example** ```js @@ -980,7 +1082,7 @@ getRemoteAddress\(callback: AsyncCallback\): void Obtains the remote address of a socket connection. This API uses an asynchronous callback to return the result. ->**NOTE**
+>**NOTE** >This API can be called only after [connect](#connect) is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -993,6 +1095,12 @@ Obtains the remote address of a socket connection. This API uses an asynchronous | -------- | ------------------------------------------------- | ---- | ---------- | | callback | AsyncCallback<[NetAddress](#netaddress)> | Yes | Callback used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 201 | Permission denied. | + **Example** ```js @@ -1019,7 +1127,7 @@ getRemoteAddress\(\): Promise Obtains the remote address of a socket connection. This API uses a promise to return the result. ->**NOTE**
+>**NOTE** >This API can be called only after [connect](#connect) is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -1029,9 +1137,15 @@ Obtains the remote address of a socket connection. This API uses a promise to re **Return value** | Type | Description | -| ------------------------------------------ | ------------------------------------------ | +| :------------------------------------------ | :------------------------------------------ | | Promise<[NetAddress](#netaddress)> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 201 | Permission denied. | + **Example** ```js @@ -1057,7 +1171,7 @@ getState\(callback: AsyncCallback\): void Obtains the status of the TCPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE**
+>**NOTE** >This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -1070,6 +1184,11 @@ Obtains the status of the TCPSocket connection. This API uses an asynchronous ca | -------- | ------------------------------------------------------ | ---- | ---------- | | callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | Yes | Callback used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 201 | Permission denied. | **Example** @@ -1097,7 +1216,7 @@ getState\(\): Promise Obtains the status of the TCPSocket connection. This API uses a promise to return the result. ->**NOTE**
+>**NOTE** >This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -1107,9 +1226,14 @@ Obtains the status of the TCPSocket connection. This API uses a promise to retur **Return value** | Type | Description | -| ----------------------------------------------- | ----------------------------------------- | +| :----------------------------------------------- | :----------------------------------------- | | Promise<[SocketStateBase](#socketstatebase)> | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 201 | Permission denied. | **Example** @@ -1136,7 +1260,7 @@ setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback\): voi Sets other properties of the TCPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE**
+>**NOTE** >This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -1150,6 +1274,13 @@ Sets other properties of the TCPSocket connection. This API uses an asynchronous | options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -1185,7 +1316,7 @@ setExtraOptions\(options: TCPExtraOptions\): Promise Sets other properties of the TCPSocket connection. This API uses a promise to return the result. ->**NOTE**
+>**NOTE** >This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -1201,9 +1332,15 @@ Sets other properties of the TCPSocket connection. This API uses a promise to re **Return value** | Type | Description | -| -------------- | --------------------------------------------------- | +| :-------------- | :--------------------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | **Example** @@ -1264,7 +1401,7 @@ off\(type: 'message', callback?: Callback<\{message: ArrayBuffer, remoteInfo: So Disables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE**
+>**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 @@ -1284,7 +1421,7 @@ 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. +// 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('message', callback); tcp.off('message'); ``` @@ -1305,7 +1442,6 @@ Enables listening for connection or close events of the TCPSocket connection. Th | type | string | Yes | Type of the event to subscribe to.

- **connect**: connection event
- **close**: close event| | callback | Callback\ | Yes | Callback used to return the result. | - **Example** ```js @@ -1325,7 +1461,7 @@ 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**
+>**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 @@ -1345,14 +1481,14 @@ 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. +// 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"); } 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. +// 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('close', callback2); tcp.off('close'); ``` @@ -1389,7 +1525,7 @@ 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**
+>**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 @@ -1409,7 +1545,7 @@ 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. +// 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('error', callback); tcp.off('error'); ``` @@ -1452,7 +1588,13 @@ Defines other properties of the TCPSocket connection. | receiveBufferSize | number | No | Size of the receive buffer, in bytes. | | sendBufferSize | number | No | Size of the send buffer, in bytes. | | reuseAddress | boolean | No | Whether to reuse addresses. The default value is **false**. | -| socketTimeout | number | No | Timeout duration of the TCPSocket connection, in ms. | +| socketTimeout | number | No | Timeout duration of the UDPSocket connection, in ms. | + +## Description of TCP Error Codes + +The TCP error code mapping is in the format of 2301000 + Linux kernel error code. + +For details about error codes, see [Socket Error Codes](../errorcodes/errorcode-net-socket.md). ## socket.constructTLSSocketInstance9+ @@ -1465,7 +1607,7 @@ Creates a **TLSSocket** object. **Return value** | Type | Description | -| --------------------------------- | ---------------------- | +| :--------------------------------- | :---------------------- | | [TLSSocket](#tlssocket9) | **TLSSocket** object.| **Example** @@ -1535,7 +1677,7 @@ Binds the IP address and port number. This API uses a promise to return the resu **Return value** | Type | Description | -| -------------- | ------------------------------------------------------- | +| :-------------- | :------------------------------------------------------- | | Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -1609,7 +1751,7 @@ Obtains the status of the TLSSocket connection. This API uses a promise to retur **Return value** | Type | Description | -| ----------------------------------------------- | ----------------------------------------- | +| :----------------------------------------------- | :----------------------------------------- | | Promise\<[SocketStateBase](#socketstatebase)> | Promise used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -1706,7 +1848,7 @@ Sets other properties of the TCPSocket connection after successful binding of th **Return value** | Type | Description | -| -------------- | --------------------------------------------------- | +| :-------------- | :--------------------------------------------------- | | Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -1767,7 +1909,6 @@ Sets up a TLSSocket connection, and creates and initializes a TLS session after | 2303104 | Interrupted system call. | | 2303109 | Bad file number. | | 2303111 | Resource temporarily unavailable try again. | -| 2303113 | System permission denied. | | 2303188 | Socket operation on non-socket. | | 2303191 | Protocol wrong type for socket. | | 2303198 | Address already in use. | @@ -1784,7 +1925,7 @@ Sets up a TLSSocket connection, and creates and initializes a TLS session after ```js let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication -tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { +tlsTwoWay.bind({address: '192.168.xxx.xxx', port: 8080, family: 1}, err => { if (err) { console.log('bind fail'); return; @@ -1795,14 +1936,14 @@ let options = { ALPNProtocols: ["spdy/1", "http/1.1"], address: { address: "192.168.xx.xxx", - port: xxxx, + port: 8080, family: 1, }, secureOptions: { key: "xxxx", cert: "xxxx", ca: ["xxxx"], - passwd: "xxxx", + password: "xxxx", protocols: [socket.Protocol.TLSv12], useRemoteCipherPrefer: true, signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", @@ -1810,12 +1951,12 @@ let options = { }, }; tlsTwoWay.connect(options, (err, data) => { - console.error(err); - console.log(data); + 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: xxxx, family: 1}, err => { + tlsOneWay.bind({address: '192.168.xxx.xxx', port: 8080, family: 1}, err => { if (err) { console.log('bind fail'); return; @@ -1825,7 +1966,7 @@ tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { let oneWayOptions = { address: { address: "192.168.xxx.xxx", - port: xxxx, + port: 8080, family: 1, }, secureOptions: { @@ -1834,8 +1975,8 @@ let oneWayOptions = { }, }; tlsOneWay.connect(oneWayOptions, (err, data) => { - console.error(err); - console.log(data); + console.error("connect callback error"+err); + console.log(JSON.stringify(data)); }); ``` @@ -1867,7 +2008,6 @@ Sets up a TLSSocket connection, and creates and initializes a TLS session after | 2303104 | Interrupted system call. | | 2303109 | Bad file number. | | 2303111 | Resource temporarily unavailable try again. | -| 2303113 | System permission denied. | | 2303188 | Socket operation on non-socket. | | 2303191 | Protocol wrong type for socket. | | 2303198 | Address already in use. | @@ -1884,7 +2024,7 @@ Sets up a TLSSocket connection, and creates and initializes a TLS session after ```js let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication -tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { +tlsTwoWay.bind({address: '192.168.xxx.xxx', port: 8080, family: 1}, err => { if (err) { console.log('bind fail'); return; @@ -1895,14 +2035,14 @@ let options = { ALPNProtocols: ["spdy/1", "http/1.1"], address: { address: "xxxx", - port: xxxx, + port: 8080, family: 1, }, secureOptions: { key: "xxxx", cert: "xxxx", ca: ["xxxx"], - passwd: "xxxx", + password: "xxxx", protocols: [socket.Protocol.TLSv12], useRemoteCipherPrefer: true, signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", @@ -1910,13 +2050,13 @@ let options = { }, }; tlsTwoWay.connect(options).then(data => { - console.log(data); + console.log(JSON.stringify(data)); }).catch(err => { console.error(err); }); let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication -tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { +tlsOneWay.bind({address: '192.168.xxx.xxx', port: 8080, family: 1}, err => { if (err) { console.log('bind fail'); return; @@ -1926,7 +2066,7 @@ tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { let oneWayOptions = { address: { address: "192.168.xxx.xxx", - port: xxxx, + port: 8080, family: 1, }, secureOptions: { @@ -1935,7 +2075,7 @@ let oneWayOptions = { }, }; tlsOneWay.connect(oneWayOptions).then(data => { - console.log(data); + console.log(JSON.stringify(data)); }).catch(err => { console.error(err); }); @@ -1985,7 +2125,7 @@ Obtains the remote address of a TLSSocket connection. This API uses a promise to **Return value** | Type | Description | -| ------------------------------------------ | ------------------------------------------ | +| :------------------------------------------ | :------------------------------------------ | | Promise\<[NetAddress](#netaddress)> | Promise used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -2050,7 +2190,7 @@ Obtains the local digital certificate after a TLSSocket connection is establishe **Return value** -| Type | Description | +| Type | Description | | -------------- | -------------------- | | Promise\<[X509CertRawData](#x509certrawdata9)> | Promise used to return the result. If the operation fails, an error message is returned.| @@ -2264,7 +2404,7 @@ Obtains the cipher suite negotiated by both communication parties after a TLSSoc ```js tls.getCipherSuite().then(data => { - console.log(data); + console.log('getCipherSuite success:' + JSON.stringify(data)); }).catch(err => { console.error(err); }); @@ -2328,7 +2468,7 @@ Obtains the signing algorithm negotiated by both communication parties after a T ```js tls.getSignatureAlgorithms().then(data => { - console.log(data); + console.log("getSignatureAlgorithms success" + data); }).catch(err => { console.error(err); }); @@ -2491,7 +2631,7 @@ Defines TLS connection options. | -------------- | ------------------------------------- | --- |-------------- | | address | [NetAddress](#netaddress) | Yes | Gateway address. | | secureOptions | [TLSSecureOptions](#tlssecureoptions9) | Yes| TLS security options.| -| ALPNProtocols | Array\ | Yes| Application Layer Protocol Negotiation (ALPN) protocols. | +| ALPNProtocols | Array\ | No| Application Layer Protocol Negotiation (ALPN) protocols. | ## TLSSecureOptions9+ @@ -2504,7 +2644,7 @@ Defines TLS security options. The CA certificate is mandatory, and other paramet | ca | string \| Array\ | Yes| CA certificate of the server, which is used to authenticate the digital certificate of the server.| | cert | string | No| Digital certificate of the local client. | | key | string | No| Private key of the local digital certificate. | -| passwd | string | No| Password for reading the private key. | +| password | string | No| Password for reading the private key. | | protocols | [Protocol](#protocol9) \|Array\<[Protocol](#protocol9)> | No| TLS protocol version. | | useRemoteCipherPrefer | boolean | No| Whether to use the remote cipher suite preferentially. | | signatureAlgorithms | string | No| Signing algorithm used during communication. | diff --git a/en/application-dev/reference/apis/js-apis-webSocket.md b/en/application-dev/reference/apis/js-apis-webSocket.md index 2b2fa3af70..6319fda995 100644 --- a/en/application-dev/reference/apis/js-apis-webSocket.md +++ b/en/application-dev/reference/apis/js-apis-webSocket.md @@ -1,10 +1,9 @@ -# @ohos.net.webSocket (WebSocket Connection) +# # @ohos.net.webSocket (WebSocket Connection) -The **webSocket** module implements WebSocket connection management and operation. - -> **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. +> **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. + 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. @@ -17,7 +16,7 @@ If an error occurs in any of the preceding processes, the client will receive a import webSocket from '@ohos.net.webSocket'; ``` -## Complete Example +## Examples ```js import webSocket from '@ohos.net.webSocket'; @@ -37,7 +36,7 @@ ws.on('open', (err, value) => { }); 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. + // 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) { @@ -49,7 +48,7 @@ ws.on('message', (err, value) => { } }); 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)); @@ -71,7 +70,7 @@ Creates a WebSocket connection. You can use this API to create or close a WebSoc **System capability**: SystemCapability.Communication.NetStack -**Return Value** +**Return value** | Type | Description | | :---------------------------------- | :----------------------------------------------------------- | @@ -94,7 +93,7 @@ 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. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -105,6 +104,12 @@ Initiates a WebSocket request to establish a WebSocket connection to a given URL | url | string | Yes | URL for establishing a WebSocket connection.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | **Example** @@ -127,7 +132,7 @@ connect\(url: string, options: WebSocketRequestOptions, callback: AsyncCallback< 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. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -139,6 +144,12 @@ Initiates a WebSocket request carrying specified options to establish a WebSocke | options | WebSocketRequestOptions | Yes | Request options. For details, see [WebSocketRequestOptions](#websocketrequestoptions).| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | **Example** @@ -166,7 +177,7 @@ 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. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -177,12 +188,19 @@ Initiates a WebSocket request carrying specified options to establish a WebSocke | url | string | Yes | URL for establishing a WebSocket connection. | | options | WebSocketRequestOptions | No | Request options. For details, see [WebSocketRequestOptions](#websocketrequestoptions).| -**Return Value** +**Return value** | Type | Description | | :----------------- | :-------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -203,7 +221,7 @@ send\(data: string | ArrayBuffer, callback: AsyncCallback\): void Sends data through a WebSocket connection. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -214,6 +232,13 @@ Sends data through a WebSocket connection. This API uses an asynchronous callbac | data | string \| ArrayBuffer 8+ | Yes | Data to send.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -237,7 +262,7 @@ send\(data: string | ArrayBuffer\): Promise Sends data through a WebSocket connection. This API uses a promise to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -247,12 +272,19 @@ Sends data through a WebSocket connection. This API uses a promise to return the | ------ | ------ | ---- | ------------ | | data | string \| ArrayBuffer 8+ | Yes | Data to send.| -**Return Value** +**Return value** | Type | Description | | :----------------- | :-------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -275,7 +307,7 @@ close\(callback: AsyncCallback\): void Closes a WebSocket connection. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -285,6 +317,13 @@ Closes a WebSocket connection. This API uses an asynchronous callback to return | -------- | ------------------------ | ---- | ---------- | | callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -306,7 +345,7 @@ close\(options: WebSocketCloseOptions, callback: AsyncCallback\): void Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -317,6 +356,13 @@ Closes a WebSocket connection carrying specified options such as **code** and ** | options | WebSocketCloseOptions | Yes | Request options. For details, see [WebSocketCloseOptions](#websocketcloseoptions).| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -341,7 +387,7 @@ close\(options?: WebSocketCloseOptions\): Promise Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses a promise to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -351,12 +397,19 @@ Closes a WebSocket connection carrying specified options such as **code** and ** | ------- | --------------------- | ---- | ----------------------------------------------------- | | options | WebSocketCloseOptions | No | Request options. For details, see [WebSocketCloseOptions](#websocketcloseoptions).| -**Return Value** +**Return value** | Type | Description | | :----------------- | :-------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | + **Example** ```js @@ -406,7 +459,7 @@ 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. ->![](public_sys-resources/icon-note.gif) **NOTE:** +>**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 @@ -437,7 +490,7 @@ 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. ->![](public_sys-resources/icon-note.gif) **NOTE:** +>**NOTE** >The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\). **System capability**: SystemCapability.Communication.NetStack @@ -449,7 +502,6 @@ Enables listening for the **message** events of a WebSocket connection. This API | type | string | Yes | Event type.
**message**: event indicating that a message has been received from the server.| | callback | AsyncCallback\8+\> | Yes | Callback used to return the result. | - **Example** ```js @@ -466,7 +518,7 @@ 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. ->![](public_sys-resources/icon-note.gif) **NOTE:** +>**NOTE** >The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 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. @@ -507,7 +559,7 @@ 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); }); ``` @@ -518,7 +570,7 @@ off\(type: 'close', callback?: AsyncCallback<\{ code: number, reason: string \}\ Disables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result. ->![](public_sys-resources/icon-note.gif) **NOTE:** +>**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 @@ -530,7 +582,6 @@ Disables listening for the **close** events of a WebSocket connection. This API | type | string | Yes | Event type.
**close**: event indicating that a WebSocket connection has been closed.| | callback | AsyncCallback<{ code: number, reason: string }> | No | Callback used to return the result. | - **Example** ```js @@ -554,7 +605,6 @@ Enables listening for the **error** events of a WebSocket connection. This API u | type | string | Yes | Event type.
**error**: event indicating the WebSocket connection has encountered an error.| | callback | ErrorCallback | Yes | Callback used to return the result. | - **Example** ```js @@ -571,7 +621,7 @@ 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. ->![](public_sys-resources/icon-note.gif) **NOTE:** +>**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 @@ -621,8 +671,8 @@ You can customize the result codes sent to the server. The result codes in the f | Value | Description | | :-------- | :----------------- | -| 1000 | Normally closed | -| 1001 | Connection closed by the server | -| 1002 | Incorrect protocol | -| 1003 | Data unable to be processed| -| 1004~1015 | Reserved | +| 1000 | Normally closed. | +| 1001 | Connection closed by the server. | +| 1002 | Incorrect protocol. | +| 1003 | Data unable to be processed.| +| 1004~1015 | Reserved. | diff --git a/en/application-dev/reference/errorcodes/Readme-EN.md b/en/application-dev/reference/errorcodes/Readme-EN.md index 6de69bc7c9..5e54641232 100644 --- a/en/application-dev/reference/errorcodes/Readme-EN.md +++ b/en/application-dev/reference/errorcodes/Readme-EN.md @@ -47,6 +47,8 @@ - [File Management Error Codes](errorcode-filemanagement.md) - Network Management - [Upload and Download Error Codes](errorcode-request.md) + - [HTTP Error Codes](errorcode-http.md) + - [Socket Error Codes](errorcode-socket.md) - Connectivity - [NFC Error Codes](errorcode-nfc.md) - [RPC Error Codes](errorcode-rpc.md) diff --git a/en/application-dev/reference/errorcodes/errorcode-net-http.md b/en/application-dev/reference/errorcodes/errorcode-net-http.md new file mode 100644 index 0000000000..bece9d1b26 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-net-http.md @@ -0,0 +1,527 @@ +# HTTP Error Codes + +## 2300001 Protocol Not Supported + +**Error Message** + +Unsupported protocol. + +**Description** + +This error code is reported if the input protocol version is not supported by the server. + +**Cause** + +The input protocol version is not supported by the server. + +**Solution** + +Specify a protocol version supported by the server. + +## 2300003 Incorrect URL Format + +**Error Message** + +URL using bad/illegal format or missing URL. + +**Description** + +This error code is reported if the URL format is incorrect. + +**Cause** + +The format of the input URL is incorrect. + +**Solution** + +Specify a URL of the correct format. + +## 2300005 Failed to Resolve the Domain Name of the Proxy Server + +**Error Message** + +Couldn't resolve proxy name. + +**Description** + +This error code is reported if the domain name of the proxy server cannot be resolved. + +**Cause** + +This error code is reported if the URL of the proxy server is incorrect. + +**Solution** + +Specify a URL of the correct format. + +## 2300006 Failed to Resolve the Domain Name of the Host + +**Error Message** + +Couldn't resolve host name. + +**Description** + +This error code is reported if the domain name of the host cannot be resolved. + +**Cause** + +1. The input URL is incorrect. + +2. The network connection is abnormal. + +**Solution** + +1. Specify a URL of the correct format. + +2. Rectify network connection faults. + +## 2300007 Failed to Connect to the Server + +**Error Message** + +Couldn't connect to server. + +**Description** + +This error code is reported if the server connection failed. + +**Cause** + +The format of the input URL is incorrect. + +**Solution** + +Specify a URL of the correct format. + +## 2300008 Invalid Data Returned by the Server + +**Error Message** + +Weird server reply. + +**Description** + +This error code is reported if the data returned by the server is invalid. + +**Cause** + +The server encounters an error and returns data in non-HTTP format. + +**Solution** + +Check the server implementation. + +## 2300009 Access to Remote Resources Denied + +**Error Message** + +Access denied to remote resource. + +**Description** + +This error code is reported if the access to remote resources is denied by the server. + +**Cause** + +The access to the specified resource is denied by the server. + +**Solution** + +Check whether access to the requested resource is allowed. + +## 2300016 HTT2 Framing Layer Error + +**Error Message** + +Error in the HTTP2 framing layer. + +**Description** + +This error code is reported if an error occurs on the HTTP2 framing layer. + +**Cause** + +HTTP2 is not supported by the server. + +**Solution** + +Capture and analyze packets to check whether HTTP2 is supported by the server. + +## 2300018 Incomplete Data Returned by the Server + +**Error Message** + +Transferred a partial file. + +**Description** + +This error code is reported if data returned by the server is incomplete. + +**Cause** + +This problem is probable due to server implementation. + +**Solution** + +Check the server implementation. + +## 2300023 Failed to Write Received Data to a Disk or Application + +**Error Message** + +Failed writing received data to disk/application. + +**Description** + +This error code is reported if an error occurs while writing received data to the disk or application. + +**Cause** + +The application does not have the data write permission. + +**Solution** + +Check the permissions granted to the application. + +## 2300025 Failed to Upload Data + +**Error Message** + +Upload failed. + +**Description** + +This error code is reported if data upload fails. + +**Cause** + +The file is too large or the network is faulty. The server may reject the **STOR** command if FTP is used. + +**Solution** + +Check the file size and network status. + +## 2300026 Failed to Open or Read Local Data from a File or Application + +**Error Message** + +Failed to open/read local data from file/application. + +**Description** + +This error code is reported if an error occurs while opening or reading local data from a file or application. + +**Cause** + +The application does not have the data read permission. + +**Solution** + +Check the permissions granted to the application. + +## 2300027 Insufficient Memory + +**Error Message** + +Out of memory. + +**Description** + +This error code is reported if the memory is insufficient. + +**Cause** + +This error code is reported if the memory is insufficient. + +**Solution** + +Check the system memory. + +## 2300028 Operation Timeout + +**Error Message** + +Timeout was reached. + +**Description** + +This error code is reported if the operation times out. + +**Cause** + +The TCP connection or the read/write operation times out. + +**Solution** + +Rectify network faults. + +## 2300047 Maximum Redirections Reached + +**Error Message** + +Number of redirects hit maximum amount. + +**Description** + +This error code is reported if the number of redirections reaches the maximum. + +**Cause** + +Redirection is performed too frequently. + +**Solution** + +Check the server implementation. + +## 2300052 No Content Returned by the Server + +**Error Message** + +Server returned nothing (no headers, no data). + +**Description** + +This error code is reported if no content is returned by the server. + +**Cause** + +This problem is probable due to server implementation. + +**Solution** + +Check the server implementation. + +## 2300055 Failed to Send Network Data + +**Error Message** + +Failed sending data to the peer. + +**Description** + +This error code is reported if an error occurs while sending network data to the peer end. + +**Cause** + +This problem is probable due to a network fault. + +**Solution** + +Rectify network faults. + +## 2300056 Failed to Receive Network Data + +**Error Message** + +Failure when receiving data from the peer. + +**Description** + +This error code is reported if an error occurs while receiving network data from the peer end. + +**Cause** + +This problem is probable due to a network fault. + +**Solution** + +Rectify network faults. + +## 2300058 Local SSL Certificate Error + +**Error Message** + +Problem with the local SSL certificate. + +**Description** + +This error code is reported if the local SSL certificate is incorrect. + +**Cause** + +The format of the SSL certificate is incorrect. + +**Solution** + +Check the format of the SSL certificate. + +## 2300059 Failed to Use the Specified SSL Cipher Algorithm + +**Error Message** + +Couldn't use specified SSL cipher. + +**Description** + +This error code is reported if the specified SSL cipher algorithm cannot be used. + +**Cause** + +The system does not support the cipher algorithm negotiated between the client and server. + +**Solution** + +Capture and analyze packets to check whether the cipher algorithm is supported. + +## 2300060 Incorrect SSL Certificate or SSH Key of the Remote Server + +**Error Message** + +SSL peer certificate or SSH remote key was not OK. + +**Description** + +This error code is reported if the SSL certificate or SSH key of the remote server is incorrect. + +**Cause** + +It is probable that the server identity verification fails because the certificate has expired. + +**Solution** + +Check whether the certificate is valid. + +## 2300061 Unrecognized or Incorrect HTTP Encoding Format + +**Error Message** + +Unrecognized or bad HTTP Content or Transfer-Encoding. + +**Description** + +This error code is reported if the HTTP encoding format cannot be identified or is incorrect. + +**Cause** + +The HTTP encoding format is incorrect. + +**Solution** + +Check the server implementation. Currently, only gzip encoding is supported. + +## 2300063 Maximum File Size Exceeded + +**Error Message** + +Maximum file size exceeded. + +**Description** + +This error code is reported if the maximum file size is exceeded. + +**Cause** + +The downloaded file is too large. + +**Solution** + +Check the server implementation. + +## 2300070 Insufficient Server Disk Space + +**Error Message** + +Remote disk full or allocation exceeded. + +**Description** + +This error code is reported if the server disk space is insufficient. + +**Cause** + +The server disk is full. + +**Solution** + +Check the server disk space. + +## 2300073 Uploaded File Already Exists + +**Error Message** + +Remote file already exists. + +**Description** + +This error code is reported if the server finds that the uploaded file already exists. + +**Cause** + +The uploaded file already exists. + +**Solution** + +Check the server for files that already exist. + +## 2300077 No SSL CA Certificate or Access Permission + +**Error Message** + +Problem with the SSL CA cert (path? access rights?). + +**Description** + +This error code is reported if the SSL CA certificate does not exist or the access permission is not available. + +**Cause** + +The SSL CA certificate is not available or the access permission is not granted. + +**Solution** + +Check whether the SSL CA certificate exists or the access permission is granted. + +## 2300078 URL Requested File Not Found + +**Error Message** + +Remote file not found. + +**Description** + +This error code is reported if the file requested by the specified URL does not exist. + +**Cause** + +The file requested by the specified URL does not exist. + +**Solution** + +Check whether the file requested by the specified URL exists. + +## 2300094 Identity Verification Failed + +**Error Message** + +An authentication function returned an error. + +**Description** + +This error code is reported if identity verification fails. + +**Cause** + +The specified identity verification field does not match that on the server. + +**Solution** + +Check whether the specified identity verification field matches that on the server. + +## 2300999 Unknown Error + +**Error Message** + +Unknown Other Error. + +**Description** + +This error code is reported if an unknown error occurs. + +**Cause** + +An unknown error occurs. + +**Solution** + +Try again or contact technical support. diff --git a/en/application-dev/reference/errorcodes/errorcode-net-socket.md b/en/application-dev/reference/errorcodes/errorcode-net-socket.md new file mode 100644 index 0000000000..ebd15740b6 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-net-socket.md @@ -0,0 +1,351 @@ +# Socket Error Codes + +## 2301001 Operation Not Allowed + +**Error Message** + +Operation not permitted. + +**Description** + +This error code is reported if an operation is not allowed. + +**Cause** + +The operation is illegal. + +**Procedure** + +Check the operation procedure. + +## 2301002 File Not Exist + +**Error Message** + +No such file or directory. + +**Description** + +This error code is reported if the requested file does not exist. + +**Cause** + +The requested file does not exist. + +**Procedure** + +Check the file name or file path. + +## 2301003 Process Not Exist + +**Error Message** + +No such process. + +**Description** + +This error code is reported if a process does not exist. + +**Cause** + +The process does not exist. + +**Procedure** + +Check the process information. + +## 2301004 System Call Interrupted + +**Error Message** + +Interrupted system call. + +**Description** + +This error code is reported if the system call is interrupted. + +**Cause** + +The system call is interrupted. + +**Procedure** + +Rectify system call errors. + +**Description of TCP/UDP error codes:** +> Mapping format of other TCP/UDP Socket error codes: 2301000 + Linux kernel error code (errno). For details, see Linux kernel error codes. + +## 2300002 System Internal Error + +**Error Message** + +System internal error. + +**Description** + +This error code is reported if a system internal error occurs. + +**Cause** + +1. The memory is abnormal. + +2. A null pointer is present. + +**Procedure** + +1. Check whether the memory space is sufficient. If not, clear the memory and try again. + +2. Check whether the system is normal. If not, try again later or restart the device. + +## 2303104 System Call Interrupted + +**Error Message** + +Interrupted system call. + +**Description** + +This error code is reported if the system call is interrupted. + +**Cause** + +Calling the **connect** function may result in a long blocking time. In such a case, the system generates an interrupt signal and returns an **EINTR** error. + +**Procedure** + +Call the **connect** function to try network connection again. + +## 2303109 Error File Number + +**Error Message** + +Bad file number. + +**Description** + +This error code is reported if an operation is performed on a locally closed socket. + +**Cause** + +The socket FD may be closed. + +**Procedure** + +Check whether the socket is closed unexpectedly. + +## 2303111 Requested Resource Temporarily Unavailable + +**Error Message** + +Resource temporarily unavailable try again. + +**Description** + +This error code is reported if the requested system resource is temporarily unavailable. + +**Cause** + +The system resources are in use. + +**Procedure** + +Try again later. + +## 2303188 Socket Operations on Non-Sockets + +**Error Message** + +Socket operation on non-socket. + +**Description** + +This error code is reported if a socket descriptor is not specified for the **socket** parameter. + +**Cause** + +A socket descriptor is not specified for the **socket** parameter. + +**Procedure** + +Check whether the descriptor is correctly obtained. + +## 2303191 Incorrect Socket Protocol Type + +**Error Message** + +Protocol wrong type for socket. + +**Description** + +This error code is reported if the type of the specified socket protocol is incorrect. + +**Cause** + +The **socket** function is called with an unsupported socket protocol type. +For example, the protocol type cannot be set to **SOCK_STREAM socket** for the the Internet UDP protocol. + +**Procedure** + +Check whether the socket protocol type is correct. + +## 2303198 Network Address Already In Use + +**Error Message** + +Address already in use. + +**Description** + +This error code is reported if a network address has been used. + +**Cause** + +The probable cause can be any of the following: The application attempts to bind a socket to an IP address/port that has been used for an existing socket. The socket is not properly closed. The socket is still being closed. + +**Procedure** + +Try another network address. + +## 2303199 Failed to Assign the Requested Address + +**Error Message** + +Cannot assign requested address. + +**Description** + +This error code is reported if the requested address is invalid in its context. + +**Cause** + +The remote address or port is invalid for the remote server. + +**Procedure** + +Check whether the address or port is correct. + +## 2303210 Connection Timeout + +**Error Message** + +Connection timed out. + +**Description** + +This error code is reported if the connection to the remote server cannot be set up for a long time. + +**Cause** + +It is probable that a server breakdown has occurred. + +**Procedure** + +Contact the peer end to rectify the fault. + +## 2303501 Null SSL + +**Error Message** + +SSL is null. + +**Description** + +This error code is reported if the SSL is null. + +**Cause** + +The returned error information is null when an internal function fails to be executed. + +**Procedure** + +Call the function again. + +## 2303502 TLS Reading Error + +**Error Message** + +Error in tls reading. + +**Description** + +This error code is reported if an error occurs while reading data on the TLS socket. + +**Cause** + +The underlying socket is blocked. + +**Procedure** + +Perform data receiving again. + +## 2303503 TLS Writing Error + +**Error Message** + +Error in tls writing. + +**Description** + +This error code is reported if an error occurs while writing data on the TLS socket. + +**Cause** + +When the send buffer is full, the underlying socket sends an **EWOUDLBLOCK** error, which means that the server does not read the data sent from the client. + +**Procedure** + +Rectify the fault on the server side. + +## 2303504 x509 Failed to Look Up the x509 Certificate + +**Error Message** + +Error looking up x509. + +**Description** + +An error occurred when verifying the x509 certificate. + +**Cause** + +The local certificate does not match the server certificate. + +**Procedure** + +Check whether the local CA matches the server certificate. + +## 2303505 TLS System Call Error + +**Error Message** + +Error occurred in the tls system call. + +**Description** + +This error code is reported if the TLS system call fails because of fatal I/O errors. + +**Cause** + +Network communication fails because of network faults. + +**Procedure** + +For details, see the Linux kernel error codes (errno). + +## 2303506 Failed to Close TLS Connections + +**Error Message** + +Error clearing tls connection. + +**Description** + +This error code is reported if the TLS/SSL connection to be closed has been disabled. + +**Cause** + +The TLS/SSL connection to be closed has been disabled. + +**Procedure** + +Initiate a new TLS/SSL connection. -- GitLab