提交 661ccb4a 编写于 作者: S shawn_he

update doc

Signed-off-by: Nshawn_he <shawn.he@huawei.com>
上级 80ff84eb
...@@ -49,44 +49,43 @@ let httpRequest = http.createHttp(); ...@@ -49,44 +49,43 @@ let httpRequest = http.createHttp();
// This API is used to listen for the HTTP Response Header event, which is returned earlier than the result of the HTTP request. It is up to you whether to listen for HTTP Response Header events. // This API is used to listen for the HTTP Response Header event, which is returned earlier than the result of the HTTP request. It is up to you whether to listen for HTTP Response Header events.
// on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8. // on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8.
httpRequest.on('headersReceive', (header) => { httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header)); console.info('header: ' + JSON.stringify(header));
}); });
httpRequest.request( httpRequest.request(
// Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL. // Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL.
"EXAMPLE_URL", {
{ method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET. // You can add header fields based on service requirements.
// You can add header fields based on service requirements. header: {
header: { 'Content-Type': 'application/json'
'Content-Type': 'application/json' },
}, // This field is used to transfer data when the POST request is used.
// This field is used to transfer data when the POST request is used. extraData: {
extraData: { "data": "data to send",
"data": "data to send", },
}, expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data.
expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data. usingCache: true, // Optional. The default value is true.
usingCache: true, // Optional. The default value is true. priority: 1, // Optional. The default value is 1.
priority: 1, // Optional. The default value is 1. connectTimeout: 60000 // Optional. The default value is 60000, in ms.
connectTimeout: 60000 // Optional. The default value is 60000, in ms. readTimeout: 60000, // Optional. The default value is 60000, in ms.
readTimeout: 60000, // Optional. The default value is 60000, in ms. usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system.
usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system. usingProxy: false, // Optional. By default, network proxy is not used. This field is supported since API 10.
usingProxy: false, // Optional. By default, network proxy is not used. This field is supported since API 10. }, (err, data) => {
}, (err, data) => { if (!err) {
if (!err) { // data.result carries the HTTP response. Parse the response based on service requirements.
// data.result carries the HTTP response. Parse the response based on service requirements. console.info('Result:' + JSON.stringify(data.result));
console.info('Result:' + JSON.stringify(data.result)); console.info('code:' + JSON.stringify(data.responseCode));
console.info('code:' + JSON.stringify(data.responseCode)); // data.header carries the HTTP response header. Parse the content based on service requirements.
// data.header carries the HTTP response header. Parse the content based on service requirements. console.info('header:' + JSON.stringify(data.header));
console.info('header:' + JSON.stringify(data.header)); console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
console.info('cookies:' + JSON.stringify(data.cookies)); // 8+ } else {
} else { console.info('error:' + JSON.stringify(err));
console.info('error:' + JSON.stringify(err)); // Unsubscribe from HTTP Response Header events.
// Unsubscribe from HTTP Response Header events. httpRequest.off('headersReceive');
httpRequest.off('headersReceive'); // Call the destroy() method to release resources after HttpRequest is complete.
// Call the destroy() method to release resources after HttpRequest is complete. httpRequest.destroy();
httpRequest.destroy();
}
} }
}
); );
``` ```
...@@ -108,61 +107,56 @@ import http from '@ohos.net.http' ...@@ -108,61 +107,56 @@ import http from '@ohos.net.http'
let httpRequest = http.createHttp(); let httpRequest = http.createHttp();
// Subscribe to HTTP response header events. // Subscribe to HTTP response header events.
httpRequest.on('headersReceive', (header) => { httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header)); console.info('header: ' + JSON.stringify(header));
}); });
// Subscribe to events indicating receiving of HTTP streaming responses. // Subscribe to events indicating receiving of HTTP streaming responses.
let res = ''; let res = '';
httpRequest.on('dataReceive', (data) => { httpRequest.on('dataReceive', (data) => {
res += data; res += data;
console.info('res: ' + res); console.info('res: ' + res);
}); });
// Subscribe to events indicating completion of receiving HTTP streaming responses. // Subscribe to events indicating completion of receiving HTTP streaming responses.
httpRequest.on('dataEnd', () => { httpRequest.on('dataEnd', () => {
console.info('No more data in response, data receive end'); console.info('No more data in response, data receive end');
}); });
// Subscribe to events indicating progress of receiving HTTP streaming responses. // Subscribe to events indicating progress of receiving HTTP streaming responses.
httpRequest.on('dataProgress', (data) => { httpRequest.on('dataProgress', (data) => {
console.log("dataProgress receiveSize:" + data.receiveSize+ ", totalSize:" + data.totalSize); console.log("dataProgress receiveSize:" + data.receiveSize + ", totalSize:" + data.totalSize);
}); });
httpRequest.request2( httpRequest.request2(
// Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL. // Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL.
"EXAMPLE_URL", "EXAMPLE_URL",
{ {
method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET. method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
// You can add header fields based on service requirements. // You can add header fields based on service requirements.
header: { header: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}, },
// This field is used to transfer data when the POST request is used. // This field is used to transfer data when the POST request is used.
extraData: { extraData: {
"data": "data to send", "data": "data to send",
}, },
expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data. expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data.
usingCache: true, // Optional. The default value is true. usingCache: true, // Optional. The default value is true.
priority: 1, // Optional. The default value is 1. priority: 1, // Optional. The default value is 1.
connectTimeout: 60000 // Optional. The default value is 60000, in ms. connectTimeout: 60000 // Optional. The default value is 60000, in ms.
readTimeout: 60000, // Optional. The default value is 60000, in ms. If a large amount of data needs to be transmitted, you are advised to set this parameter to a larger value to ensure normal data transmission. readTimeout: 60000, // Optional. The default value is 60000, in ms. If a large amount of data needs to be transmitted, you are advised to set this parameter to a larger value to ensure normal data transmission.
usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system. usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system.
}, (err, data) => { }, (err, data) => {
console.info('error:' + JSON.stringify(err)); console.info('error:' + JSON.stringify(err));
console.info('ResponseCode :' + JSON.stringify(data)); console.info('ResponseCode :' + JSON.stringify(data));
// Unsubscribe from HTTP Response Header events. // Unsubscribe from HTTP Response Header events.
httpRequest.off('headersReceive'); httpRequest.off('headersReceive');
// Unregister the observer for events indicating receiving of HTTP streaming responses. // Unregister the observer for events indicating receiving of HTTP streaming responses.
httpRequest.off('dataReceive'); httpRequest.off('dataReceive');
// Unregister the observer for events indicating progress of receiving HTTP streaming responses. // Unregister the observer for events indicating progress of receiving HTTP streaming responses.
httpRequest.off('dataProgress'); httpRequest.off('dataProgress');
// Unregister the observer for events indicating completion of receiving HTTP streaming responses. // Unregister the observer for events indicating completion of receiving HTTP streaming responses.
httpRequest.off('dataEnd'); httpRequest.off('dataEnd');
// Call the destroy() method to release resources after HttpRequest is complete. // Call the destroy() method to release resources after HttpRequest is complete.
httpRequest.destroy(); httpRequest.destroy();
} }
); );
``` ```
\ No newline at end of file
## Samples
The following sample is provided to help you better understand how to develop the HTTP data request feature:
- [HTTP Data Request (ArkTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Connectivity/Http)
- [HTTP Communication (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/SmartChatEtsOH)
# Network Connection Management # Network Connection Management
## Introduction ## Introduction
The Network Connection Management module provides basic network management capabilities, including management of Wi-Fi/cellular/Ethernet connection priorities, network quality evaluation, subscription to network connection status changes, query of network connection information, and DNS resolution. 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** > **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). > 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 ## 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. - Producer: a provider of data networks, such as Wi-Fi, cellular, and Ethernet.
- 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. - Consumer: a user of data networks, for example, an application or a system service.
- 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. - 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** ## **Constraints**
- Programming language: C++ and JS
- System: Linux kernel - Programming language: C++ and JS
- 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. - 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 ## When to Use
Typical application scenarios of network connection management are as follows: 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 - Subscribing to status changes of the specified network
- Querying network connection information based on the data network - Obtaining the list of all registered networks
- Resolving the domain name of a network to obtain all IP addresses - 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. The following describes the development procedure specific to each application scenario.
## Available APIs ## Available APIs
For the complete list of APIs and example code, see [Network Connection Management](../reference/apis/js-apis-net-connection.md). For the complete list of APIs and example code, see [Network Connection Management](../reference/apis/js-apis-net-connection.md).
| Type| API| Description| | Type| API| Description|
...@@ -75,44 +82,46 @@ For the complete list of APIs and example code, see [Network Connection Manageme ...@@ -75,44 +82,46 @@ For the complete list of APIs and example code, see [Network Connection Manageme
```js ```js
// Import the connection namespace. // Import the connection namespace.
import connection from '@ohos.net.connection' import connection from '@ohos.net.connection'
let netCap = { let netCap = {
// Assume that the default network is Wi-Fi. If you need to create a cellular network connection, set the network type to CELLULAR. // Assume that the default network is Wi-Fi. If you need to create a cellular network connection, set the network type to CELLULAR.
bearerTypes: [connection.NetBearType.BEARER_CELLULAR], bearerTypes: [connection.NetBearType.BEARER_CELLULAR],
// Set the network capability to INTERNET. // Set the network capability to INTERNET.
networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET], networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET],
}; };
let netSpec = { let netSpec = {
netCapabilities: netCap, netCapabilities: netCap,
}; };
// Set the timeout value to 10s. The default value is 0. // Set the timeout value to 10s. The default value is 0.
let timeout = 10 * 1000; let timeout = 10 * 1000;
// Create a NetConnection object. // Create a NetConnection object.
let conn = connection.createNetConnection(netSpec, timeout); let conn = connection.createNetConnection(netSpec, timeout);
// Listen to network status change events. If the network is available, an on_netAvailable event is returned. // Listen to network status change events. If the network is available, an on_netAvailable event is returned.
conn.on('netAvailable', (data=> { conn.on('netAvailable', (data => {
console.log("net is available, netId is " + data.netId); 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. // Listen to network status change events. If the network is unavailable, an on_netUnavailable event is returned.
conn.on('netUnavailable', (data=> { conn.on('netUnavailable', (data => {
console.log("net is unavailable, netId is " + data.netId); console.log("net is unavailable, netId is " + data.netId);
})); }));
// Register an observer for network status changes. // Register an observer for network status changes.
conn.register((err, data) => {}); conn.register((err, data) => {
});
// Unregister the observer for network status changes.
conn.unregister((err, data) => {}); // Unregister the observer for network status changes.
conn.unregister((err, data) => {
});
``` ```
## Obtaining the List of All Registered Networks ## Obtaining the List of All Registered Networks
### How to Develop ### How to Develop
1. Import the connection namespace from **@ohos.net.connection.d.ts**. 1. Import the connection namespace from **@ohos.net.connection.d.ts**.
...@@ -120,21 +129,21 @@ For the complete list of APIs and example code, see [Network Connection Manageme ...@@ -120,21 +129,21 @@ For the complete list of APIs and example code, see [Network Connection Manageme
```js ```js
// Import the connection namespace. // Import the connection namespace.
import connection from '@ohos.net.connection' import connection from '@ohos.net.connection'
// Obtain the list of all connected networks. // Obtain the list of all connected networks.
connection.getAllNets((err, data) => { connection.getAllNets((err, data) => {
console.log(JSON.stringify(err)); console.log(JSON.stringify(err));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
if (data) { if (data) {
this.netList = data; this.netList = data;
} }
}) })
``` ```
## Querying Network Capability Information and Connection Information of Specified Data Network ## Querying Network Capability Information and Connection Information of Specified Data Network
### How to Develop ### How to Develop
1. Import the connection namespace from **@ohos.net.connection.d.ts**. 1. Import the connection namespace from **@ohos.net.connection.d.ts**.
...@@ -146,89 +155,89 @@ For the complete list of APIs and example code, see [Network Connection Manageme ...@@ -146,89 +155,89 @@ For the complete list of APIs and example code, see [Network Connection Manageme
```js ```js
// Import the connection namespace. // Import the connection namespace.
import connection from '@ohos.net.connection' import connection from '@ohos.net.connection'
// Call getDefaultNet to obtain the default data network specified by **NetHandle**. // Call getDefaultNet to obtain the default data network specified by **NetHandle**.
connection.getDefaultNet((err, data) => { connection.getDefaultNet((err, data) => {
console.log(JSON.stringify(err)); console.log(JSON.stringify(err));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
if (data) { if (data) {
this.netHandle = 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. // Obtain the network capability information of the data network specified by **NetHandle**. The capability information includes information such as the network type and specific network capabilities.
connection.getNetCapabilities(this.netHandle, (err, data) => { connection.getNetCapabilities(this.netHandle, (err, data) => {
console.log(JSON.stringify(err)); console.log(JSON.stringify(err));
// Obtain the network type via bearerTypes. // Obtain the network type via bearerTypes.
for (let item of data.bearerTypes) { for (let item of data.bearerTypes) {
if (item == 0) { if (item == 0) {
// Cellular network // Cellular network
console.log(JSON.stringify("BEARER_CELLULAR")); console.log(JSON.stringify("BEARER_CELLULAR"));
} else if (item == 1) { } else if (item == 1) {
// Wi-Fi network // Wi-Fi network
console.log(JSON.stringify("BEARER_WIFI")); console.log(JSON.stringify("BEARER_WIFI"));
} else if (item == 3) { } else if (item == 3) {
// Ethernet network // Ethernet network
console.log(JSON.stringify("BEARER_ETHERNET")); console.log(JSON.stringify("BEARER_ETHERNET"));
} }
} }
// Obtain the specific network capabilities via networkCap. // Obtain the specific network capabilities via networkCap.
for (let item of data.networkCap) { for (let item of data.networkCap) {
if (item == 0) { if (item == 0) {
// The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages. // The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages.
console.log(JSON.stringify("NET_CAPABILITY_MMS")); console.log(JSON.stringify("NET_CAPABILITY_MMS"));
} else if (item == 11) { } else if (item == 11) {
// The network traffic is not metered. // The network traffic is not metered.
console.log(JSON.stringify("NET_CAPABILITY_NOT_METERED")); console.log(JSON.stringify("NET_CAPABILITY_NOT_METERED"));
} else if (item == 12) { } else if (item == 12) {
// The network has the Internet access capability, which is set by the network provider. // The network has the Internet access capability, which is set by the network provider.
console.log(JSON.stringify("NET_CAPABILITY_INTERNET")); console.log(JSON.stringify("NET_CAPABILITY_INTERNET"));
} else if (item == 15) { } else if (item == 15) {
// The network does not use a Virtual Private Network (VPN). // The network does not use a Virtual Private Network (VPN).
console.log(JSON.stringify("NET_CAPABILITY_NOT_VPN")); console.log(JSON.stringify("NET_CAPABILITY_NOT_VPN"));
} else if (item == 16) { } else if (item == 16) {
// The Internet access capability of the network is successfully verified by the connection management module. // The Internet access capability of the network is successfully verified by the connection management module.
console.log(JSON.stringify("NET_CAPABILITY_VALIDATED")); console.log(JSON.stringify("NET_CAPABILITY_VALIDATED"));
} }
} }
}) })
// Obtain the connection information of the data network specified by NetHandle. Connection information includes link and route information. // Obtain the connection information of the data network specified by NetHandle. Connection information includes link and route information.
connection.getConnectionProperties(this.netHandle, (err, data) => { connection.getConnectionProperties(this.netHandle, (err, data) => {
console.log(JSON.stringify(err)); console.log(JSON.stringify(err));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}) })
// Call getAllNets to obtain the list of all connected networks via Array<NetHandle>. // Call getAllNets to obtain the list of all connected networks via Array<NetHandle>.
connection.getAllNets((err, data) => { connection.getAllNets((err, data) => {
console.log(JSON.stringify(err)); console.log(JSON.stringify(err));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
if (data) { if (data) {
this.netList = data; this.netList = data;
} }
}) })
for (let item of this.netList) { for (let item of this.netList) {
// Obtain the network capability information of the network specified by each netHandle on the network list cyclically. // Obtain the network capability information of the network specified by each netHandle on the network list cyclically.
connection.getNetCapabilities(item, (err, data) => { connection.getNetCapabilities(item, (err, data) => {
console.log(JSON.stringify(err)); console.log(JSON.stringify(err));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}) })
// Obtain the connection information of the network specified by each netHandle on the network list cyclically. // Obtain the connection information of the network specified by each netHandle on the network list cyclically.
connection.getConnectionProperties(item, (err, data) => { connection.getConnectionProperties(item, (err, data) => {
console.log(JSON.stringify(err)); console.log(JSON.stringify(err));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}) })
} }
``` ```
## Resolving the domain name of a network to obtain all IP addresses ## Resolving the domain name of a network to obtain all IP addresses
### How to Develop ### How to Develop
1. Import the connection namespace from **@ohos.net.connection.d.ts**. 1. Import the connection namespace from **@ohos.net.connection.d.ts**.
...@@ -236,11 +245,11 @@ For the complete list of APIs and example code, see [Network Connection Manageme ...@@ -236,11 +245,11 @@ For the complete list of APIs and example code, see [Network Connection Manageme
```js ```js
// Import the connection namespace. // Import the connection namespace.
import connection from '@ohos.net.connection' import connection from '@ohos.net.connection'
// Use the default network to resolve the host name to obtain the list of all IP addresses. // Use the default network to resolve the host name to obtain the list of all IP addresses.
connection.getAddressesByName(this.host, (err, data) => { connection.getAddressesByName(this.host, (err, data) => {
console.log(JSON.stringify(err)); console.log(JSON.stringify(err));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}) })
``` ```
# Ethernet Connection # Ethernet Connection
## Introduction ## Introduction
The Ethernet Connection module allows a device to access the Internet through a network cable.
After a device is connected to the Ethernet through a network cable, the device can obtain a series of network attributes, such as the dynamically allocated IP address, subnet mask, gateway, and DNS. You can manually configure and obtain the network attributes of the device in static mode. The Ethernet Connection module allows a device to access the Internet through a network cable. After a device is connected to the Ethernet through a network cable, the device can obtain a series of network attributes, such as the dynamically allocated IP address, subnet mask, gateway, and DNS. You can manually configure and obtain the network attributes of the device in static mode.
> **NOTE** > **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). > 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** ## **Constraints**
- Programming language: C++ and JS
- System: Linux kernel - Programming language: C++ and JS
- 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. - 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 ## When to Use
Typical application scenarios of Ethernet connection are as follows: Typical application scenarios of Ethernet connection are as follows:
- Dynamically assigning a series of network attributes, such as the IP address, subnet mask, gateway, and DNS in DHCP mode to enable network access
- Configuring a series of network attributes, such as the IP address, subnet mask, gateway, and DNS, in static mode to enable network access. - Dynamically assigning a series of network attributes, such as the IP address, subnet mask, gateway, and DNS in DHCP mode to enable network access
- Configuring a series of network attributes, such as the IP address, subnet mask, gateway, and DNS, in static mode to enable network access.
The following describes the development procedure specific to each application scenario. The following describes the development procedure specific to each application scenario.
## Available APIs ## Available APIs
For the complete list of APIs and example code, see [Ethernet Connection](../reference/apis/js-apis-net-ethernet.md). For the complete list of APIs and example code, see [Ethernet Connection](../reference/apis/js-apis-net-ethernet.md).
| Type| API| Description| | Type| API| Description|
...@@ -28,6 +32,8 @@ For the complete list of APIs and example code, see [Ethernet Connection](../ref ...@@ -28,6 +32,8 @@ For the complete list of APIs and example code, see [Ethernet Connection](../ref
| ohos.net.ethernet | function getIfaceConfig(iface: string, callback: AsyncCallback\<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 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 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.| | 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.|
| ohos.net.ethernet | function on(type: 'interfaceStateChange', callback: Callback\<{ iface: string, active: boolean }\>): void; | Subscribes to interface state change events.|
| ohos.net.ethernet | function off(type: 'interfaceStateChange', callback?: Callback\<{ iface: string, active: boolean }\>): void; | Unsubscribes from interface state change events.|
## Ethernet Connection – DHCP Mode ## Ethernet Connection – DHCP Mode
...@@ -39,44 +45,45 @@ For the complete list of APIs and example code, see [Ethernet Connection](../ref ...@@ -39,44 +45,45 @@ For the complete list of APIs and example code, see [Ethernet Connection](../ref
```js ```js
// Import the ethernet namespace from @ohos.net.ethernet. // Import the ethernet namespace from @ohos.net.ethernet.
import ethernet from '@ohos.net.ethernet' import ethernet from '@ohos.net.ethernet'
// Call getAllActiveIfaces to obtain the list of all active network ports. // Call getAllActiveIfaces to obtain the list of all active network ports.
ethernet.getAllActiveIfaces((error, data) => { ethernet.getAllActiveIfaces((error, data) => {
if (error) { if (error) {
console.log("getAllActiveIfaces callback error = " + error); console.log("getAllActiveIfaces callback error = " + error);
} else { } else {
console.log("getAllActiveIfaces callback data.length = " + data.length); console.log("getAllActiveIfaces callback data.length = " + data.length);
for (let i = 0; i < data.length; i++) { for (let i = 0; i < data.length; i++) {
console.log("getAllActiveIfaces callback = " + data[i]); console.log("getAllActiveIfaces callback = " + data[i]);
} }
} }
}); });
// Call isIfaceActive to check whether the specified network port is active. // Call isIfaceActive to check whether the specified network port is active.
ethernet.isIfaceActive("eth0", (error, data) => { ethernet.isIfaceActive("eth0", (error, data) => {
if (error) { if (error) {
console.log("isIfaceActive callback error = " + error); console.log("isIfaceActive callback error = " + error);
} else { } else {
console.log("isIfaceActive callback = " + data); console.log("isIfaceActive callback = " + data);
} }
}); });
// Call getIfaceConfig to obtain the network attributes of the specified Ethernet network. // Call getIfaceConfig to obtain the network attributes of the specified Ethernet network.
ethernet.getIfaceConfig("eth0", (error, data) => { ethernet.getIfaceConfig("eth0", (error, data) => {
if (error) { if (error) {
console.log("getIfaceConfig callback error = " + error); console.log("getIfaceConfig callback error = " + error);
} else { } else {
console.log("getIfaceConfig callback mode = " + data.mode); console.log("getIfaceConfig callback mode = " + data.mode);
console.log("getIfaceConfig callback ipAddr = " + data.ipAddr); console.log("getIfaceConfig callback ipAddr = " + data.ipAddr);
console.log("getIfaceConfig callback routeAddr = " + data.routeAddr); console.log("getIfaceConfig callback routeAddr = " + data.routeAddr);
console.log("getIfaceConfig callback gateAddr = " + data.gateAddr); console.log("getIfaceConfig callback gateAddr = " + data.gateAddr);
console.log("getIfaceConfig callback maskAddr = " + data.maskAddr); console.log("getIfaceConfig callback maskAddr = " + data.maskAddr);
console.log("getIfaceConfig callback dns0Addr = " + data.dns0Addr); console.log("getIfaceConfig callback dns0Addr = " + data.dns0Addr);
console.log("getIfaceConfig callback dns1Addr = " + data.dns1Addr); console.log("getIfaceConfig callback dns1Addr = " + data.dns1Addr);
} }
}); });
``` ```
## Ethernet Connection – Static Mode ## Ethernet Connection – Static Mode
### How to Develop ### How to Develop
...@@ -90,51 +97,75 @@ For the complete list of APIs and example code, see [Ethernet Connection](../ref ...@@ -90,51 +97,75 @@ For the complete list of APIs and example code, see [Ethernet Connection](../ref
```js ```js
// Import the ethernet namespace from @ohos.net.ethernet. // Import the ethernet namespace from @ohos.net.ethernet.
import ethernet from '@ohos.net.ethernet' import ethernet from '@ohos.net.ethernet'
// Call getAllActiveIfaces to obtain the list of all active network ports. // Call getAllActiveIfaces to obtain the list of all active network ports.
ethernet.getAllActiveIfaces((error, data) => { ethernet.getAllActiveIfaces((error, data) => {
if (error) { if (error) {
console.log("getAllActiveIfaces callback error = " + error); console.log("getAllActiveIfaces callback error = " + error);
} else { } else {
console.log("getAllActiveIfaces callback data.length = " + data.length); console.log("getAllActiveIfaces callback data.length = " + data.length);
for (let i = 0; i < data.length; i++) { for (let i = 0; i < data.length; i++) {
console.log("getAllActiveIfaces callback = " + data[i]); console.log("getAllActiveIfaces callback = " + data[i]);
} }
} }
}); });
// Call isIfaceActive to check whether the specified network port is active. // Call isIfaceActive to check whether the specified network port is active.
ethernet.isIfaceActive("eth0", (error, data) => { ethernet.isIfaceActive("eth0", (error, data) => {
if (error) { if (error) {
console.log("isIfaceActive callback error = " + error); console.log("isIfaceActive callback error = " + error);
} else { } else {
console.log("isIfaceActive callback = " + data); console.log("isIfaceActive callback = " + data);
} }
}); });
// Call setIfaceConfig to configure the network attributes of the specified Ethernet network. // Call setIfaceConfig to configure the network attributes of the specified Ethernet network.
ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.xx.xx", routeAddr:"192.168.xx.xx", ethernet.setIfaceConfig("eth0", {
gateAddr:"192.168.xx.xx", maskAddr:"255.255.xx.xx", dnsAddr0:"1.1.xx.xx", dnsAddr1:"2.2.xx.xx"},(error) => { mode: ethernet.STATIC, ipAddr: "192.168.xx.xx", routeAddr: "192.168.xx.xx",
if (error) { gateAddr: "192.168.xx.xx", maskAddr: "255.255.xx.xx", dnsAddr0: "1.1.xx.xx", dnsAddr1: "2.2.xx.xx"
console.log("setIfaceConfig callback error = " + error); }, (error) => {
} else { if (error) {
console.log("setIfaceConfig callback ok "); console.log("setIfaceConfig callback error = " + error);
} } else {
}); console.log("setIfaceConfig callback ok ");
}
// Call getIfaceConfig to obtain the network attributes of the specified Ethernet network. });
ethernet.getIfaceConfig("eth0", (error, data) => {
if (error) { // Call getIfaceConfig to obtain the network attributes of the specified Ethernet network.
console.log("getIfaceConfig callback error = " + error); ethernet.getIfaceConfig("eth0", (error, data) => {
} else { if (error) {
console.log("getIfaceConfig callback mode = " + data.mode); console.log("getIfaceConfig callback error = " + error);
console.log("getIfaceConfig callback ipAddr = " + data.ipAddr); } else {
console.log("getIfaceConfig callback routeAddr = " + data.routeAddr); console.log("getIfaceConfig callback mode = " + data.mode);
console.log("getIfaceConfig callback gateAddr = " + data.gateAddr); console.log("getIfaceConfig callback ipAddr = " + data.ipAddr);
console.log("getIfaceConfig callback maskAddr = " + data.maskAddr); console.log("getIfaceConfig callback routeAddr = " + data.routeAddr);
console.log("getIfaceConfig callback dns0Addr = " + data.dns0Addr); console.log("getIfaceConfig callback gateAddr = " + data.gateAddr);
console.log("getIfaceConfig callback dns1Addr = " + data.dns1Addr); console.log("getIfaceConfig callback maskAddr = " + data.maskAddr);
} console.log("getIfaceConfig callback dns0Addr = " + data.dns0Addr);
}); console.log("getIfaceConfig callback dns1Addr = " + data.dns1Addr);
}
});
```
## Subscribes the status change of network device interfaces.
### How to Develop
1. Import the **ethernet** namespace from **@ohos.net.ethernet**.
2. Call the **on()** method to subscribe to **interfaceStateChange** events. It is up to you whether to listen for **interfaceStateChange** events.
3. Check whether an **interfaceStateChange** event is triggered when the interface state changes.
4. Call the **off()** method to unsubscribe from **interfaceStateChange** events.
```js
// Import the ethernet namespace from @ohos.net.ethernet.
import ethernet from '@ohos.net.ethernet'
// Subscribe to interfaceStateChange events.
ethernet.on('interfaceStateChange', ((data) => {
console.log(JSON.stringify(data));
}));
// Unsubscribe from interfaceStateChange events.
ethernet.off('interfaceStateChange');
``` ```
# Network Sharing # Network Sharing
## Introduction ## Introduction
The Network Sharing module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing. It also allows you to query the network sharing state and shared mobile data volume. 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** > **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). > 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 ## Basic Concepts
- Wi-Fi sharing: Shares the network through a Wi-Fi hotspot.
- Bluetooth sharing: Shares the network through Bluetooth. - Wi-Fi sharing: Shares the network through a Wi-Fi hotspot.
- USB tethering: Shares the network using a USB flash drive. - Bluetooth sharing: Shares the network through Bluetooth.
- USB tethering: Shares the network using a USB flash drive.
## **Constraints** ## **Constraints**
- Programming language: C++ and JS
- System: Linux kernel - Programming language: C++ and JS
- 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. - 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 ## When to Use
Typical network sharing scenarios are as follows: Typical network sharing scenarios are as follows:
- Enabling network sharing
- Disabling network sharing - Enabling network sharing
- Obtaining the data traffic of the shared network - Disabling network sharing
- Obtaining the data traffic of the shared network
The following describes the development procedure specific to each application scenario. The following describes the development procedure specific to each application scenario.
## Available APIs ## Available APIs
For the complete list of APIs and example code, see [Network Sharing](../reference/apis/js-apis-net-sharing.md). For the complete list of APIs and example code, see [Network Sharing](../reference/apis/js-apis-net-sharing.md).
| Type| API| Description| | Type| API| Description|
...@@ -54,18 +61,18 @@ For the complete list of APIs and example code, see [Network Sharing](../referen ...@@ -54,18 +61,18 @@ For the complete list of APIs and example code, see [Network Sharing](../referen
```js ```js
// Import the sharing namespace from @ohos.net.sharing. // Import the sharing namespace from @ohos.net.sharing.
import sharing from '@ohos.net.sharing' import sharing from '@ohos.net.sharing'
// Subscribe to network sharing state changes. // Subscribe to network sharing state changes.
sharing.on('sharingStateChange', (error, data) => { sharing.on('sharingStateChange', (error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
// Call startSharing to start network sharing of the specified type. // Call startSharing to start network sharing of the specified type.
sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
## Disabling network sharing ## Disabling network sharing
...@@ -79,18 +86,18 @@ For the complete list of APIs and example code, see [Network Sharing](../referen ...@@ -79,18 +86,18 @@ For the complete list of APIs and example code, see [Network Sharing](../referen
```js ```js
// Import the sharing namespace from @ohos.net.sharing. // Import the sharing namespace from @ohos.net.sharing.
import sharing from '@ohos.net.sharing' import sharing from '@ohos.net.sharing'
// Subscribe to network sharing state changes. // Subscribe to network sharing state changes.
sharing.on('sharingStateChange', (error, data) => { sharing.on('sharingStateChange', (error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
// Call stopSharing to stop network sharing of the specified type. // Call stopSharing to stop network sharing of the specified type.
sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
## Obtaining the data traffic of the shared network ## Obtaining the data traffic of the shared network
...@@ -104,27 +111,27 @@ For the complete list of APIs and example code, see [Network Sharing](../referen ...@@ -104,27 +111,27 @@ For the complete list of APIs and example code, see [Network Sharing](../referen
```js ```js
// Import the sharing namespace from @ohos.net.sharing. // Import the sharing namespace from @ohos.net.sharing.
import sharing from '@ohos.net.sharing' import sharing from '@ohos.net.sharing'
// Call startSharing to start network sharing of the specified type. // Call startSharing to start network sharing of the specified type.
sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
// Call getStatsTotalBytes to obtain the data traffic generated during data sharing. // Call getStatsTotalBytes to obtain the data traffic generated during data sharing.
sharing.getStatsTotalBytes((error, data) => { sharing.getStatsTotalBytes((error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
// Call stopSharing to stop network sharing of the specified type and clear the data volume of network sharing. // Call stopSharing to stop network sharing of the specified type and clear the data volume of network sharing.
sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
// Call getStatsTotalBytes again. The data volume of network sharing has been cleared. // Call getStatsTotalBytes again. The data volume of network sharing has been cleared.
sharing.getStatsTotalBytes((error, data) => { sharing.getStatsTotalBytes((error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -186,136 +186,136 @@ TLS Socket connection process on the client: ...@@ -186,136 +186,136 @@ TLS Socket connection process on the client:
```js ```js
import socket from '@ohos.net.socket' import socket from '@ohos.net.socket'
// Create a TLS Socket connection (for two-way authentication). // Create a TLS Socket connection (for two-way authentication).
let tlsTwoWay = socket.constructTLSSocketInstance(); let tlsTwoWay = socket.constructTLSSocketInstance();
// Subscribe to TLS Socket connection events. // Subscribe to TLS Socket connection events.
tlsTwoWay.on('message', value => { tlsTwoWay.on('message', value => {
console.log("on message") console.log("on message")
let buffer = value.message let buffer = value.message
let dataView = new DataView(buffer) let dataView = new DataView(buffer)
let str = "" let str = ""
for (let i = 0; i < dataView.byteLength; ++i) { for (let i = 0; i < dataView.byteLength; ++i) {
str += String.fromCharCode(dataView.getUint8(i)) str += String.fromCharCode(dataView.getUint8(i))
} }
console.log("on connect received:" + str) console.log("on connect received:" + str)
}); });
tlsTwoWay.on('connect', () => { tlsTwoWay.on('connect', () => {
console.log("on connect") console.log("on connect")
}); });
tlsTwoWay.on('close', () => { tlsTwoWay.on('close', () => {
console.log("on close") console.log("on close")
}); });
// Bind the local IP address and port number. // Bind the local IP address and port number.
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) { if (err) {
console.log('bind fail'); console.log('bind fail');
return; return;
} }
console.log('bind success'); console.log('bind success');
}); });
// Set the communication parameters. // Set the communication parameters.
let options = { let options = {
ALPNProtocols: ["spdy/1", "http/1.1"], ALPNProtocols: ["spdy/1", "http/1.1"],
// Set up a connection to the specified IP address and port number. // Set up a connection to the specified IP address and port number.
address: { address: {
address: "192.168.xx.xxx", address: "192.168.xx.xxx",
port: xxxx, // Port port: xxxx, // Port
family: 1, family: 1,
}, },
// Set the parameters used for authentication during communication. // Set the parameters used for authentication during communication.
secureOptions: { secureOptions: {
key: "xxxx", // Key key: "xxxx", // Key
cert: "xxxx", // Digital certificate cert: "xxxx", // Digital certificate
ca: ["xxxx"], // CA certificate ca: ["xxxx"], // CA certificate
passwd: "xxxx", // Password for generating the key passwd: "xxxx", // Password for generating the key
protocols: [socket.Protocol.TLSv12], // Communication protocol protocols: [socket.Protocol.TLSv12], // Communication protocol
useRemoteCipherPrefer: true, // Whether to preferentially use the peer cipher suite useRemoteCipherPrefer: true, // Whether to preferentially use the peer cipher suite
signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", // Signature algorithm signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", // Signature algorithm
cipherSuite: "AES256-SHA256", // Cipher suite cipherSuite: "AES256-SHA256", // Cipher suite
}, },
}; };
// Set up a connection. // Set up a connection.
tlsTwoWay.connect(options, (err, data) => { tlsTwoWay.connect(options, (err, data) => {
console.error(err); console.error(err);
console.log(data); console.log(data);
}); });
// Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events. // Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events.
tlsTwoWay.close((err) => { tlsTwoWay.close((err) => {
if (err) { if (err) {
console.log("close callback error = " + err); console.log("close callback error = " + err);
} else { } else {
console.log("close success"); console.log("close success");
} }
tlsTwoWay.off('message'); tlsTwoWay.off('message');
tlsTwoWay.off('connect'); tlsTwoWay.off('connect');
tlsTwoWay.off('close'); tlsTwoWay.off('close');
}); });
// Create a TLS Socket connection (for one-way authentication). // Create a TLS Socket connection (for one-way authentication).
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
// Subscribe to TLS Socket connection events. // Subscribe to TLS Socket connection events.
tlsTwoWay.on('message', value => { tlsTwoWay.on('message', value => {
console.log("on message") console.log("on message")
let buffer = value.message let buffer = value.message
let dataView = new DataView(buffer) let dataView = new DataView(buffer)
let str = "" let str = ""
for (let i = 0;i < dataView.byteLength; ++i) { for (let i = 0; i < dataView.byteLength; ++i) {
str += String.fromCharCode(dataView.getUint8(i)) str += String.fromCharCode(dataView.getUint8(i))
} }
console.log("on connect received:" + str) console.log("on connect received:" + str)
}); });
tlsTwoWay.on('connect', () => { tlsTwoWay.on('connect', () => {
console.log("on connect") console.log("on connect")
}); });
tlsTwoWay.on('close', () => { tlsTwoWay.on('close', () => {
console.log("on close") console.log("on close")
}); });
// Bind the local IP address and port number. // Bind the local IP address and port number.
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) { if (err) {
console.log('bind fail'); console.log('bind fail');
return; return;
} }
console.log('bind success'); console.log('bind success');
}); });
// Set the communication parameters. // Set the communication parameters.
let oneWayOptions = { let oneWayOptions = {
address: { address: {
address: "192.168.xxx.xxx", address: "192.168.xxx.xxx",
port: xxxx, port: xxxx,
family: 1, family: 1,
}, },
secureOptions: { secureOptions: {
ca: ["xxxx","xxxx"], // CA certificate ca: ["xxxx","xxxx"], // CA certificate
cipherSuite: "AES256-SHA256", // Cipher suite cipherSuite: "AES256-SHA256", // Cipher suite
}, },
}; };
// Set up a connection. // Set up a connection.
tlsOneWay.connect(oneWayOptions, (err, data) => { tlsOneWay.connect(oneWayOptions, (err, data) => {
console.error(err); console.error(err);
console.log(data); console.log(data);
}); });
// Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events. // Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events.
tlsTwoWay.close((err) => { tlsTwoWay.close((err) => {
if (err) { if (err) {
console.log("close callback error = " + err); console.log("close callback error = " + err);
} else { } else {
console.log("close success"); console.log("close success");
} }
tlsTwoWay.off('message'); tlsTwoWay.off('message');
tlsTwoWay.off('connect'); tlsTwoWay.off('connect');
tlsTwoWay.off('close'); tlsTwoWay.off('close');
}); });
``` ```
\ No newline at end of file
# WebSocket Connection # WebSocket Connection
## When to Use
## Use Cases
You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the **createWebSocket()** API to create a **WebSocket** object and then use the **connect()** API to connect to the server. If the connection is successful, the client will receive a callback of the **open** event. Then, the client can communicate with the server using the **send()** API. When the server sends a message to the client, the client will receive a callback of the **message** event. If the client no longer needs this connection, it can call the **close()** API to disconnect from the server. Then, the client will receive a callback of the **close** event. You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the **createWebSocket()** API to create a **WebSocket** object and then use the **connect()** API to connect to the server. If the connection is successful, the client will receive a callback of the **open** event. Then, the client can communicate with the server using the **send()** API. When the server sends a message to the client, the client will receive a callback of the **message** event. If the client no longer needs this connection, it can call the **close()** API to disconnect from the server. Then, the client will receive a callback of the **close** event.
If an error occurs in any of the preceding processes, the client will receive a callback of the **error** event. If an error occurs in any of the preceding processes, the client will receive a callback of the **error** event.
## Available APIs ## Available APIs
The WebSocket connection function is mainly implemented by the WebSocket module. To use related APIs, you must declare the **ohos.permission.INTERNET** permission. The following table describes the related APIs. The WebSocket connection function is mainly implemented by the WebSocket module. To use related APIs, you must declare the **ohos.permission.INTERNET** permission. The following table describes the related APIs.
| API | Description | | API| Description|
| -------- | -------- | | -------- | -------- |
| createWebSocket() | Creates a WebSocket connection. | | createWebSocket() | Creates a WebSocket connection.|
| connect() | Establishes a WebSocket connection to a given URL. | | connect() | Establishes a WebSocket connection to a given URL.|
| send() | Sends data through the WebSocket connection. | | send() | Sends data through the WebSocket connection.|
| close() | Closes a WebSocket connection. | | close() | Closes a WebSocket connection.|
| on(type: 'open') | Enables listening for **open** events of a WebSocket connection. | | on(type: 'open') | Enables listening for **open** events of a WebSocket connection.|
| off(type: 'open') | Disables listening for **open** events of a WebSocket connection. | | off(type: 'open') | Disables listening for **open** events of a WebSocket connection.|
| on(type: 'message') | Enables listening for **message** events of a WebSocket connection. | | on(type: 'message') | Enables listening for **message** events of a WebSocket connection.|
| off(type: 'message') | Disables listening for **message** events of a WebSocket connection. | | off(type: 'message') | Disables listening for **message** events of a WebSocket connection.|
| on(type: 'close') | Enables listening for **close** events of a WebSocket connection. | | on(type: 'close') | Enables listening for **close** events of a WebSocket connection.|
| off(type: 'close') | Disables listening for **close** events of a WebSocket connection. | | off(type: 'close') | Disables listening for **close** events of a WebSocket connection.|
| on(type: 'error') | Enables listening for **error** events of a WebSocket connection. | | on(type: 'error') | Enables listening for **error** events of a WebSocket connection.|
| off(type: 'error') | Disables listening for **error** events of a WebSocket connection. | | off(type: 'error') | Disables listening for **error** events of a WebSocket connection.|
## How to Develop ## How to Develop
1. Import the required WebSocket module. 1. Import the required webSocket module.
2. Create a **WebSocket** object. 2. Create a **WebSocket** object.
3. (Optional) Subscribe to WebSocket open, message, close, and error events. 3. (Optional) Subscribe to WebSocket **open**, **message**, **close**, and **error** events.
4. Establish a WebSocket connection to a given URL. 4. Establish a WebSocket connection to a given URL.
5. Close the WebSocket connection if it is no longer needed. 5. Close the WebSocket connection if it is no longer needed.
```js ```js
import webSocket from '@ohos.net.webSocket'; import webSocket from '@ohos.net.webSocket';
......
...@@ -173,7 +173,7 @@ Obtains system service information. ...@@ -173,7 +173,7 @@ Obtains system service information.
**Example** **Example**
```js ```js
import fileio from '@ohos.fileio' import fs from '@ohos.file.fs'
import hidebug from '@ohos.hidebug' import hidebug from '@ohos.hidebug'
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
...@@ -181,7 +181,7 @@ let context = featureAbility.getContext(); ...@@ -181,7 +181,7 @@ let context = featureAbility.getContext();
context.getFilesDir().then((data) => { context.getFilesDir().then((data) => {
var path = data + "/serviceInfo.txt" var path = data + "/serviceInfo.txt"
console.info("output path: " + path) console.info("output path: " + path)
let fd = fileio.openSync(path, 0o102, 0o666) let fd = fs.openSync(path, 0o102, 0o666)
var serviceId = 10 var serviceId = 10
var args = new Array("allInfo") var args = new Array("allInfo")
try { try {
...@@ -190,7 +190,7 @@ context.getFilesDir().then((data) => { ...@@ -190,7 +190,7 @@ context.getFilesDir().then((data) => {
console.info(error.code) console.info(error.code)
console.info(error.message) console.info(error.message)
} }
fileio.closeSync(fd); fs.closeSync(fd);
}) })
``` ```
...@@ -283,7 +283,7 @@ try { ...@@ -283,7 +283,7 @@ try {
startProfiling(filename : string) : void startProfiling(filename : string) : void
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.startJsCpuProfiling](#hidebugstartjscpuprofiling9) instead. > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.startJsCpuProfiling](#hidebugstartjscpuprofiling9).
Starts the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`. Starts the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`.
...@@ -309,7 +309,7 @@ hidebug.stopProfiling(); ...@@ -309,7 +309,7 @@ hidebug.stopProfiling();
stopProfiling() : void stopProfiling() : void
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.stopJsCpuProfiling](#hidebugstopjscpuprofiling9) instead. > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.stopJsCpuProfiling](#hidebugstopjscpuprofiling9).
Stops the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`. Stops the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`.
...@@ -329,7 +329,7 @@ hidebug.stopProfiling(); ...@@ -329,7 +329,7 @@ hidebug.stopProfiling();
dumpHeapData(filename : string) : void dumpHeapData(filename : string) : void
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.dumpJsHeapData](#hidebugdumpjsheapdata9) instead. > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.dumpJsHeapData](#hidebugdumpjsheapdata9).
Exports the heap data. Exports the heap data.
......
...@@ -48,19 +48,19 @@ Sets the network interface configuration. This API uses an asynchronous callback ...@@ -48,19 +48,19 @@ Sets the network interface configuration. This API uses an asynchronous callback
```js ```js
ethernet.setIfaceConfig("eth0", { ethernet.setIfaceConfig("eth0", {
mode: 0, mode: 0,
ipAddr: "192.168.xx.xxx", ipAddr: "192.168.xx.xxx",
route: "192.168.xx.xxx", route: "192.168.xx.xxx",
gateway: "192.168.xx.xxx", gateway: "192.168.xx.xxx",
netMask: "255.255.255.0", netMask: "255.255.255.0",
dnsServers: "1.1.1.1", dnsServers: "1.1.1.1",
domain: "2.2.2.2" domain: "2.2.2.2"
}, (error) => { }, (error) => {
if (error) { if (error) {
console.log("setIfaceConfig callback error = " + JSON.stringify(error)); console.log("setIfaceConfig callback error = " + JSON.stringify(error));
} else { } else {
console.log("setIfaceConfig callback ok "); console.log("setIfaceConfig callback ok ");
} }
}); });
``` ```
...@@ -106,17 +106,17 @@ Sets the network interface configuration. This API uses a promise to return the ...@@ -106,17 +106,17 @@ Sets the network interface configuration. This API uses a promise to return the
```js ```js
ethernet.setIfaceConfig("eth0", { ethernet.setIfaceConfig("eth0", {
mode: 0, mode: 0,
ipAddr: "192.168.xx.xxx", ipAddr: "192.168.xx.xxx",
route: "192.168.xx.xxx", route: "192.168.xx.xxx",
gateway: "192.168.xx.xxx", gateway: "192.168.xx.xxx",
netMask: "255.255.255.0", netMask: "255.255.255.0",
dnsServers: "1.1.1.1", dnsServers: "1.1.1.1",
domain: "2.2.2.2" domain: "2.2.2.2"
}).then(() => { }).then(() => {
console.log("setIfaceConfig promise ok "); console.log("setIfaceConfig promise ok ");
}).catch(error => { }).catch(error => {
console.log("setIfaceConfig promise error = " + JSON.stringify(error)); console.log("setIfaceConfig promise error = " + JSON.stringify(error));
}); });
``` ```
...@@ -154,17 +154,17 @@ Obtains the configuration of a network interface. This API uses an asynchronous ...@@ -154,17 +154,17 @@ Obtains the configuration of a network interface. This API uses an asynchronous
```js ```js
ethernet.getIfaceConfig("eth0", (error, value) => { ethernet.getIfaceConfig("eth0", (error, value) => {
if (error) { if (error) {
console.log("getIfaceConfig callback error = " + JSON.stringify(error)); console.log("getIfaceConfig callback error = " + JSON.stringify(error));
} else { } else {
console.log("getIfaceConfig callback mode = " + JSON.stringify(value.mode)); console.log("getIfaceConfig callback mode = " + JSON.stringify(value.mode));
console.log("getIfaceConfig callback ipAddr = " + JSON.stringify(value.ipAddr)); console.log("getIfaceConfig callback ipAddr = " + JSON.stringify(value.ipAddr));
console.log("getIfaceConfig callback route = " + JSON.stringify(value.route)); console.log("getIfaceConfig callback route = " + JSON.stringify(value.route));
console.log("getIfaceConfig callback gateway = " + JSON.stringify(value.gateway)); console.log("getIfaceConfig callback gateway = " + JSON.stringify(value.gateway));
console.log("getIfaceConfig callback netMask = " + JSON.stringify(value.netMask)); console.log("getIfaceConfig callback netMask = " + JSON.stringify(value.netMask));
console.log("getIfaceConfig callback dnsServers = " + JSON.stringify(value.dnsServers)); console.log("getIfaceConfig callback dnsServers = " + JSON.stringify(value.dnsServers));
console.log("getIfaceConfig callback domain = " + JSON.stringify(value.domain)); console.log("getIfaceConfig callback domain = " + JSON.stringify(value.domain));
} }
}); });
``` ```
...@@ -207,15 +207,15 @@ Obtains the configuration of a network interface. This API uses a promise to ret ...@@ -207,15 +207,15 @@ Obtains the configuration of a network interface. This API uses a promise to ret
```js ```js
ethernet.getIfaceConfig("eth0").then((data) => { ethernet.getIfaceConfig("eth0").then((data) => {
console.log("getIfaceConfig promise mode = " + JSON.stringify(data.mode)); console.log("getIfaceConfig promise mode = " + JSON.stringify(data.mode));
console.log("getIfaceConfig promise ipAddr = " + JSON.stringify(data.ipAddr)); console.log("getIfaceConfig promise ipAddr = " + JSON.stringify(data.ipAddr));
console.log("getIfaceConfig promise route = " + JSON.stringify(data.route)); console.log("getIfaceConfig promise route = " + JSON.stringify(data.route));
console.log("getIfaceConfig promise gateway = " + JSON.stringify(data.gateway)); console.log("getIfaceConfig promise gateway = " + JSON.stringify(data.gateway));
console.log("getIfaceConfig promise netMask = " + JSON.stringify(data.netMask)); console.log("getIfaceConfig promise netMask = " + JSON.stringify(data.netMask));
console.log("getIfaceConfig promise dnsServers = " + JSON.stringify(data.dnsServers)); console.log("getIfaceConfig promise dnsServers = " + JSON.stringify(data.dnsServers));
console.log("getIfaceConfig promise domain = " + JSON.stringify(data.domain)); console.log("getIfaceConfig promise domain = " + JSON.stringify(data.domain));
}).catch(error => { }).catch(error => {
console.log("getIfaceConfig promise error = " + JSON.stringify(error)); console.log("getIfaceConfig promise error = " + JSON.stringify(error));
}); });
``` ```
...@@ -253,11 +253,11 @@ Checks whether a network interface is active. This API uses an asynchronous call ...@@ -253,11 +253,11 @@ Checks whether a network interface is active. This API uses an asynchronous call
```js ```js
ethernet.isIfaceActive("eth0", (error, value) => { ethernet.isIfaceActive("eth0", (error, value) => {
if (error) { if (error) {
console.log("whether2Activate callback error = " + JSON.stringify(error)); console.log("whether2Activate callback error = " + JSON.stringify(error));
} else { } else {
console.log("whether2Activate callback = " + JSON.stringify(value)); console.log("whether2Activate callback = " + JSON.stringify(value));
} }
}); });
``` ```
...@@ -300,9 +300,9 @@ Checks whether a network interface is active. This API uses a promise to return ...@@ -300,9 +300,9 @@ Checks whether a network interface is active. This API uses a promise to return
```js ```js
ethernet.isIfaceActive("eth0").then((data) => { ethernet.isIfaceActive("eth0").then((data) => {
console.log("isIfaceActive promise = " + JSON.stringify(data)); console.log("isIfaceActive promise = " + JSON.stringify(data));
}).catch(error => { }).catch(error => {
console.log("isIfaceActive promise error = " + JSON.stringify(error)); console.log("isIfaceActive promise error = " + JSON.stringify(error));
}); });
``` ```
...@@ -336,14 +336,14 @@ Obtains the list of all active network interfaces. This API uses an asynchronous ...@@ -336,14 +336,14 @@ Obtains the list of all active network interfaces. This API uses an asynchronous
```js ```js
ethernet.getAllActiveIfaces((error, value) => { ethernet.getAllActiveIfaces((error, value) => {
if (error) { if (error) {
console.log("getAllActiveIfaces callback error = " + JSON.stringify(error)); console.log("getAllActiveIfaces callback error = " + JSON.stringify(error));
} else { } else {
console.log("getAllActiveIfaces callback value.length = " + JSON.stringify(value.length)); console.log("getAllActiveIfaces callback value.length = " + JSON.stringify(value.length));
for (let i = 0; i < value.length; i++) { for (let i = 0; i < value.length; i++) {
console.log("getAllActiveIfaces callback = " + JSON.stringify(value[i])); console.log("getAllActiveIfaces callback = " + JSON.stringify(value[i]));
}
} }
}
}); });
``` ```
...@@ -377,15 +377,83 @@ Obtains the list of all active network interfaces. This API uses a promise to re ...@@ -377,15 +377,83 @@ Obtains the list of all active network interfaces. This API uses a promise to re
```js ```js
ethernet.getAllActiveIfaces().then((data) => { ethernet.getAllActiveIfaces().then((data) => {
console.log("getAllActiveIfaces promise data.length = " + JSON.stringify(data.length)); console.log("getAllActiveIfaces promise data.length = " + JSON.stringify(data.length));
for (let i = 0; i < data.length; i++) { for (let i = 0; i < data.length; i++) {
console.log("getAllActiveIfaces promise = " + JSON.stringify(data[i])); console.log("getAllActiveIfaces promise = " + JSON.stringify(data[i]));
} }
}).catch(error => { }).catch(error => {
console.log("getAllActiveIfaces promise error = " + JSON.stringify(error)); console.log("getAllActiveIfaces promise error = " + JSON.stringify(error));
}); });
``` ```
## ethernet.on('interfaceStateChange')<sup>10+</sup>
on(type: 'interfaceStateChange', callback: Callback\<{ iface: string, active: boolean }\>): void
Registers an observer for NIC hot swap events. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Ethernet
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| type | string | Yes | Event type. The value is **interfaceStateChange**.|
| callback | AsyncCallback\<{ iface: string, active: boolean }\> | Yes | Callback used to return the result.<br>**iface**: NIC name.<br>**active**: whether the NIC is active. The value **true** indicates that the NIC is active, and the value **false** indicates the opposite.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Applicable only to system applications. |
| 401 | Parameter error. |
**Example**
```js
ethernet.on('interfaceStateChange', (data) => {
console.log('on interfaceSharingStateChange: ' + JSON.stringify(data));
});
```
## ethernet.off('interfaceStateChange')<sup>10+</sup>
off(type: 'interfaceStateChange', callback?: Callback\<{ iface: string, active: boolean }\>): void
Unregisters the observer for NIC hot swap events. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Ethernet
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| type | string | Yes | Event type. The value is **interfaceStateChange**.|
| callback | AsyncCallback\<{ iface: string, active: boolean }> | No | Callback used to return the result.<br>**iface**: NIC name.<br>**active**: whether the NIC is active. The value **true** indicates that the NIC is active, and the value **false** indicates the opposite.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Applicable only to system applications. |
| 401 | Parameter error. |
**Example**
```js
ethernet.off('interfaceStateChange');
```
## InterfaceConfiguration ## InterfaceConfiguration
Defines the network configuration for the Ethernet connection. Defines the network configuration for the Ethernet connection.
......
...@@ -43,10 +43,12 @@ Sets a background network policy. This API uses an asynchronous callback to retu ...@@ -43,10 +43,12 @@ Sets a background network policy. This API uses an asynchronous callback to retu
```js ```js
policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))), (error, data) => { policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))), (error, data) => {
this.callBack(error, data); this.callBack(error, data);
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}); }
)
;
``` ```
## policy.setBackgroundPolicy ## policy.setBackgroundPolicy
...@@ -84,9 +86,9 @@ Sets a background network policy. This API uses a promise to return the result. ...@@ -84,9 +86,9 @@ Sets a background network policy. This API uses a promise to return the result.
**Example** **Example**
```js ```js
policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) { policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -118,9 +120,9 @@ Obtains the background network policy. This API uses an asynchronous callback to ...@@ -118,9 +120,9 @@ Obtains the background network policy. This API uses an asynchronous callback to
```js ```js
policy.isBackgroundAllowed((error, data) => { policy.isBackgroundAllowed((error, data) => {
this.callBack(error, data); this.callBack(error, data);
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}); });
``` ```
...@@ -151,9 +153,9 @@ Obtains the background network policy. This API uses a promise to return the res ...@@ -151,9 +153,9 @@ Obtains the background network policy. This API uses a promise to return the res
**Example** **Example**
```js ```js
policy.isBackgroundAllowed().then(function(error, data) { policy.isBackgroundAllowed().then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -190,10 +192,10 @@ Sets an application-specific network policy. This API uses an asynchronous callb ...@@ -190,10 +192,10 @@ Sets an application-specific network policy. This API uses an asynchronous callb
```js ```js
let param = { let param = {
uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy) uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy)
} }
policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy), (error, data) => { policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy), (error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -234,11 +236,11 @@ Sets an application-specific network policy. This API uses a promise to return t ...@@ -234,11 +236,11 @@ Sets an application-specific network policy. This API uses a promise to return t
```js ```js
let param = { let param = {
uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy) uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy)
} }
policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy)).then(function(error, data) { policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy)).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -274,7 +276,7 @@ Obtains an application-specific network policy by **uid**. This API uses an asyn ...@@ -274,7 +276,7 @@ Obtains an application-specific network policy by **uid**. This API uses an asyn
```js ```js
policy.getPolicyByUid(Number.parseInt(this.firstParam), (error, data) => { policy.getPolicyByUid(Number.parseInt(this.firstParam), (error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -313,9 +315,9 @@ Obtains an application-specific network policy by **uid**. This API uses a promi ...@@ -313,9 +315,9 @@ Obtains an application-specific network policy by **uid**. This API uses a promi
**Example** **Example**
```js ```js
policy.getPolicyByUid(Number.parseInt(this.firstParam)).then(function(error, data) { policy.getPolicyByUid(Number.parseInt(this.firstParam)).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -351,7 +353,7 @@ Obtains the UID array of applications configured with a certain application-spec ...@@ -351,7 +353,7 @@ Obtains the UID array of applications configured with a certain application-spec
```js ```js
policy.getUidsByPolicy(Number.parseInt(this.currentNetUidPolicy), (error, data) => { policy.getUidsByPolicy(Number.parseInt(this.currentNetUidPolicy), (error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -390,9 +392,9 @@ Obtains the UID array of applications configured with a certain application-spec ...@@ -390,9 +392,9 @@ Obtains the UID array of applications configured with a certain application-spec
**Example** **Example**
```js ```js
policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function(error, data) { policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -425,7 +427,7 @@ Obtains the network quota policies. This API uses an asynchronous callback to re ...@@ -425,7 +427,7 @@ Obtains the network quota policies. This API uses an asynchronous callback to re
```js ```js
policy.getNetQuotaPolicies((error, data) => { policy.getNetQuotaPolicies((error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -456,9 +458,9 @@ Obtains the network quota policies. This API uses a promise to return the result ...@@ -456,9 +458,9 @@ Obtains the network quota policies. This API uses a promise to return the result
**Example** **Example**
```js ```js
policy.getNetQuotaPolicies().then(function(error, data) { policy.getNetQuotaPolicies().then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -493,12 +495,22 @@ Sets an array of network quota policies. This API uses an asynchronous callback ...@@ -493,12 +495,22 @@ Sets an array of network quota policies. This API uses an asynchronous callback
**Example** **Example**
```js ```js
let param = {netType:Number.parseInt(this.netType), iccid:this.iccid, ident:this.ident, periodDuration:this.periodDuration, warningBytes:Number.parseInt(this.warningBytes), let param = {
limitBytes:Number.parseInt(this.limitBytes), lastWarningRemind:this.lastWarningRemind, lastLimitRemind:this.lastLimitRemind, metered:Boolean(Number.parseInt(this.metered)), limitAction:this.limitAction}; netType: Number.parseInt(this.netType),
iccid: this.iccid,
ident: this.ident,
periodDuration: this.periodDuration,
warningBytes: Number.parseInt(this.warningBytes),
limitBytes: Number.parseInt(this.limitBytes),
lastWarningRemind: this.lastWarningRemind,
lastLimitRemind: this.lastLimitRemind,
metered: Boolean(Number.parseInt(this.metered)),
limitAction: this.limitAction
};
this.netQuotaPolicyList.push(param); this.netQuotaPolicyList.push(param);
policy.setNetQuotaPolicies(this.netQuotaPolicyList, (error, data) => { policy.setNetQuotaPolicies(this.netQuotaPolicyList, (error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -537,13 +549,23 @@ Sets an array of network quota policies. This API uses a promise to return the r ...@@ -537,13 +549,23 @@ Sets an array of network quota policies. This API uses a promise to return the r
**Example** **Example**
```js ```js
let param = {netType:Number.parseInt(this.netType), iccid:this.iccid, ident:this.ident, periodDuration:this.periodDuration, warningBytes:Number.parseInt(this.warningBytes), let param = {
limitBytes:Number.parseInt(this.limitBytes), lastWarningRemind:this.lastWarningRemind, lastLimitRemind:this.lastLimitRemind, metered:Boolean(Number.parseInt(this.metered)), limitAction:this.limitAction}; netType: Number.parseInt(this.netType),
iccid: this.iccid,
ident: this.ident,
periodDuration: this.periodDuration,
warningBytes: Number.parseInt(this.warningBytes),
limitBytes: Number.parseInt(this.limitBytes),
lastWarningRemind: this.lastWarningRemind,
lastLimitRemind: this.lastLimitRemind,
metered: Boolean(Number.parseInt(this.metered)),
limitAction: this.limitAction
};
this.netQuotaPolicyList.push(param); this.netQuotaPolicyList.push(param);
policy.setNetQuotaPolicies(this.netQuotaPolicyList).then(function(error, data) { policy.setNetQuotaPolicies(this.netQuotaPolicyList).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -579,7 +601,7 @@ Restores all the policies (cellular network, background network, firewall, and a ...@@ -579,7 +601,7 @@ Restores all the policies (cellular network, background network, firewall, and a
```js ```js
this.firstParam = iccid; this.firstParam = iccid;
policy.restoreAllPolicies(this.firstParam, (error, data) => { policy.restoreAllPolicies(this.firstParam, (error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -619,9 +641,9 @@ Restores all the policies (cellular network, background network, firewall, and a ...@@ -619,9 +641,9 @@ Restores all the policies (cellular network, background network, firewall, and a
```js ```js
this.firstParam = iccid; this.firstParam = iccid;
policy.restoreAllPolicies(this.firstParam).then(function(error, data){ policy.restoreAllPolicies(this.firstParam).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -659,10 +681,10 @@ Checks whether an application is allowed to access metered networks. This API us ...@@ -659,10 +681,10 @@ Checks whether an application is allowed to access metered networks. This API us
```js ```js
let param = { let param = {
uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean)) uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean))
} }
policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (error, data) => { policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -704,11 +726,11 @@ Checks whether an application is allowed to access metered networks. This API us ...@@ -704,11 +726,11 @@ Checks whether an application is allowed to access metered networks. This API us
```js ```js
let param = { let param = {
uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean)) uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean))
} }
policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) { policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -746,10 +768,10 @@ Checks whether an application is allowed to access the given network. This API u ...@@ -746,10 +768,10 @@ Checks whether an application is allowed to access the given network. This API u
```js ```js
let param = { let param = {
uid: Number.parseInt(this.firstParam), iface: this.secondParam uid: Number.parseInt(this.firstParam), iface: this.secondParam
} }
policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam, (error, data) => { policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam, (error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -790,11 +812,11 @@ Checks whether an application is allowed to access the given network. This API u ...@@ -790,11 +812,11 @@ Checks whether an application is allowed to access the given network. This API u
```js ```js
let param = { let param = {
uid: Number.parseInt(this.firstParam), iface: this.secondParam uid: Number.parseInt(this.firstParam), iface: this.secondParam
} }
policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam).then(function(error, data) { policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -831,10 +853,10 @@ Sets whether to add an application to the device idle allowlist. This API uses a ...@@ -831,10 +853,10 @@ Sets whether to add an application to the device idle allowlist. This API uses a
```js ```js
let param = { let param = {
uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean))
} }
policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (error, data) => { policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -875,11 +897,11 @@ Sets whether to add an application to the device idle allowlist. This API uses a ...@@ -875,11 +897,11 @@ Sets whether to add an application to the device idle allowlist. This API uses a
```js ```js
let param = { let param = {
uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean))
} }
policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) { policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -912,7 +934,7 @@ Obtains the UID array of applications that are on the device idle allowlist. Thi ...@@ -912,7 +934,7 @@ Obtains the UID array of applications that are on the device idle allowlist. Thi
```js ```js
policy.getDeviceIdleAllowList((error, data) => { policy.getDeviceIdleAllowList((error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -943,9 +965,9 @@ Obtains the UID array of applications that are on the device idle allowlist. Thi ...@@ -943,9 +965,9 @@ Obtains the UID array of applications that are on the device idle allowlist. Thi
**Example** **Example**
```js ```js
policy.getDeviceIdleAllowList().then(function(error, data) { policy.getDeviceIdleAllowList().then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -981,7 +1003,7 @@ Obtains the background network policies configured for the given application. Th ...@@ -981,7 +1003,7 @@ Obtains the background network policies configured for the given application. Th
```js ```js
this.firstParam = uid this.firstParam = uid
policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam), (error, data) => { policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam), (error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -1021,9 +1043,9 @@ Obtains the background network policies configured for the given application. Th ...@@ -1021,9 +1043,9 @@ Obtains the background network policies configured for the given application. Th
```js ```js
this.firstParam = uid this.firstParam = uid
policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam)).then(function(error, data) { policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam)).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -1059,7 +1081,7 @@ Restores all the policies (cellular network, background network, firewall, and a ...@@ -1059,7 +1081,7 @@ Restores all the policies (cellular network, background network, firewall, and a
```js ```js
this.firstParam = iccid this.firstParam = iccid
policy.resetPolicies(this.firstParam, (error, data) => { policy.resetPolicies(this.firstParam, (error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -1098,13 +1120,13 @@ Restores all the policies (cellular network, background network, firewall, and a ...@@ -1098,13 +1120,13 @@ Restores all the policies (cellular network, background network, firewall, and a
**Example** **Example**
```js ```js
policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function(error, data) { policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function (error, data) {
}) })
this.firstParam = iccid this.firstParam = iccid
policy.resetPolicies(this.firstParam).then(function(error, data) { policy.resetPolicies(this.firstParam).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -1142,10 +1164,10 @@ Updates a reminder policy. This API uses an asynchronous callback to return the ...@@ -1142,10 +1164,10 @@ Updates a reminder policy. This API uses an asynchronous callback to return the
```js ```js
let param = { let param = {
netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType
} }
policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType), (error, data) => { policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType), (error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -1187,11 +1209,11 @@ Updates a reminder policy. This API uses a promise to return the result. ...@@ -1187,11 +1209,11 @@ Updates a reminder policy. This API uses a promise to return the result.
```js ```js
let param = { let param = {
netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType
} }
policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType)).then(function(error, data) { policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType)).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -1228,10 +1250,10 @@ Sets whether to add an application to the power-saving allowlist. This API uses ...@@ -1228,10 +1250,10 @@ Sets whether to add an application to the power-saving allowlist. This API uses
```js ```js
let param = { let param = {
uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean))
} }
policy.setPowerSaveAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (error, data) => { policy.setPowerSaveAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -1272,11 +1294,11 @@ Sets whether to add an application to the power-saving allowlist. This API uses ...@@ -1272,11 +1294,11 @@ Sets whether to add an application to the power-saving allowlist. This API uses
```js ```js
let param = { let param = {
uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean))
} }
policy.setPowerSaveAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) { policy.setPowerSaveAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -1309,7 +1331,7 @@ Obtains the UID array of applications that are on the power-saving allowlist. Th ...@@ -1309,7 +1331,7 @@ Obtains the UID array of applications that are on the power-saving allowlist. Th
```js ```js
policy.getPowerSaveAllowList((error, data) => { policy.getPowerSaveAllowList((error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -1340,9 +1362,9 @@ Obtains the UID array of applications that are on the device idle allowlist. Thi ...@@ -1340,9 +1362,9 @@ Obtains the UID array of applications that are on the device idle allowlist. Thi
**Example** **Example**
```js ```js
policy.getPowerSaveAllowList().then(function(error, data) { policy.getPowerSaveAllowList().then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -1371,7 +1393,7 @@ Subscribes to policy changes. This API uses an asynchronous callback to return t ...@@ -1371,7 +1393,7 @@ Subscribes to policy changes. This API uses an asynchronous callback to return t
```js ```js
policy.on('netUidPolicyChange', (data) => { policy.on('netUidPolicyChange', (data) => {
this.log('on netUidPolicyChange: ' + JSON.stringify(data)); this.log('on netUidPolicyChange: ' + JSON.stringify(data));
}) })
``` ```
...@@ -1396,7 +1418,7 @@ Subscribes to rule changes. This API uses an asynchronous callback to return the ...@@ -1396,7 +1418,7 @@ Subscribes to rule changes. This API uses an asynchronous callback to return the
```js ```js
policy.on('netUidRuleChange', (data) => { policy.on('netUidRuleChange', (data) => {
this.log('on netUidRuleChange: ' + JSON.stringify(data)); this.log('on netUidRuleChange: ' + JSON.stringify(data));
}) })
``` ```
...@@ -1421,7 +1443,7 @@ Subscribes to metered **iface** changes. This API uses an asynchronous callback ...@@ -1421,7 +1443,7 @@ Subscribes to metered **iface** changes. This API uses an asynchronous callback
```js ```js
policy.on('netMeteredIfacesChange', (data) => { policy.on('netMeteredIfacesChange', (data) => {
this.log('on netMeteredIfacesChange: ' + JSON.stringify(data)); this.log('on netMeteredIfacesChange: ' + JSON.stringify(data));
}) })
``` ```
...@@ -1446,7 +1468,7 @@ Subscribes to network quota policy changes. This API uses an asynchronous callba ...@@ -1446,7 +1468,7 @@ Subscribes to network quota policy changes. This API uses an asynchronous callba
```js ```js
policy.on('netQuotaPolicyChange', (data) => { policy.on('netQuotaPolicyChange', (data) => {
this.log('on netQuotaPolicyChange: ' + JSON.stringify(data)); this.log('on netQuotaPolicyChange: ' + JSON.stringify(data));
}) })
``` ```
...@@ -1471,7 +1493,7 @@ Subscribes to background network policy changes. This API uses an asynchronous c ...@@ -1471,7 +1493,7 @@ Subscribes to background network policy changes. This API uses an asynchronous c
```js ```js
policy.on('netBackgroundPolicyChange', (data) => { policy.on('netBackgroundPolicyChange', (data) => {
this.log('on netBackgroundPolicyChange: ' + JSON.stringify(data)); this.log('on netBackgroundPolicyChange: ' + JSON.stringify(data));
}) })
``` ```
...@@ -1540,10 +1562,10 @@ Enumerates the reminder types. ...@@ -1540,10 +1562,10 @@ Enumerates the reminder types.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
| Name | Value| Description | | Name| Value| Description|
| ---------------------- | - | ------- | | ---------------------- | - | ------- |
| REMIND_TYPE_WARNING | 1 | Warning.| | REMIND_TYPE_WARNING | 1 | Warning.|
| REMIND_TYPE_LIMIT | 2 | Limit.| | REMIND_TYPE_LIMIT | 2 | Limit.|
## NetUidPolicy ## NetUidPolicy
......
...@@ -43,8 +43,8 @@ Checks whether network sharing is supported. This API uses an asynchronous callb ...@@ -43,8 +43,8 @@ Checks whether network sharing is supported. This API uses an asynchronous callb
```js ```js
sharing.isSharingSupported((error, data) => { sharing.isSharingSupported((error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -79,9 +79,9 @@ Checks whether network sharing is supported. This API uses a promise to return t ...@@ -79,9 +79,9 @@ Checks whether network sharing is supported. This API uses a promise to return t
```js ```js
sharing.isSharingSupported().then(data => { sharing.isSharingSupported().then(data => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}).catch(error => { }).catch(error => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
...@@ -115,8 +115,8 @@ Checks whether network sharing is in progress. This API uses an asynchronous cal ...@@ -115,8 +115,8 @@ Checks whether network sharing is in progress. This API uses an asynchronous cal
```js ```js
sharing.isSharing((error, data) => { sharing.isSharing((error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -150,9 +150,9 @@ Checks whether network sharing is in progress. This API uses a promise to return ...@@ -150,9 +150,9 @@ Checks whether network sharing is in progress. This API uses a promise to return
```js ```js
sharing.isSharing().then(data => { sharing.isSharing().then(data => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}).catch(error => { }).catch(error => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
...@@ -194,9 +194,10 @@ Starts network sharing of a specified type. This API uses an asynchronous callba ...@@ -194,9 +194,10 @@ Starts network sharing of a specified type. This API uses an asynchronous callba
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.startSharing(SHARING_WIFI, (error) => { sharing.startSharing(SHARING_WIFI, (error) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
...@@ -243,11 +244,12 @@ Starts network sharing of a specified type. This API uses a promise to return th ...@@ -243,11 +244,12 @@ Starts network sharing of a specified type. This API uses a promise to return th
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.startSharing(SHARING_WIFI).then(() => { sharing.startSharing(SHARING_WIFI).then(() => {
console.log("start wifi sharing successful"); console.log("start wifi sharing successful");
}).catch(error => { }).catch(error => {
console.log("start wifi sharing failed"); console.log("start wifi sharing failed");
}); });
``` ```
...@@ -287,9 +289,10 @@ Stops network sharing of a specified type. This API uses an asynchronous callbac ...@@ -287,9 +289,10 @@ Stops network sharing of a specified type. This API uses an asynchronous callbac
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.stopSharing(SHARING_WIFI, (error) => { sharing.stopSharing(SHARING_WIFI, (error) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
...@@ -334,11 +337,12 @@ Stops network sharing of a specified type. This API uses a promise to return the ...@@ -334,11 +337,12 @@ Stops network sharing of a specified type. This API uses a promise to return the
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.stopSharing(SHARING_WIFI).then(() => { sharing.stopSharing(SHARING_WIFI).then(() => {
console.log("stop wifi sharing successful"); console.log("stop wifi sharing successful");
}).catch(error => { }).catch(error => {
console.log("stop wifi sharing failed"); console.log("stop wifi sharing failed");
}); });
``` ```
...@@ -372,8 +376,8 @@ Obtains the volume of mobile data traffic received via network sharing. This API ...@@ -372,8 +376,8 @@ Obtains the volume of mobile data traffic received via network sharing. This API
```js ```js
sharing.getStatsRxBytes((error, data) => { sharing.getStatsRxBytes((error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -407,9 +411,9 @@ Obtains the volume of mobile data traffic received via network sharing. This API ...@@ -407,9 +411,9 @@ Obtains the volume of mobile data traffic received via network sharing. This API
```js ```js
sharing.getStatsRxBytes().then(data => { sharing.getStatsRxBytes().then(data => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}).catch(error => { }).catch(error => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
...@@ -443,8 +447,8 @@ Obtains the volume of mobile data traffic sent via network sharing. This API use ...@@ -443,8 +447,8 @@ Obtains the volume of mobile data traffic sent via network sharing. This API use
```js ```js
sharing.getStatsTxBytes((error, data) => { sharing.getStatsTxBytes((error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -478,9 +482,9 @@ Obtains the volume of mobile data traffic sent via network sharing. This API use ...@@ -478,9 +482,9 @@ Obtains the volume of mobile data traffic sent via network sharing. This API use
```js ```js
sharing.getStatsTxBytes().then(data => { sharing.getStatsTxBytes().then(data => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}).catch(error => { }).catch(error => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
...@@ -514,8 +518,8 @@ Obtains the volume of mobile data traffic sent and received via network sharing. ...@@ -514,8 +518,8 @@ Obtains the volume of mobile data traffic sent and received via network sharing.
```js ```js
sharing.getStatsTotalBytes((error, data) => { sharing.getStatsTotalBytes((error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -549,9 +553,9 @@ Obtains the volume of mobile data traffic sent and received via network sharing. ...@@ -549,9 +553,9 @@ Obtains the volume of mobile data traffic sent and received via network sharing.
```js ```js
sharing.getStatsTotalBytes().then(data => { sharing.getStatsTotalBytes().then(data => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}).catch(error => { }).catch(error => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
...@@ -588,10 +592,11 @@ Obtains the names of NICs in the specified network sharing state. This API uses ...@@ -588,10 +592,11 @@ Obtains the names of NICs in the specified network sharing state. This API uses
```js ```js
import SharingIfaceState from '@ohos.net.sharing' import SharingIfaceState from '@ohos.net.sharing'
let SHARING_BLUETOOTH=2;
let SHARING_BLUETOOTH = 2;
sharing.getSharingIfaces(SHARING_BLUETOOTH, (error, data) => { sharing.getSharingIfaces(SHARING_BLUETOOTH, (error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -633,11 +638,12 @@ Obtains the names of NICs in the specified network sharing state. This API uses ...@@ -633,11 +638,12 @@ Obtains the names of NICs in the specified network sharing state. This API uses
```js ```js
import SharingIfaceState from '@ohos.net.sharing' import SharingIfaceState from '@ohos.net.sharing'
let SHARING_BLUETOOTH=2;
let SHARING_BLUETOOTH = 2;
sharing.getSharingIfaces(SHARING_BLUETOOTH).then(data => { sharing.getSharingIfaces(SHARING_BLUETOOTH).then(data => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}).catch(error => { }).catch(error => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
...@@ -674,10 +680,11 @@ Obtains the network sharing state of the specified type. This API uses an asynch ...@@ -674,10 +680,11 @@ Obtains the network sharing state of the specified type. This API uses an asynch
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.getSharingState(SHARING_WIFI, (error, data) => { sharing.getSharingState(SHARING_WIFI, (error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -719,11 +726,12 @@ Obtains the network sharing state of the specified type. This API uses a promise ...@@ -719,11 +726,12 @@ Obtains the network sharing state of the specified type. This API uses a promise
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.getSharingState(SHARING_WIFI).then(data => { sharing.getSharingState(SHARING_WIFI).then(data => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}).catch(error => { }).catch(error => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
...@@ -760,10 +768,11 @@ Obtains regular expressions of NICs of a specified type. This API uses an asynch ...@@ -760,10 +768,11 @@ Obtains regular expressions of NICs of a specified type. This API uses an asynch
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.getSharableRegexes(SHARING_WIFI, (error, data) => { sharing.getSharableRegexes(SHARING_WIFI, (error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -805,11 +814,12 @@ Obtains regular expressions of NICs of a specified type. This API uses a promise ...@@ -805,11 +814,12 @@ Obtains regular expressions of NICs of a specified type. This API uses a promise
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.getSharableRegexes(SHARING_WIFI).then(data => { sharing.getSharableRegexes(SHARING_WIFI).then(data => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}).catch(error => { }).catch(error => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
...@@ -842,8 +852,8 @@ Subscribes to network sharing state changes. This API uses an asynchronous callb ...@@ -842,8 +852,8 @@ Subscribes to network sharing state changes. This API uses an asynchronous callb
**Example** **Example**
```js ```js
sharing.on('sharingStateChange', (data) => { sharing.on('sharingStateChange', (data) => {
console.log('on sharingStateChange: ' + JSON.stringify(data)); console.log('on sharingStateChange: ' + JSON.stringify(data));
}); });
``` ```
...@@ -877,13 +887,14 @@ Unsubscribes from network sharing state changes. This API uses an asynchronous c ...@@ -877,13 +887,14 @@ Unsubscribes from network sharing state changes. This API uses an asynchronous c
```js ```js
sharing.off('sharingStateChange', (data) => { sharing.off('sharingStateChange', (data) => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
## sharing.on('interfaceSharingStateChange') ## sharing.on('interfaceSharingStateChange')
on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIfaceType, iface: string, state:
SharingIfaceState }>): void
Subscribes to network sharing state changes of a specified NIC. This API uses an asynchronous callback to return the result. Subscribes to network sharing state changes of a specified NIC. This API uses an asynchronous callback to return the result.
...@@ -910,14 +921,15 @@ Subscribes to network sharing state changes of a specified NIC. This API uses an ...@@ -910,14 +921,15 @@ Subscribes to network sharing state changes of a specified NIC. This API uses an
**Example** **Example**
```js ```js
sharing.on('interfaceSharingStateChange', (data) => { sharing.on('interfaceSharingStateChange', (data) => {
console.log('on interfaceSharingStateChange: ' + JSON.stringify(data)); console.log('on interfaceSharingStateChange:' + JSON.stringify(data));
}); });
``` ```
## sharing.off('interfaceSharingStateChange') ## sharing.off('interfaceSharingStateChange')
off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfaceType, iface: string, state:
SharingIfaceState }>): void
Unsubscribes from network sharing status changes of a specified NIC. This API uses an asynchronous callback to return the result. Unsubscribes from network sharing status changes of a specified NIC. This API uses an asynchronous callback to return the result.
...@@ -945,7 +957,7 @@ Unsubscribes from network sharing status changes of a specified NIC. This API us ...@@ -945,7 +957,7 @@ Unsubscribes from network sharing status changes of a specified NIC. This API us
```js ```js
sharing.off('interfaceSharingStateChange', (data) => { sharing.off('interfaceSharingStateChange', (data) => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -978,8 +990,8 @@ Subscribes to upstream network changes. This API uses an asynchronous callback t ...@@ -978,8 +990,8 @@ Subscribes to upstream network changes. This API uses an asynchronous callback t
**Example** **Example**
```js ```js
sharing.on('sharingUpstreamChange', (data) => { sharing.on('sharingUpstreamChange', (data) => {
console.log('on sharingUpstreamChange: ' + JSON.stringify(data)); console.log('on sharingUpstreamChange:' + JSON.stringify(data));
}); });
``` ```
...@@ -1013,7 +1025,7 @@ Unsubscribes from upstream network changes. This API uses an asynchronous callba ...@@ -1013,7 +1025,7 @@ Unsubscribes from upstream network changes. This API uses an asynchronous callba
```js ```js
sharing.off('sharingUpstreamChange', (data) => { sharing.off('sharingUpstreamChange', (data) => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
......
...@@ -5,11 +5,12 @@ ...@@ -5,11 +5,12 @@
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the [createWebSocket](#websocketcreatewebsocket) API to create a [WebSocket](#websocket) object and then use the [connect](#connect) API to connect to the server. If the connection is successful, the client will receive a callback of the [open](#onopen) event. Then, the client can communicate with the server using the [send](#send) API. When the server sends a message to the client, the client will receive a callback of the [message](#onmessage) event. If the client no longer needs this connection, it can call the [close](#close) API to disconnect from the server. Then, the client will receive a callback of the [close](#onclose) event. You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the [createWebSocket](#websocketcreatewebsocket) API to create a [WebSocket](#websocket) object and then use the [connect](#connect) API to connect to the server.
If the connection is successful, the client will receive a callback of the [open](#onopen) event. Then, the client can communicate with the server using the [send](#send) API.
When the server sends a message to the client, the client will receive a callback of the [message](#onmessage) event. If the client no longer needs this connection, it can call the [close](#close) API to disconnect from the server. Then, the client will receive a callback of the [close](#onclose) event.
If an error occurs in any of the preceding processes, the client will receive a callback of the [error](#onerror) event. If an error occurs in any of the preceding processes, the client will receive a callback of the [error](#onerror) event.
## Modules to Import ## Modules to Import
```js ```js
...@@ -21,44 +22,48 @@ import webSocket from '@ohos.net.webSocket'; ...@@ -21,44 +22,48 @@ import webSocket from '@ohos.net.webSocket';
```js ```js
import webSocket from '@ohos.net.webSocket'; import webSocket from '@ohos.net.webSocket';
var defaultIpAddress = "ws://"; let defaultIpAddress = "ws://";
let ws = webSocket.createWebSocket(); let ws = webSocket.createWebSocket();
ws.on('open', (err, value) => { ws.on('open', (err, value) => {
console.log("on open, status:" + value['status'] + ", message:" + value['message']); if (err != undefined) {
// When receiving the on('open') event, the client can use the send() API to communicate with the server. console.log(JSON.stringify(err))
ws.send("Hello, server!", (err, value) => { return
if (!err) { }
console.log("send success"); console.log("on open, status:" + value['status'] + ", message:" + value['message']);
} else { // When receiving the on('open') event, the client can use the send() API to communicate with the server.
console.log("send fail, err:" + JSON.stringify(err)); ws.send("Hello, server!", (err, value) => {
} if (!err) {
}); console.log("send success");
} else {
console.log("send fail, err:" + JSON.stringify(err));
}
});
}); });
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.
if (value === 'bye') { if (value === 'bye') {
ws.close((err, value) => { ws.close((err, value) => {
if (!err) { if (!err) {
console.log("close success"); console.log("close success");
} else { } else {
console.log("close fail, err is " + JSON.stringify(err)); console.log("close fail, err is " + JSON.stringify(err));
} }
}); });
} }
}); });
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);
}); });
ws.on('error', (err) => { ws.on('error', (err) => {
console.log("on error, error:" + JSON.stringify(err)); console.log("on error, error:" + JSON.stringify(err));
}); });
ws.connect(defaultIpAddress, (err, value) => { ws.connect(defaultIpAddress, (err, value) => {
if (!err) { if (!err) {
console.log("connect success"); console.log("connect success");
} else { } else {
console.log("connect fail, err:" + JSON.stringify(err)); console.log("connect fail, err:" + JSON.stringify(err));
} }
}); });
``` ```
...@@ -82,7 +87,6 @@ Creates a WebSocket connection. You can use this API to create or close a WebSoc ...@@ -82,7 +87,6 @@ Creates a WebSocket connection. You can use this API to create or close a WebSoc
let ws = webSocket.createWebSocket(); let ws = webSocket.createWebSocket();
``` ```
## WebSocket ## WebSocket
Defines a **WebSocket** object. Before invoking WebSocket APIs, you need to call [webSocket.createWebSocket](#websocketcreatewebsocket) to create a **WebSocket** object. Defines a **WebSocket** object. Before invoking WebSocket APIs, you need to call [webSocket.createWebSocket](#websocketcreatewebsocket) to create a **WebSocket** object.
...@@ -93,6 +97,9 @@ connect(url: string, callback: AsyncCallback\<boolean\>): void ...@@ -93,6 +97,9 @@ connect(url: string, callback: AsyncCallback\<boolean\>): void
Initiates a WebSocket request to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result. Initiates a WebSocket request to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result.
> **NOTE**
> You can listen to **error** events to obtain the operation result. If an error occurs, the error code 200 will be returned.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -117,21 +124,23 @@ Initiates a WebSocket request to establish a WebSocket connection to a given URL ...@@ -117,21 +124,23 @@ Initiates a WebSocket request to establish a WebSocket connection to a given URL
let ws = webSocket.createWebSocket(); let ws = webSocket.createWebSocket();
let url = "ws://" let url = "ws://"
ws.connect(url, (err, value) => { ws.connect(url, (err, value) => {
if (!err) { if (!err) {
console.log("connect success"); console.log("connect success");
} else { } else {
console.log("connect fail, err:" + JSON.stringify(err)) console.log("connect fail, err:" + JSON.stringify(err))
} }
}); });
``` ```
### connect ### connect
connect(url: string, options: WebSocketRequestOptions, callback: AsyncCallback\<boolean\>): void connect(url: string, options: WebSocketRequestOptions, callback: AsyncCallback\<boolean\>): void
Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result. Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result.
> **NOTE**
> You can listen to **error** events to obtain the operation result. If an error occurs, the error code 200 will be returned.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -157,26 +166,28 @@ Initiates a WebSocket request carrying specified options to establish a WebSocke ...@@ -157,26 +166,28 @@ Initiates a WebSocket request carrying specified options to establish a WebSocke
let ws = webSocket.createWebSocket(); let ws = webSocket.createWebSocket();
let url = "ws://" let url = "ws://"
ws.connect(url, { ws.connect(url, {
header: { header: {
"key": "value", "key": "value",
"key2": "value2" "key2": "value2"
} }
}, (err, value) => { }, (err, value) => {
if (!err) { if (!err) {
console.log("connect success"); console.log("connect success");
} else { } else {
console.log("connect fail, err:" + JSON.stringify(err)) console.log("connect fail, err:" + JSON.stringify(err))
} }
}); });
``` ```
### connect ### connect
connect(url: string, options?: WebSocketRequestOptions): Promise\<boolean\> connect(url: string, options?: WebSocketRequestOptions): Promise\<boolean\>
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.
> **NOTE**
> You can listen to **error** events to obtain the operation result. If an error occurs, the error code 200 will be returned.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -208,13 +219,12 @@ let ws = webSocket.createWebSocket(); ...@@ -208,13 +219,12 @@ let ws = webSocket.createWebSocket();
let url = "ws://" let url = "ws://"
let promise = ws.connect(url); let promise = ws.connect(url);
promise.then((value) => { promise.then((value) => {
console.log("connect success") console.log("connect success")
}).catch((err) => { }).catch((err) => {
console.log("connect fail, error:" + JSON.stringify(err)) console.log("connect fail, error:" + JSON.stringify(err))
}); });
``` ```
### send ### send
send(data: string | ArrayBuffer, callback: AsyncCallback\<boolean\>): void send(data: string | ArrayBuffer, callback: AsyncCallback\<boolean\>): void
...@@ -245,17 +255,16 @@ Sends data through a WebSocket connection. This API uses an asynchronous callbac ...@@ -245,17 +255,16 @@ Sends data through a WebSocket connection. This API uses an asynchronous callbac
let ws = webSocket.createWebSocket(); let ws = webSocket.createWebSocket();
let url = "ws://" let url = "ws://"
ws.connect(url, (err, value) => { ws.connect(url, (err, value) => {
ws.send("Hello, server!", (err, value) => { ws.send("Hello, server!", (err, value) => {
if (!err) { if (!err) {
console.log("send success"); console.log("send success");
} else { } else {
console.log("send fail, err:" + JSON.stringify(err)) console.log("send fail, err:" + JSON.stringify(err))
} }
}); });
}); });
``` ```
### send ### send
send(data: string | ArrayBuffer): Promise\<boolean\> send(data: string | ArrayBuffer): Promise\<boolean\>
...@@ -291,16 +300,15 @@ Sends data through a WebSocket connection. This API uses a promise to return the ...@@ -291,16 +300,15 @@ Sends data through a WebSocket connection. This API uses a promise to return the
let ws = webSocket.createWebSocket(); let ws = webSocket.createWebSocket();
let url = "ws://" let url = "ws://"
ws.connect(url, (err, value) => { ws.connect(url, (err, value) => {
let promise = ws.send("Hello, server!"); let promise = ws.send("Hello, server!");
promise.then((value) => { promise.then((value) => {
console.log("send success") console.log("send success")
}).catch((err) => { }).catch((err) => {
console.log("send fail, error:" + JSON.stringify(err)) console.log("send fail, error:" + JSON.stringify(err))
}); });
}); });
``` ```
### close ### close
close(callback: AsyncCallback\<boolean\>): void close(callback: AsyncCallback\<boolean\>): void
...@@ -328,17 +336,15 @@ Closes a WebSocket connection. This API uses an asynchronous callback to return ...@@ -328,17 +336,15 @@ Closes a WebSocket connection. This API uses an asynchronous callback to return
```js ```js
let ws = webSocket.createWebSocket(); let ws = webSocket.createWebSocket();
let url = "ws://"
ws.close((err, value) => { ws.close((err, value) => {
if (!err) { if (!err) {
console.log("close success") console.log("close success")
} else { } else {
console.log("close fail, err is " + JSON.stringify(err)) console.log("close fail, err is " + JSON.stringify(err))
} }
}); });
``` ```
### close ### close
close(options: WebSocketCloseOptions, callback: AsyncCallback\<boolean\>): void close(options: WebSocketCloseOptions, callback: AsyncCallback\<boolean\>): void
...@@ -367,20 +373,18 @@ Closes a WebSocket connection carrying specified options such as **code** and ** ...@@ -367,20 +373,18 @@ Closes a WebSocket connection carrying specified options such as **code** and **
```js ```js
let ws = webSocket.createWebSocket(); let ws = webSocket.createWebSocket();
let url = "ws://"
ws.close({ ws.close({
code: 1000, code: 1000,
reason: "your reason" reason: "your reason"
}, (err, value) => { }, (err, value) => {
if (!err) { if (!err) {
console.log("close success") console.log("close success")
} else { } else {
console.log("close fail, err is " + JSON.stringify(err)) console.log("close fail, err is " + JSON.stringify(err))
} }
}); });
``` ```
### close ### close
close(options?: WebSocketCloseOptions): Promise\<boolean\> close(options?: WebSocketCloseOptions): Promise\<boolean\>
...@@ -414,19 +418,17 @@ Closes a WebSocket connection carrying specified options such as **code** and ** ...@@ -414,19 +418,17 @@ Closes a WebSocket connection carrying specified options such as **code** and **
```js ```js
let ws = webSocket.createWebSocket(); let ws = webSocket.createWebSocket();
let url = "ws://"
let promise = ws.close({ let promise = ws.close({
code: 1000, code: 1000,
reason: "your reason" reason: "your reason"
}); });
promise.then((value) => { promise.then((value) => {
console.log("close success") console.log("close success")
}).catch((err) => { }).catch((err) => {
console.log("close fail, err is " + JSON.stringify(err)) console.log("close fail, err is " + JSON.stringify(err))
}); });
``` ```
### on('open') ### on('open')
on(type: 'open', callback: AsyncCallback\<Object\>): void on(type: 'open', callback: AsyncCallback\<Object\>): void
...@@ -442,25 +444,23 @@ Enables listening for the **open** events of a WebSocket connection. This API us ...@@ -442,25 +444,23 @@ Enables listening for the **open** events of a WebSocket connection. This API us
| type | string | Yes | Event type. <br />**open**: event indicating that a WebSocket connection has been opened.| | type | string | Yes | Event type. <br />**open**: event indicating that a WebSocket connection has been opened.|
| callback | AsyncCallback\<Object\> | Yes | Callback used to return the result. | | callback | AsyncCallback\<Object\> | Yes | Callback used to return the result. |
**Example** **Example**
```js ```js
let ws = webSocket.createWebSocket(); let ws = webSocket.createWebSocket();
ws.on('open', (err, value) => { ws.on('open', (err, value) => {
console.log("on open, status:" + value['status'] + ", message:" + value['message']); console.log("on open, status:" + value['status'] + ", message:" + value['message']);
}); });
``` ```
### off('open') ### off('open')
off(type: 'open', callback?: AsyncCallback\<Object\>): void off(type: 'open', callback?: AsyncCallback\<Object\>): void
Disables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result. Disables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE** > **NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. > You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -476,22 +476,21 @@ Disables listening for the **open** events of a WebSocket connection. This API u ...@@ -476,22 +476,21 @@ Disables listening for the **open** events of a WebSocket connection. This API u
```js ```js
let ws = webSocket.createWebSocket(); let ws = webSocket.createWebSocket();
let callback1 = (err, value) => { let callback1 = (err, value) => {
console.log("on open, status:" + value['status'] + ", message:" + value['message']); console.log("on open, status:" + value['status'] + ", message:" + value['message']);
} }
ws.on('open', callback1); ws.on('open', callback1);
// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. // You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
ws.off('open', callback1); ws.off('open', callback1);
``` ```
### on('message') ### on('message')
on(type: 'message', callback: AsyncCallback\<string | ArrayBuffer\>): void on(type: 'message', callback: AsyncCallback\<string | ArrayBuffer\>): void
Enables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented. Enables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented.
>**NOTE** > **NOTE**
>The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8). > The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8).
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -507,20 +506,19 @@ Enables listening for the **message** events of a WebSocket connection. This API ...@@ -507,20 +506,19 @@ Enables listening for the **message** events of a WebSocket connection. This API
```js ```js
let ws = webSocket.createWebSocket(); let ws = webSocket.createWebSocket();
ws.on('message', (err, value) => { ws.on('message', (err, value) => {
console.log("on message, message:" + value); console.log("on message, message:" + value);
}); });
``` ```
### off('message') ### off('message')
off(type: 'message', callback?: AsyncCallback\<string | ArrayBuffer\>): void off(type: 'message', callback?: AsyncCallback\<string | ArrayBuffer\>): void
Disables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented. Disables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented.
>**NOTE** > **NOTE**
>The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8). > The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8).
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. > You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -538,7 +536,6 @@ let ws = webSocket.createWebSocket(); ...@@ -538,7 +536,6 @@ let ws = webSocket.createWebSocket();
ws.off('message'); ws.off('message');
``` ```
### on('close') ### on('close')
on(type: 'close', callback: AsyncCallback\<{ code: number, reason: string }\>): void on(type: 'close', callback: AsyncCallback\<{ code: number, reason: string }\>): void
...@@ -559,19 +556,18 @@ Enables listening for the **close** events of a WebSocket connection. This API u ...@@ -559,19 +556,18 @@ Enables listening for the **close** events of a WebSocket connection. This API u
```js ```js
let ws = webSocket.createWebSocket(); let ws = 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);
}); });
``` ```
### off('close') ### off('close')
off(type: 'close', callback?: AsyncCallback\<{ code: number, reason: string }\>): void off(type: 'close', callback?: AsyncCallback\<{ code: number, reason: string }\>): void
Disables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result. Disables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE** > **NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. > You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -589,7 +585,6 @@ let ws = webSocket.createWebSocket(); ...@@ -589,7 +585,6 @@ let ws = webSocket.createWebSocket();
ws.off('close'); ws.off('close');
``` ```
### on('error') ### on('error')
on(type: 'error', callback: ErrorCallback): void on(type: 'error', callback: ErrorCallback): void
...@@ -603,26 +598,25 @@ Enables listening for the **error** events of a WebSocket connection. This API u ...@@ -603,26 +598,25 @@ Enables listening for the **error** events of a WebSocket connection. This API u
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------- | | -------- | ------------- | ---- | ------------------------------- |
| type | string | Yes | Event type.<br />**error**: event indicating the WebSocket connection has encountered an error.| | type | string | Yes | Event type.<br />**error**: event indicating the WebSocket connection has encountered an error.|
| callback | ErrorCallback | Yes | Callback used to return the result. | | callback | ErrorCallback | Yes | Callback used to return the result.<br>Common error code: 200|
**Example** **Example**
```js ```js
let ws = webSocket.createWebSocket(); let ws = webSocket.createWebSocket();
ws.on('error', (err) => { ws.on('error', (err) => {
console.log("on error, error:" + JSON.stringify(err)) console.log("on error, error:" + JSON.stringify(err))
}); });
``` ```
### off('error') ### off('error')
off(type: 'error', callback?: ErrorCallback): void off(type: 'error', callback?: ErrorCallback): void
Disables listening for the **error** events of a WebSocket connection. This API uses an asynchronous callback to return the result. Disables listening for the **error** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE** > **NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. > You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -640,7 +634,6 @@ let ws = webSocket.createWebSocket(); ...@@ -640,7 +634,6 @@ let ws = webSocket.createWebSocket();
ws.off('error'); ws.off('error');
``` ```
## WebSocketRequestOptions ## WebSocketRequestOptions
Defines the optional parameters carried in the request for establishing a WebSocket connection. Defines the optional parameters carried in the request for establishing a WebSocket connection.
...@@ -651,7 +644,6 @@ Defines the optional parameters carried in the request for establishing a WebSoc ...@@ -651,7 +644,6 @@ Defines the optional parameters carried in the request for establishing a WebSoc
| ------ | ------ | ---- | ------------------------------------------------------------ | | ------ | ------ | ---- | ------------------------------------------------------------ |
| header | Object | No | Header carrying optional parameters in the request for establishing a WebSocket connection. You can customize the parameter or leave it unspecified.| | header | Object | No | Header carrying optional parameters in the request for establishing a WebSocket connection. You can customize the parameter or leave it unspecified.|
## WebSocketCloseOptions ## WebSocketCloseOptions
Defines the optional parameters carried in the request for closing a WebSocket connection. Defines the optional parameters carried in the request for closing a WebSocket connection.
......
...@@ -119,4 +119,6 @@ ...@@ -119,4 +119,6 @@
- [Thermal Level Customization](subsys-thermal_level.md) - [Thermal Level Customization](subsys-thermal_level.md)
- [Thermal Log Customization](subsys-thermal_log.md) - [Thermal Log Customization](subsys-thermal_log.md)
- [Thermal Policy Customization](subsys-thermal_policy.md) - [Thermal Policy Customization](subsys-thermal_policy.md)
- [Thermal Scene Customization](subsys-thermal_scene.md) - [Thermal Scene Customization](subsys-thermal_scene.md)
\ No newline at end of file - Power Management
- [Power Mode Customization](subsys-power-mode-customization.md)
\ No newline at end of file
...@@ -457,8 +457,8 @@ ...@@ -457,8 +457,8 @@
- [FaultLogger Development](subsystems/subsys-dfx-faultlogger.md) - [FaultLogger Development](subsystems/subsys-dfx-faultlogger.md)
- [Hiview Development](subsystems/subsys-dfx-hiview.md) - [Hiview Development](subsystems/subsys-dfx-hiview.md)
- Power - Power
- Power Consumption Statistics - Display Management
- [Power Consumption Statistics Customization](subsystems/subsys-power-stats-power-average-customization.md) - [System Brightness Customization](subsystems/subsys-power-brightness-customization.md)
- Battery Management - Battery Management
- [Battery Level and LED Color Mapping Customization](subsystems/subsys-power-level-LED-color.md) - [Battery Level and LED Color Mapping Customization](subsystems/subsys-power-level-LED-color.md)
- [Battery Temperature Protection Customization](subsystems/subsys-power-temperature-protection.md) - [Battery Temperature Protection Customization](subsystems/subsys-power-temperature-protection.md)
...@@ -466,6 +466,8 @@ ...@@ -466,6 +466,8 @@
- [Charging Current and Voltage Limit Customization](subsystems/subsys-power-charge-current-voltage-limit.md) - [Charging Current and Voltage Limit Customization](subsystems/subsys-power-charge-current-voltage-limit.md)
- [Charging Type Customization](subsystems/subsys-power-charge-type-customization.md) - [Charging Type Customization](subsystems/subsys-power-charge-type-customization.md)
- [Power-off Charging Animation Customization](subsystems/subsys-power-poweroff-charge-animation.md) - [Power-off Charging Animation Customization](subsystems/subsys-power-poweroff-charge-animation.md)
- Power Consumption Statistics
- [Power Consumption Statistics Customization](subsystems/subsys-power-stats-power-average-customization.md)
- Thermal Management - Thermal Management
- [Charging Idle State Customization](subsystems/subsys-thermal_charging_idle_state.md) - [Charging Idle State Customization](subsystems/subsys-thermal_charging_idle_state.md)
- [Thermal Control Customization](subsystems/subsys-thermal_control.md) - [Thermal Control Customization](subsystems/subsys-thermal_control.md)
...@@ -473,7 +475,9 @@ ...@@ -473,7 +475,9 @@
- [Thermal Level Customization](subsystems/subsys-thermal_level.md) - [Thermal Level Customization](subsystems/subsys-thermal_level.md)
- [Thermal Log Customization](subsystems/subsys-thermal_log.md) - [Thermal Log Customization](subsystems/subsys-thermal_log.md)
- [Thermal Policy Customization](subsystems/subsys-thermal_policy.md) - [Thermal Policy Customization](subsystems/subsys-thermal_policy.md)
- [Thermal Scene Customization](subsystems/subsys-thermal_scene.md) - [Thermal Scene Customization](subsystems/subsys-thermal_scene.md)
- Power Management
- [Power Mode Customization](subsystems/subsys-power-mode-customization.md)
- Featured Topics - Featured Topics
- HPM Part - HPM Part
- [HPM Part Overview](hpm-part/hpm-part-about.md) - [HPM Part Overview](hpm-part/hpm-part-about.md)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册