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\<NetHandle>): 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 getGlobalHttpProxy<sup>10+</sup>(callback: AsyncCallback\<HttpProxy>): void;| Obtains the global HTTP proxy for the network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function setGlobalHttpProxy<sup>10+</sup>(httpProxy: HttpProxy, callback: AsyncCallback<void>): void;| Sets the global HTTP proxy for the network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function getAppNet<sup>9+</sup>(callback: AsyncCallback\<NetHandle>): 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 setAppNet<sup>9+</sup>(netHandle: NetHandle, callback: AsyncCallback\<void>): 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 getDefaultNetSync<sup>9+</sup>(): 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\<boolean>): 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\<Array\<NetHandle>>): 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\<ConnectionProperties>): 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\<NetCapabilities>): void; |Obtains the capability set of the default network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function isDefaultNetMetered<sup>9+</sup>(callback: AsyncCallback<boolean>): 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>): 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>): 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\<Array\<NetAddress>>): 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>): void; | Enables the airplane mode. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function disableAirplaneMode(callback: AsyncCallback\<void>): 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>): 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\<Array\<NetAddress>>): 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\<NetAddress>): 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 | register(callback: AsyncCallback\<void>): void; |Registers an observer for the default network or the network specified in **createNetConnection**.|
| ohos.net.connection.NetConnection | unregister(callback: AsyncCallback\<void>): 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.
importconnectionfrom'@ohos.net.connection'
letnetCap={
// Assume that the default network is Wi-Fi. If you need to create a cellular network connection, set the network type to CELLULAR.
// 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.
importconnectionfrom'@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\<NetHandle>**.
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.
importconnectionfrom'@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.
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>): 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\<InterfaceConfiguration>): 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\<number>): 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\<Array\<string>>): 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.
importethernetfrom'@ohos.net.ethernet'
// Call getAllActiveIfaces to obtain the list of all active network ports.
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.
importethernetfrom'@ohos.net.ethernet'
// Call getAllActiveIfaces to obtain the list of all active network ports.
-[HTTP Data Request](http-request.md): Initiates a data request through HTTP.
-[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.
-[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.
-[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.
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>): void |Sets a background network policy. This API uses an asynchronous callback to return the result.|
| ohos.net.policy | function isBackgroundAllowed(callback: AsyncCallback\<boolean>): 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>): 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\<NetUidPolicy>): 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\<Array\<number>>): 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\<Array\<NetQuotaPolicy>>): void; |Obtains the network quota policies. This API uses an asynchronous callback to return the result.|
| ohos.net.policy | function setNetQuotaPolicies(quotaPolicies: Array\<NetQuotaPolicy>, callback: AsyncCallback\<void>): 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>): 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\<boolean>): 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\<boolean>): 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>): 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\<Array\<number>>): 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\<NetBackgroundPolicy>): 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>): 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>): 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>): 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\<Array\<number>>): 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\<Array\<string>>): 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\<Array\<string>>): 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\<Array\<NetQuotaPolicy>>): 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\<Array\<NetQuotaPolicy>>): 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\<boolean>): 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\<boolean>): 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.
importpolicyfrom'@ohos.net.policy';
addNetQuotaPolicy(){
letparam={
// 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.
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\<boolean>): 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\<boolean>): 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>): void; | Starts network sharing. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function stopSharing(type: SharingIfaceType, callback: AsyncCallback\<void>): void; | Stops network sharing. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function getStatsRxBytes(callback: AsyncCallback\<number>): 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\<number>): 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\<number>): 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\<Array\<string>>): 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\<SharingIfaceState>): 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\<Array\<string>>): 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\<boolean>): void; | Subscribes to network sharing state changes.|
| ohos.net.sharing | function off(type: 'sharingStateChange', callback?: Callback\<boolean>): 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\<NetHandle>): void; | Subscribes to upstream NIC changes.|
| ohos.net.sharing | function off(type: 'sharingUpstreamChange', callback?: Callback\<NetHandle>): 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.
importsharingfrom'@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.
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
## 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).
| API| Description |
Socket connection functions are mainly implemented by the **socket** module. The following table describes the related APIs.
| API| Description|
| -------- | -------- |
| -------- | -------- |
| constructUDPSocketInstance() | Creates a **UDPSocket** object.|
| constructUDPSocketInstance() | Creates a **UDPSocket** object.|
| constructTCPSocketInstance() | Creates a **TCPSocket** object.|
| constructTCPSocketInstance() | Creates a **TCPSocket** object.|
| bind() | Binds the IP address and port number.|
| bind() | Binds the IP address and port number.|
| send() | Sends data.|
| send() | Sends data.|
| close() | Closes a Socket connection. |
| close() | Closes a Socket connection.|
| getState() | Obtains the Socket connection status. |
| getState() | Obtains the Socket connection status.|
| connect() | Connects to the specified IP address and port. This function is supported only for TCP. |
| 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. |
| 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. |
| on(type: 'message') | Subscribes to **message** events of the Socket connection.|
| off(type: 'message') | Disables listening for **message** events of the Socket connection. |
| off(type: 'message') | Unsubscribes from **message** events of the Socket connection.|
| on(type: 'close') | Enables listening for **close** events of the Socket connection. |
| on(type: 'close') | Subscribes to **close** events of the Socket connection.|
| off(type: 'close') | Disables listening for **close** events of the Socket connection. |
| off(type: 'close') | Unsubscribes from **close** events of the Socket connection.|
| on(type: 'error') | Enables listening for **error** events of the Socket connection. |
| on(type: 'error') | Subscribes to **error** events of the Socket connection.|
| off(type: 'error') | Disables listening for **error** events of the Socket connection. |
| off(type: 'error') | Unsubscribes from **error** events of the Socket connection.|
| on(type: 'listening') | Enables listening for **listening** events of the UDPSocket connection. |
| on(type: 'listening') | Subscribes to **listening** events of the UDP Socket connection. |
| off(type: 'listening') | Disables listening for **listening** events of the UDPSocket connection. |
| off(type: 'listening') | Unsubscribes from **listening** events of the UDP Socket connection. |
| on(type: 'connect') | Enables listening for **connect** events of the TCPSocket connection. |
| on(type: 'connect') | Subscribes to **connect** events of the TCP Socket connection. |
| off(type: 'connect') | Disables listening for **connect** events of the TCPSocket 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.
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.
4. Bind the IP address and port number. The port number can be specified or randomly allocated by the system.
...
@@ -48,7 +84,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
...
@@ -48,7 +84,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
6. Send data.
6. Send data.
7. Enable the TCPSocket connection to be automatically closed after use.
7. Enable the TCPSocket connection to be automatically closed after use.
```js
```js
importsocketfrom'@ohos.net.socket'
importsocketfrom'@ohos.net.socket'
...
@@ -56,7 +92,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
...
@@ -56,7 +92,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
// Create a TCPSocket object.
// Create a TCPSocket object.
lettcp=socket.constructTCPSocketInstance();
lettcp=socket.constructTCPSocketInstance();
// Enable listening for TCPSocket events.
// Subscribe to TCP Socket connection events.
tcp.on('message',value=>{
tcp.on('message',value=>{
console.log("on message")
console.log("on message")
letbuffer=value.message
letbuffer=value.message
...
@@ -86,6 +122,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
...
@@ -86,6 +122,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
return;
return;
}
}
console.log('bind success');
console.log('bind success');
// Set up a connection to the specified IP address and port number.
// Set up a connection to the specified IP address and port number.
letconnectAddress={
letconnectAddress={
address:'192.168.xx.xx',
address:'192.168.xx.xx',
...
@@ -100,6 +137,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
...
@@ -100,6 +137,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
return;
return;
}
}
console.log('connect success');
console.log('connect success');
// Send data.
// Send data.
tcp.send({
tcp.send({
data:'Hello, server!'
data:'Hello, server!'
...
@@ -112,7 +150,8 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
...
@@ -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(()=>{
setTimeout(()=>{
tcp.close((err)=>{
tcp.close((err)=>{
console.log('close socket.')
console.log('close socket.')
...
@@ -122,3 +161,167 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
...
@@ -122,3 +161,167 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
tcp.off('close');
tcp.off('close');
},30*1000);
},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
importsocketfrom'@ohos.net.socket'
// Create a TLS Socket connection (for two-way authentication).
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**.
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**<br>
>**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.
>
>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
## Modules to Import
...
@@ -11,9 +13,10 @@ The **http** module provides the HTTP data request capability. An application ca
...
@@ -11,9 +13,10 @@ The **http** module provides the HTTP data request capability. An application ca
importhttpfrom'@ohos.net.http';
importhttpfrom'@ohos.net.http';
```
```
## Example
## Examples
```js
```js
// Import the HTTP namespace.
importhttpfrom'@ohos.net.http';
importhttpfrom'@ohos.net.http';
// Each httpRequest corresponds to an HTTP request task and cannot be reused.
// Each httpRequest corresponds to an HTTP request task and cannot be reused.
| 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).
| 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).
| 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).
| 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).
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.
| 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).
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.
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.
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.
| 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
## HttpRequestOptions
Specifies the type and value range of the optional parameters in the HTTP request.
Specifies the type and value range of the optional parameters in the HTTP request.
...
@@ -364,6 +809,7 @@ Specifies the type and value range of the optional parameters in the HTTP reques
...
@@ -364,6 +809,7 @@ Specifies the type and value range of the optional parameters in the HTTP reques
| readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. |
| 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. |
| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. |
| usingProtocol<sup>9+</sup> | [HttpProtocol](#httpprotocol9) | No | Protocol. The default value is automatically specified by the system. |
| usingProtocol<sup>9+</sup> | [HttpProtocol](#httpprotocol9) | No | Protocol. The default value is automatically specified by the system. |
| usingProxy<sup>10+</sup> | boolean \| Object | No | Whether to use HTTP proxy. The default value is **false**, which means not to use HTTP proxy.<br>- If **usingProxy** is of the **Boolean** type and the value is **true**, network proxy is used by default.<br>- If **usingProxy** is of the **object** type, the specified network proxy is used. |
## RequestMethod
## RequestMethod
...
@@ -372,7 +818,7 @@ Defines an HTTP request method.
...
@@ -372,7 +818,7 @@ Defines an HTTP request method.
| result | string \| Object \| ArrayBuffer<sup>6+</sup> | Yes | Response content returned based on **Content-type** in the response header:<br>- 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.<br>- application/octet-stream: ArrayBuffer<br>- Others: string|
| result | string \| Object \| ArrayBuffer<sup>6+</sup> | Yes | Response content returned based on **Content-type** in the response header:<br>- 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.<br>- application/octet-stream: ArrayBuffer<br>- Others: string|
| resultType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | Yes | Type of the return value. |
| resultType<sup>9+</sup> | [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:<br>- Content-Type: header['Content-Type'];<br>- Status-Line: header['Status-Line'];<br>- Date: header.Date/header['Date'];<br>- Server: header.Server/header['Server'];|
| header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:<br>- Content-Type: header['Content-Type'];<br>- Status-Line: header['Status-Line'];<br>- Date: header.Date/header['Date'];<br>- Server: header.Server/header['Server'];|
| cookies<sup>8+</sup> | Array\<string\> | Yes | Cookies returned by the server. |
| cookies<sup>8+</sup> | string | Yes | Cookies returned by the server. |
## http.createHttpResponseCache<sup>9+</sup>
## http.createHttpResponseCache<sup>9+</sup>
...
@@ -457,7 +903,7 @@ Creates a default object to store responses to HTTP access requests.
...
@@ -457,7 +903,7 @@ Creates a default object to store responses to HTTP access requests.
| -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).
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.
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**<br>
> **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.
> 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.
| iface | string | Yes | Name of the network interface. |
| iface | string | Yes | Interface name. |
| ic | [InterfaceConfiguration](#interfaceconfiguration) | Yes | Network interface configuration to set. |
| ic | [InterfaceConfiguration](#interfaceconfiguration) | Yes | Network interface configuration to set. |
| callback | AsyncCallback\<void> | 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.|
| callback | AsyncCallback\<void> | 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.|
| Promise\<void> | Promise that returns no value.|
| Promise\<void> | 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.|
| 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\<number> | 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.|
| callback | AsyncCallback\<number> | 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.|
| Promise\<number> | 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.|
| Promise\<number> | 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.|
| mode | [IPSetMode](#ipsetmode) | Yes | Configuration mode of the Ethernet connection.|
| Name | Type | Mandatory| Description |
| 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.|
| mode | [IPSetMode](#ipsetmode) | Yes| Configuration mode of the Ethernet connection.|
| 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.|
| 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.|
| 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.|
| 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.|
| 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 (,).|
| 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
## IPSetMode
Defines the configuration mode of the Ethernet connection.
Defines the configuration mode of the Ethernet connection.
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.
| isAllowed | boolean | Yes | Whether applications running in the background are allowed to use mobile data.|
| callback | AsyncCallback\<void> | 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.|
| Promise\<void> | 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.|
| callback | AsyncCallback\<boolean> | 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.|
| Promise\<boolean> | 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.|
| callback | AsyncCallback\<void> | 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.|
| Promise\<void> | 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.|
| 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.|
| 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.|
Obtains the UID array of applications configured with a certain application-specific network policy. This API uses an asynchronous callback to return the result.
| callback | AsyncCallback\<Array\<number>> | 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.|
| Promise\<Array\<number>> | 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.|
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.
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.
| uid | number | Yes| Unique ID of the application.|
| isMetered | boolean | Yes| Whether the network is a metered network.|
| callback | AsyncCallback\<boolean> | 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.|
| uid | number | Yes| Unique ID of the application.|
| iface | string | Yes| Name of the target network.|
| callback | AsyncCallback\<boolean> | 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.|
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.
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.
| 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.|
| 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.|
| type | netQuotaPolicyChange | Yes| Event type. The value **netQuotaPolicyChange** indicates a network quota policy change event.|
| callback | Callback\<Array\<[NetQuotaPolicy](#netquotapolicy)>> | Yes | Callback used to return the result. It is called when the registered network quota policy changes.|
| 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.|
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.
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**<br>
> **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.
> 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
## Modules to Import
...
@@ -29,6 +30,15 @@ Checks whether network sharing is supported. This API uses an asynchronous callb
...
@@ -29,6 +30,15 @@ Checks whether network sharing is supported. This API uses an asynchronous callb
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** means that network sharing is supported, and **false** means the opposite.|
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** means that network sharing is supported, and **false** means the opposite.|
| Promise\<boolean> | Promise used to return the result. The value **true** means that network sharing is supported, and **false** means the opposite.|
| Promise\<boolean> | Promise used to return the result. The value **true** means that network sharing is supported, and **false** means the opposite.|
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** means that network sharing is in progress, and **false** means the opposite.|
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** means that network sharing is in progress, and **false** means the opposite.|
| Promise\<boolean> | Promise used to return the result. The value **true** means that network sharing is in progress, and **false** means the opposite.|
| Promise\<boolean> | Promise used to return the result. The value **true** means that network sharing is in progress, and **false** means the opposite.|
@@ -140,11 +175,27 @@ Starts network sharing of a specified type. This API uses an asynchronous callba
...
@@ -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.|
| 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\<void> | Yes | Callback used to return the result.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
@@ -203,11 +270,25 @@ Stops network sharing of a specified type. This API uses an asynchronous callbac
...
@@ -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.|
| 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\<void> | Yes | Callback used to return the result.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
@@ -495,11 +660,22 @@ Obtains the network sharing state of the specified type. This API uses an asynch
...
@@ -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.|
| 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.|
| callback | AsyncCallback\<[SharingIfaceState](#sharingifacestate)> | Yes | Callback used to return the network sharing state.|
| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.|
| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.|
@@ -559,11 +746,22 @@ Obtains regular expressions of NICs of a specified type. This API uses an asynch
...
@@ -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.|
| 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\<Array\<string>> | Yes | Callback used to return an array of regular expressions.|
| callback | AsyncCallback\<Array\<string>> | Yes | Callback used to return an array of regular expressions.|
@@ -679,12 +900,18 @@ Subscribes to network sharing state changes of a specified NIC. This API uses an
...
@@ -679,12 +900,18 @@ Subscribes to network sharing state changes of a specified NIC. This API uses an
| type | string | Yes | Event name.|
| 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.|
| callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | Yes | Callback invoked when the network sharing state of the specified NIC changes.|
| 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.|
The **socket** module implements socket connection management and operation.
> **NOTE**
>
> **NOTE**<br>
> 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.
> 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.
| Promise\<void\> | Promise used to return the result.|
| Promise\<void\> | Promise used to return the result.|
**Example**
**Example**
...
@@ -123,6 +135,13 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p
...
@@ -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).|
| options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example**
**Example**
```js
```js
...
@@ -162,10 +181,17 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p
...
@@ -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).|
| options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).|
@@ -346,6 +378,12 @@ Sets other properties of the UDPSocket connection. This API uses an asynchronous
...
@@ -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).|
| options | [UDPExtraOptions](#udpextraoptions) | Yes | Other properties of the UDPSocket connection. For details, see [UDPExtraOptions](#udpextraoptions).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
Disables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
Disables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**<br/>
>**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.
>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.
// 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.
Disables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
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**<br/>
>**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.
>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.
// 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',callback1);
udp.off('listening');
udp.off('listening');
letcallback2=()=>{
letcallback2=()=>{
console.log("on close, success");
console.log("on close, success");
}
}
udp.on('close',callback2);
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',callback2);
udp.off('close');
udp.off('close');
```
```
...
@@ -563,7 +608,6 @@ Enables listening for error events of the UDPSocket connection. This API uses an
...
@@ -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.<br/>**error**: error event|
| type | string | Yes | Type of the event to subscribe to.<br/>**error**: error event|
| callback | ErrorCallback | Yes | Callback used to return the result. |
| callback | ErrorCallback | Yes | Callback used to return the result. |
Disables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
Disables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**<br/>
>**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.
>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.
// 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',callback);
udp.off('error');
udp.off('error');
```
```
...
@@ -668,6 +712,12 @@ Defines information about the socket connection.
...
@@ -668,6 +712,12 @@ Defines information about the socket connection.
| port | number | Yes | Port number. The value ranges from **0** to **65535**. |
| port | number | Yes | Port number. The value ranges from **0** to **65535**. |
| size | number | Yes | Length of the server response message, in bytes. |
| 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
## socket.constructTCPSocketInstance
constructTCPSocketInstance\(\): TCPSocket
constructTCPSocketInstance\(\): TCPSocket
...
@@ -679,7 +729,7 @@ Creates a **TCPSocket** object.
...
@@ -679,7 +729,7 @@ Creates a **TCPSocket** object.
@@ -846,6 +923,13 @@ Sends data over a TCPSocket connection. This API uses an asynchronous callback t
...
@@ -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).|
| options | [TCPSendOptions](#tcpsendoptions) | Yes | Parameters for sending data over the TCPSocket connection. For details, see [TCPSendOptions](#tcpsendoptions).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
@@ -1150,6 +1274,13 @@ Sets other properties of the TCPSocket connection. This API uses an asynchronous
...
@@ -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).|
| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
Disables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
Disables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**<br/>
>**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.
>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.
// 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',callback);
tcp.off('message');
tcp.off('message');
```
```
...
@@ -1305,7 +1442,6 @@ Enables listening for connection or close events of the TCPSocket connection. Th
...
@@ -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.<br/><br>- **connect**: connection event<br>- **close**: close event|
| type | string | Yes | Type of the event to subscribe to.<br/><br>- **connect**: connection event<br>- **close**: close event|
| callback | Callback\<void\> | Yes | Callback used to return the result. |
| callback | Callback\<void\> | Yes | Callback used to return the result. |
Disables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
Disables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**<br/>
>**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.
>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.
// 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',callback1);
tcp.off('connect');
tcp.off('connect');
letcallback2=()=>{
letcallback2=()=>{
console.log("on close success");
console.log("on close success");
}
}
tcp.on('close',callback2);
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.
Disables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
Disables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**<br/>
>**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.
>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.
// 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',callback);
tcp.off('error');
tcp.off('error');
```
```
...
@@ -1452,7 +1588,13 @@ Defines other properties of the TCPSocket connection.
...
@@ -1452,7 +1588,13 @@ Defines other properties of the TCPSocket connection.
| receiveBufferSize | number | No | Size of the receive buffer, in bytes. |
| receiveBufferSize | number | No | Size of the receive buffer, in bytes. |
| sendBufferSize | number | No | Size of the send 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**. |
| 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.constructTLSSocketInstance<sup>9+</sup>
## socket.constructTLSSocketInstance<sup>9+</sup>
...
@@ -1465,7 +1607,7 @@ Creates a **TLSSocket** object.
...
@@ -1465,7 +1607,7 @@ Creates a **TLSSocket** object.
The **webSocket** module implements WebSocket connection management and operation.
> **NOTE**
> **NOTE**<br>
> 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.
>
>
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the [createWebSocket](#websocketcreatewebsocket) API to create a [WebSocket](#websocket) object and then use the [connect](#connect) API to connect to the server. If the connection is successful, the client will receive a callback of the [open](#onopen) event. Then, the client can communicate with the server using the [send](#send) API. When the server sends a message to the client, the client will receive a callback of the [message](#onmessage) event. If the client no longer needs this connection, it can call the [close](#close) API to disconnect from the server. Then, the client will receive a callback of the [close](#onclose) event.
You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the [createWebSocket](#websocketcreatewebsocket) API to create a [WebSocket](#websocket) object and then use the [connect](#connect) API to connect to the server. If the connection is successful, the client will receive a callback of the [open](#onopen) event. Then, the client can communicate with the server using the [send](#send) API. When the server sends a message to the client, the client will receive a callback of the [message](#onmessage) event. If the client no longer needs this connection, it can call the [close](#close) API to disconnect from the server. Then, the client will receive a callback of the [close](#onclose) event.
...
@@ -17,7 +16,7 @@ If an error occurs in any of the preceding processes, the client will receive a
...
@@ -17,7 +16,7 @@ If an error occurs in any of the preceding processes, the client will receive a
importwebSocketfrom'@ohos.net.webSocket';
importwebSocketfrom'@ohos.net.webSocket';
```
```
## Complete Example
## Examples
```js
```js
importwebSocketfrom'@ohos.net.webSocket';
importwebSocketfrom'@ohos.net.webSocket';
...
@@ -37,7 +36,7 @@ ws.on('open', (err, value) => {
...
@@ -37,7 +36,7 @@ ws.on('open', (err, value) => {
});
});
ws.on('message',(err,value)=>{
ws.on('message',(err,value)=>{
console.log("on message, message:"+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.
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.
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.
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.
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.
>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.
>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.
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.
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.
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.
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.
>The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\).
>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.
>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
...
@@ -507,7 +559,7 @@ Enables listening for the **close** events of a WebSocket connection. This API u
```js
```js
letws=webSocket.createWebSocket();
letws=webSocket.createWebSocket();
ws.on('close',(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);
>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.
>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.
>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.
>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.
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.
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.