提交 55be9b6b 编写于 作者: S shawn_he

update docs

Signed-off-by: Nshawn_he <shawn.he@huawei.com>
上级 b5f13e6c
...@@ -23,7 +23,7 @@ The following table provides only a simple description of the related APIs. For ...@@ -23,7 +23,7 @@ The following table provides only a simple description of the related APIs. For
| off(type: 'headersReceive') | Unregisters the observer for HTTP Response Header events.| | off(type: 'headersReceive') | Unregisters the observer for HTTP Response Header events.|
| once\('headersReceive'\)<sup>8+</sup> | Registers a one-time observer for HTTP Response Header events.| | once\('headersReceive'\)<sup>8+</sup> | Registers a one-time observer for HTTP Response Header events.|
## How to Develop ## How to Develop request APIs
1. Import the **http** namespace from **@ohos.net.http.d.ts**. 1. Import the **http** namespace from **@ohos.net.http.d.ts**.
2. Call **createHttp()** to create an **HttpRequest** object. 2. Call **createHttp()** to create an **HttpRequest** object.
...@@ -46,7 +46,6 @@ httpRequest.on('headersReceive', (header) => { ...@@ -46,7 +46,6 @@ httpRequest.on('headersReceive', (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.
...@@ -81,3 +80,4 @@ httpRequest.request( ...@@ -81,3 +80,4 @@ httpRequest.request(
} }
); );
``` ```
# 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. - Wi-Fi sharing: Shares the network through a Wi-Fi hotspot.
- Bluetooth sharing: Shares the network through Bluetooth. - Bluetooth sharing: Shares the network through Bluetooth.
- USB tethering: Shares the network using a USB flash drive. - USB tethering: Shares the network using a USB flash drive.
## **Constraints** ## **Constraints**
- Programming language: C++ and JS - Programming language: C++ and JS
- System: Linux kernel - 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. - 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
- Enabling Network Sharing
- Disabling network sharing - Disabling network sharing
- Obtaining the data traffic of the shared network - 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));
}); });
``` ```
...@@ -13,10 +13,10 @@ The Socket Connection module allows an application to transmit data over a Socke ...@@ -13,10 +13,10 @@ The Socket Connection module allows an application to transmit data over a Socke
## When to Use ## When to Use
Applications transmit data over TCP, UDP, or TLS Socket connections. The main application scenarios are as follows: Applications transmit data over TCP, UDP, or TLSSocket connections. The main application scenarios are as follows:
- Implementing data transmission over TCP/UDP Socket connections - Implementing data transmission over TCP/UDPSocket connections
- Implementing encrypted data transmission over TLS Socket connections - Implementing encrypted data transmission over TLSSocket connections
## Available APIs ## Available APIs
...@@ -40,12 +40,12 @@ Socket connection functions are mainly implemented by the **socket** module. The ...@@ -40,12 +40,12 @@ Socket connection functions are mainly implemented by the **socket** module. The
| off(type:&nbsp;'close') | Unsubscribes from **close** events of the Socket connection.| | off(type:&nbsp;'close') | Unsubscribes from **close** events of the Socket connection.|
| on(type:&nbsp;'error') | Subscribes to **error** events of the Socket connection.| | on(type:&nbsp;'error') | Subscribes to **error** events of the Socket connection.|
| off(type:&nbsp;'error') | Unsubscribes from **error** events of the Socket connection.| | off(type:&nbsp;'error') | Unsubscribes from **error** events of the Socket connection.|
| on(type:&nbsp;'listening') | Subscribes to **listening** events of the UDP Socket connection. | | on(type:&nbsp;'listening') | Subscribes to **listening** events of the UDPSocket connection. |
| off(type:&nbsp;'listening') | Unsubscribes from **listening** events of the UDP Socket connection. | | off(type:&nbsp;'listening') | Unsubscribes from **listening** events of the UDPSocket connection. |
| on(type:&nbsp;'connect') | Subscribes to **connect** events of the TCP Socket connection. | | on(type:&nbsp;'connect') | Subscribes to **connect** events of the TCPSocket connection. |
| off(type:&nbsp;'connect') | Unsubscribes from **connect** events of the TCP Socket connection.| | off(type:&nbsp;'connect') | Unsubscribes from **connect** events of the TCPSocket connection.|
TLS Socket connection functions are mainly provided by the **tls_socket** module. The following table describes the related APIs. TLSSocket connection functions are mainly provided by the **tls_socket** module. The following table describes the related APIs.
| API| Description| | API| Description|
| -------- | -------- | | -------- | -------- |
...@@ -56,28 +56,28 @@ TLS Socket connection functions are mainly provided by the **tls_socket** module ...@@ -56,28 +56,28 @@ TLS Socket connection functions are mainly provided by the **tls_socket** module
| getCertificate() | Obtains an object representing the local certificate.| | getCertificate() | Obtains an object representing the local certificate.|
| getCipherSuite() | Obtains a list containing information about the negotiated cipher suite.| | getCipherSuite() | Obtains a list containing information about the negotiated cipher suite.|
| getProtocol() | Obtains a string containing the SSL/TLS protocol version negotiated for the current connection.| | getProtocol() | Obtains a string containing the SSL/TLS protocol version negotiated for the current connection.|
| getRemoteAddress() | Obtains the peer address of the TLS Socket connection.| | getRemoteAddress() | Obtains the peer address of the TLSSocket connection.|
| getRemoteCertificate() | Obtains an object representing a peer certificate.| | getRemoteCertificate() | Obtains an object representing a peer certificate.|
| getSignatureAlgorithms() | Obtains a list containing signature algorithms shared between the server and client, in descending order of priority.| | getSignatureAlgorithms() | Obtains a list containing signature algorithms shared between the server and client, in descending order of priority.|
| getState() | Obtains the TLS Socket connection status.| | getState() | Obtains the TLSSocket connection status.|
| off(type:&nbsp;'close') | Unsubscribes from **close** events of the TLS Socket connection.| | off(type:&nbsp;'close') | Unsubscribes from **close** events of the TLSSocket connection.|
| off(type:&nbsp;'error') | Unsubscribes from **error** events of the TLS Socket connection.| | off(type:&nbsp;'error') | Unsubscribes from **error** events of the TLSSocket connection.|
| off(type:&nbsp;'message') | Unsubscribes from **message** events of the TLS Socket connection.| | off(type:&nbsp;'message') | Unsubscribes from **message** events of the TLSSocket connection.|
| on(type:&nbsp;'close') | Subscribes to **close** events of the TLS Socket connection.| | on(type:&nbsp;'close') | Subscribes to **close** events of the TLSSocket connection.|
| on(type:&nbsp;'error') | Subscribes to **error** events of the TLS Socket connection.| | on(type:&nbsp;'error') | Subscribes to **error** events of the TLSSocket connection.|
| on(type:&nbsp;'message') | Subscribes to **message** events of the TLS Socket connection.| | on(type:&nbsp;'message') | Subscribes to **message** events of the TLSSocket connection.|
| send() | Sends data.| | send() | Sends data.|
| setExtraOptions() | Sets other properties of the TLS Socket connection.| | setExtraOptions() | Sets other properties of the TLSSocket connection.|
## Transmitting Data over TCP/UDP Socket Connections ## Transmitting Data over TCP/UDPSocket Connections
The implementation is similar for UDP Socket and TCP Socket connections. The following uses data transmission over a TCP Socket connection as an example. The implementation is similar for UDPSocket and TCPSocket connections. The following uses data transmission over a TCPSocket connection as an example.
1. Import the required **socket** module. 1. Import the required **socket** module.
2. Create a **TCPSocket** object. 2. Create a **TCPSocket** object.
3. (Optional) Subscribe to TCP Socket connection events. 3. (Optional) Subscribe to TCPSocket connection events.
4. Bind the IP address and port number. The port number can be specified or randomly allocated by the system. 4. Bind the IP address and port number. The port number can be specified or randomly allocated by the system.
...@@ -85,7 +85,7 @@ The implementation is similar for UDP Socket and TCP Socket connections. The fol ...@@ -85,7 +85,7 @@ The implementation is similar for UDP Socket and TCP Socket connections. The fol
6. Send data. 6. Send data.
7. Enable the TCP Socket connection to be automatically closed after use. 7. Enable the TCPSocket connection to be automatically closed after use.
```js ```js
import socket from '@ohos.net.socket' import socket from '@ohos.net.socket'
...@@ -93,7 +93,7 @@ The implementation is similar for UDP Socket and TCP Socket connections. The fol ...@@ -93,7 +93,7 @@ The implementation is similar for UDP Socket and TCP Socket connections. The fol
// Create a TCPSocket object. // Create a TCPSocket object.
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
// Subscribe to TCP Socket connection events. // Subscribe to TCPSocket connection events.
tcp.on('message', value => { tcp.on('message', value => {
console.log("on message") console.log("on message")
let buffer = value.message let buffer = value.message
...@@ -152,7 +152,7 @@ The implementation is similar for UDP Socket and TCP Socket connections. The fol ...@@ -152,7 +152,7 @@ The implementation is similar for UDP Socket and TCP Socket connections. The fol
}); });
}); });
// Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events. // Enable the TCPSocket connection to be automatically closed after use. Then, disable listening for TCPSocket connection events.
setTimeout(() => { setTimeout(() => {
tcp.close((err) => { tcp.close((err) => {
console.log('close socket.') console.log('close socket.')
...@@ -163,11 +163,11 @@ The implementation is similar for UDP Socket and TCP Socket connections. The fol ...@@ -163,11 +163,11 @@ The implementation is similar for UDP Socket and TCP Socket connections. The fol
}, 30 * 1000); }, 30 * 1000);
``` ```
## Implementing Encrypted Data Transmission over TLS Socket Connections ## Implementing encrypted data transmission over TLSSocket connections
### How to Develop ### How to Develop
TLS Socket connection process on the client: TLSSocket connection process on the client:
1. Import the required **socket** module. 1. Import the required **socket** module.
...@@ -177,20 +177,18 @@ TLS Socket connection process on the client: ...@@ -177,20 +177,18 @@ TLS Socket connection process on the client:
4. Create a **TLSSocket** object. 4. Create a **TLSSocket** object.
5. (Optional) Subscribe to TLS Socket connection events. 5. (Optional) Subscribe to TLSSocket connection events.
6. Send data. 6. Send data.
7. Enable the TLS Socket connection to be automatically closed after use. 7. Enable the TLSSocket connection to be automatically closed after use.
```js ```js
import socket from '@ohos.net.socket' // Create a TLSSocket connection (for two-way authentication).
let tlsTwoWay = socket.constructTLSSocketInstance();
// Create a TLS Socket connection (for two-way authentication).
let tlsTwoWay = socket.constructTLSSocketInstance();
// Subscribe to TLS Socket connection events. // Subscribe to TLSSocket 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)
...@@ -199,25 +197,25 @@ TLS Socket connection process on the client: ...@@ -199,25 +197,25 @@ TLS Socket connection process on the client:
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.
...@@ -238,16 +236,16 @@ TLS Socket connection process on the client: ...@@ -238,16 +236,16 @@ TLS Socket connection process on the client:
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 TCPSocket connection to be automatically closed after use. Then, disable listening for TCPSocket 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 {
...@@ -256,40 +254,40 @@ TLS Socket connection process on the client: ...@@ -256,40 +254,40 @@ TLS Socket connection process on the client:
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 TLSSocket 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 TLSSocket 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,
...@@ -299,16 +297,16 @@ TLS Socket connection process on the client: ...@@ -299,16 +297,16 @@ TLS Socket connection process on the client:
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 TCPSocket connection to be automatically closed after use. Then, disable listening for TCPSocket 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 {
...@@ -317,5 +315,5 @@ TLS Socket connection process on the client: ...@@ -317,5 +315,5 @@ TLS Socket connection process on the client:
tlsTwoWay.off('message'); tlsTwoWay.off('message');
tlsTwoWay.off('connect'); tlsTwoWay.off('connect');
tlsTwoWay.off('close'); tlsTwoWay.off('close');
}); });
``` ```
# 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.
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. 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';
var defaultIpAddress = "ws://"; var 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:" + JSON.stringify(value)); console.log("on open, status:" + JSON.stringify(value));
// When receiving the on('open') event, the client can use the send() API to communicate with the server. // When receiving the on('open') event, the client can use the send() API to communicate with the server.
ws.send("Hello, server!", (err, value) => { ws.send("Hello, server!", (err, value) => {
...@@ -55,8 +54,8 @@ The WebSocket connection function is mainly implemented by the WebSocket module. ...@@ -55,8 +54,8 @@ The WebSocket connection function is mainly implemented by the WebSocket module.
console.log("Failed to send the message. Err:" + JSON.stringify(err)); console.log("Failed to send the message. 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') {
...@@ -68,18 +67,18 @@ The WebSocket connection function is mainly implemented by the WebSocket module. ...@@ -68,18 +67,18 @@ The WebSocket connection function is mainly implemented by the WebSocket module.
} }
}); });
} }
}); });
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("Connected successfully"); console.log("Connected successfully");
} else { } else {
console.log("Connection failed. Err:" + JSON.stringify(err)); console.log("Connection failed. Err:" + JSON.stringify(err));
} }
}); });
``` ```
...@@ -199,8 +199,8 @@ The development process consists of the following main steps: ...@@ -199,8 +199,8 @@ The development process consists of the following main steps:
2. Run the CMake tool. 2. Run the CMake tool.
- Use hdc_std to connect to the RK3568 development board and put **demo** and **mobilenetv2.ms** to the same directory on the board. - Use hdc_std to connect to the device and put **demo** and **mobilenetv2.ms** to the same directory on the board.
- Run the hdc_std shell command to access the development board, go to the directory where **demo** is located, and run the following command: - Run the hdc_std shell command to access the device, go to the directory where **demo** is located, and run the following command:
```shell ```shell
./demo mobilenetv2.ms ./demo mobilenetv2.ms
......
...@@ -8,8 +8,6 @@ During application development, you may need to use different resources, such as ...@@ -8,8 +8,6 @@ During application development, you may need to use different resources, such as
## Resource Categories ## Resource Categories
### resources Directory
Resource files used during application development must be stored in specified directories for management. The **resources** directory consists of three types of subdirectories: the **base** subdirectory, qualifiers subdirectories, and the **rawfile** subdirectory. The common resource files used across projects in the stage model are stored in the **resources** directory under **AppScope**. Resource files used during application development must be stored in specified directories for management. The **resources** directory consists of three types of subdirectories: the **base** subdirectory, qualifiers subdirectories, and the **rawfile** subdirectory. The common resource files used across projects in the stage model are stored in the **resources** directory under **AppScope**.
The **base** subdirectory is provided by default, and the qualifiers subdirectories are created on your own. When your application needs to use a resource, the system preferentially searches the qualifiers subdirectories that match the current device state. The system searches the **base** subdirectory for the target resource only when the **resources** directory does not contain any qualifiers subdirectories that match the current device state or the target resource is not found in the qualifiers subdirectories. The **rawfile** directory is not searched for resources. The **base** subdirectory is provided by default, and the qualifiers subdirectories are created on your own. When your application needs to use a resource, the system preferentially searches the qualifiers subdirectories that match the current device state. The system searches the **base** subdirectory for the target resource only when the **resources** directory does not contain any qualifiers subdirectories that match the current device state or the target resource is not found in the qualifiers subdirectories. The **rawfile** directory is not searched for resources.
...@@ -18,37 +16,55 @@ Example of the **resources** directory: ...@@ -18,37 +16,55 @@ Example of the **resources** directory:
``` ```
resources resources
|---base // Default directory |---base
| |---element
| | |---string.json
| |---media
| | |---icon.png
| |---profile
| | |---test_profile.json
|---en_US // Default directory. When the device language is en-us, resources in this directory are preferentially matched.
| |---element
| | |---string.json
| |---media
| | |---icon.png
| |---profile
| | |---test_profile.json
|---zh_CN // Default directory. When the device language is zh-cn, resources in this directory are preferentially matched.
| |---element | |---element
| | |---string.json | | |---string.json
| |---media | |---media
| | |---icon.png | | |---icon.png
|---en_GB-vertical-car-mdpi // Example of a qualifiers subdirectory, which needs to be created on your own | |---profile
| | |---test_profile.json
|---en_GB-vertical-car-mdpi // Example of a qualifiers subdirectory, which needs to be created on your own.
| |---element | |---element
| | |---string.json | | |---string.json
| |---media | |---media
| | |---icon.png | | |---icon.png
|---rawfile | |---profile
| | |---test_profile.json
|---rawfile // Other types of files are saved as raw files and will not be integrated into the resources.index file. You can customize the file name as needed.
``` ```
**Table 1** Classification of the resources directory **Table 1** Classification of the resources directory
| Category | base Subdirectory | Qualifiers Subdirectory | rawfile Subdirectory | | Category | base Subdirectory | Qualifiers Subdirectory | rawfile Subdirectory |
| ---- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | | ---- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- |
| Structure| The **base** subdirectory is a default directory. If no qualifiers subdirectories in the **resources** directory of the application match the device status, the resource file in the **base** subdirectory will be automatically referenced.<br>Resource group subdirectories are located at the second level of subdirectories to store basic elements such as strings, colors, and boolean values, as well as resource files such as media, animations, and layouts. For details, see [Resource Group Subdirectories](#resource-group-subdirectories).| You need to create qualifiers subdirectories on your own. Each directory name consists of one or more qualifiers that represent the application scenarios or device characteristics. For details, see [Qualifiers Subdirectories](#qualifiers-subdirectories).<br>Resource group subdirectories are located at the second level of subdirectories to store basic elements such as strings, colors, and boolean values, as well as resource files such as media, animations, and layouts. For details, see [Resource Group Subdirectories](#resource-group-subdirectories).| You can create multiple levels of subdirectories with custom directory names. They can be used to store various resource files.<br>However, resource files in the **rawfile** subdirectory will not be matched based on the device status.| | Structure| The **base** subdirectory is a default directory. If no qualifiers subdirectories in the **resources** directory of the application match the device status, the resource file in the **base** subdirectory will be automatically referenced.<br>Resource group subdirectories are located at the second-level subdirectories in the **base** directory to store basic elements such as strings, colors, and boolean values, as well as resource files such as media, animations, and layouts. For details, see [Resource Group Directory](#resource-group-directory).| **en_US** and **zh_CN** are two default qualifiers subdirectories. You need to create other qualifiers subdirectories on your own. Each directory name consists of one or more qualifiers that represent the application scenarios or device characteristics. For details, see [Qualifiers Directory](#qualifiers-directory).<br>Resource group subdirectories are located at the second level of qualifiers subdirectories to store basic elements such as strings, colors, and boolean values, as well as resource files such as media, animations, and layouts. For details, see [Resource Group Directory](#resource-group-directory).| You can create multiple levels of subdirectories with custom directory names. They can be used to store various resource files.<br>However, resource files in the **rawfile** subdirectory will not be matched based on the device status.|
| Compilation| Resource files in the subdirectory are compiled into binary files, and each resource file is assigned an ID. | Resource files in the subdirectory are compiled into binary files, and each resource file is assigned an ID. | Resource files in the subdirectory are directly packed into the application without being compiled, and no IDs will be assigned to the resource files. | | Compilation| Resource files in the subdirectories are compiled into binary files, and each resource file is assigned an ID. | Resource files in the subdirectories are compiled into binary files, and each resource file is assigned an ID. | Resource files in the subdirectory are directly packed into the application without being compiled, and no IDs will be assigned to the resource files. |
| Reference| Resource files in the subdirectory are referenced based on the resource type and resource name. | Resource files in the subdirectory are referenced based on the resource type and resource name. | Resource files in the subdirectory are referenced based on the file path and file name. | | Reference| Resource files in the subdirectory are referenced based on the resource type and resource name. | Resource files in the subdirectory are referenced based on the resource type and resource name. | Resource files in the subdirectory are referenced based on the file path and file name. |
### Qualifiers Subdirectories ### Qualifiers Subdirectories
The name of a qualifiers subdirectory consists of one or more qualifiers that represent the application scenarios or device characteristics, covering the mobile country code (MCC), mobile network code (MNC), language, script, country or region, screen orientation, device type, night mode, and screen density. The qualifiers are separated using underscores (\_) or hyphens (\-). Before creating a qualifiers subdirectory, familiarize yourself with the directory naming conventions and the rules for matching qualifiers subdirectories and the device status. The name of a qualifiers subdirectory consists of one or more qualifiers that represent the application scenarios or device characteristics, covering the mobile country code (MCC), mobile network code (MNC), language, script, country or region, screen orientation, device type, night mode, and screen density. The qualifiers are separated using underscores (\_) or hyphens (\-). When creating a qualifiers subdirectory, you need to understand the directory naming conventions and the rules for matching qualifiers subdirectories and the device status.
**Naming Conventions for Qualifiers Subdirectories** **Naming Conventions for Qualifiers Subdirectories**
- Qualifiers are ordered in the following sequence: **\_MCC_MNC-language_script_country/region-orientation-device-color mode-density_**. You can select one or multiple qualifiers to name your subdirectory based on your application scenarios and device characteristics. - Qualifiers are ordered in the following sequence: **\_MCC_MNC-language_script_country/region-orientation-device-color mode-density**. You can select one or multiple qualifiers to name your subdirectory based on your application scenarios and device characteristics.
- Separation between qualifiers: The language, script, and country/region qualifiers are separated using underscores (\_); the MNC and MCC qualifiers are also separated using underscores (\_); other qualifiers are separated using hyphens (\-). For example, **zh_Hant_CN** and **zh_CN-car-ldpi**. - Separation between qualifiers: The language, script, and country/region qualifiers are separated using underscores (\_); the MNC and MCC qualifiers are also separated using underscores (\_); other qualifiers are separated using hyphens (-). For example, **zh_Hant_CN** and **zh_CN-car-ldpi**.
- Value range of qualifiers: The value of each qualifier must meet the requirements specified in the following table. Otherwise, the resource files in the resources directory cannot be matched. - Value range of qualifiers: The value of each qualifier must meet the requirements specified in the following table. Otherwise, the resource files in the resources directory cannot be matched.
...@@ -56,35 +72,34 @@ The name of a qualifiers subdirectory consists of one or more qualifiers that re ...@@ -56,35 +72,34 @@ The name of a qualifiers subdirectory consists of one or more qualifiers that re
| Qualifier Type | Description and Value Range | | Qualifier Type | Description and Value Range |
| ----------- | ---------------------------------------- | | ----------- | ---------------------------------------- |
| MCC&MNC| Indicates the MCC and MNC, which are obtained from the network where the device is registered. The MCC can be either followed by the MNC with an underscore (\_) in between or be used independently. For example, **mcc460** indicates China, and **mcc460\_mnc00** indicates China\_China Mobile.<br>For details about the value range, refer to **ITU-T E.212** (the international identification plan for public networks and subscriptions).| | MCC&MNC| Mobile country code and mobile network code, which are obtained from the network where the device is registered. The MCC can be either followed by the MNC with an underscore (\_) in between or be used independently. For example, **mcc460** indicates China, and **mcc460\_mnc00** indicates China\_China Mobile.<br>For details about the value range, refer to **ITU-T E.212** (the international identification plan for public networks and subscriptions).|
| Language | Indicates the language used by the device. The value consists of two or three lowercase letters. For example, **zh** indicates Chinese, **en** indicates English, and **mai** indicates Maithili.<br>For details about the value range, refer to **ISO 639** (codes for the representation of names of languages).| | Language | Language used by the device. The value consists of two or three lowercase letters. for example, **zh** indicates Chinese, en indicates English, and **mai** indicates Maithili.<br>For details about the value range, refer to **ISO 639** (codes for the representation of names of languages).|
| Text | Indicates the script type used by the device. The value starts with one uppercase letter followed by three lowercase letters. For example, **Hans** indicates simplified Chinese, and **Hant** indicates traditional Chinese.<br>For details about the value range, refer to **ISO 15924** (codes for the representation of names of scripts).| | Script | Script type used by the device. The value starts with one uppercase letter followed by three lowercase letters. For example, **Hans** indicates simplified Chinese, and **Hant** indicates traditional Chinese.<br>For details about the value range, refer to **ISO 15924** (codes for the representation of names of scripts).||
| Country/Region | Indicates the country or region where the user is located. The value consists of two or three uppercase letters or three digits. For example, **CN** indicates China, and **GB** indicates the United Kingdom.<br>For details about the value range, refer to **ISO 3166-1** (codes for the representation of names of countries and their subdivisions).| | Country/Region | Country or region where the user is located. The value consists of two or three uppercase letters or three digits. For example, **CN** indicates China, and **GB** indicates the United Kingdom.<br>For details about the value range, refer to **ISO 3166-1** (codes for the representation of names of countries and their subdivisions).||
| Screen orientation | Indicates the screen orientation of the device. The value can be:<br>- **vertical**: portrait orientation<br>- **horizontal**: landscape orientation| | Screen orientation | Screen orientation of the device. The value can be:<br>- **vertical**: portrait orientation<br>- **horizontal**: landscape orientation|
| Device type | Indicates the device type. The value can be:<br>- **car**: head unit<br>- **tv**: smart TV<br>- **wearable**: smart wearable| | Type of the registered device. | Device type. The value can be:<br>- **car**: head unit<br>- **tv**: smart TV<br>- **wearable**: smart wearable|
| Color mode | Indicates the color mode of the device. The value can be:<br>- **dark**: dark mode<br>- **light**: light mode| | Color mode | Color mode of the device. The value can be:<br>- **dark**: dark mode<br>- **light**: light mode|
| Screen density | Indicates the screen density of the device, in dpi. The value can be:<br>- **sdpi**: screen density with small-scale dots per inch (SDPI). This value is applicable for devices with a DPI range of (0, 120].<br>- **mdpi**: medium-scale screen density (Medium-scale Dots Per Inch), applicable to DPI whose value is (120, 160] device.<br>- **ldpi**: screen density with large-scale dots per inch (LDPI). This value is applicable for devices with a DPI range of (160, 240].<br>- **xldpi**: screen density with extra-large-scale dots per inch (XLDPI). This value is applicable for devices with a DPI range of (240, 320].<br>- **xxldpi**: screen density with extra-extra-large-scale dots per inch (XXLDPI). This value is applicable for devices with a DPI range of (320, 480].<br>- **xxxldpi**: screen density with extra-extra-extra-large-scale dots per inch (XXXLDPI). This value is applicable for devices with a DPI range of (480, 640].| | Screen density | Screen density of the device, in dpi. The value can be:<br>- **sdpi**: screen density with small-scale dots per inch (SDPI). This value is applicable for devices with a DPI range of (0, 120].<br>- **mdpi**: screen density with medium-scale dots per inch (MDPI). This value is applicable for devices with a DPI range of (120, 160].<br>- **ldpi**: screen density with large-scale dots per inch (LDPI). This value is applicable for devices with a DPI range of (160, 240].<br>- **xldpi**: screen density with extra-large-scale dots per inch (XLDPI). This value is applicable for devices with a DPI range of (240, 320].<br>- **xxldpi**: screen density with extra-extra-large-scale dots per inch (XXLDPI). This value is applicable for devices with a DPI range of (320, 480].<br>- **xxxldpi**: screen density with extra-extra-extra-large-scale dots per inch (XXXLDPI). This value is applicable for devices with a DPI range of (480, 640].|
**Rules for Matching Qualifiers Subdirectories and Device Resources** **Rules for Matching Qualifiers subdirectories and Device Resources**
- Qualifiers are matched with the device resources in the following priorities: MCC&MNC > locale (options: language, language_script, language_country/region, and language_script_country/region) > screen orientation > device type > color mode > screen density. - Qualifiers are matched with the device resources in the following priorities: MCC&MNC &gt; locale (options: language, language\_script, language\_country/region, and language\_script\_country/region) &gt; screen orientation &gt; device type &gt; color mode &gt; screen density.
- If the qualifiers subdirectories contain the **MCC, MNC, language, script, screen orientation, device type, and color mode** qualifiers, their values must be consistent with the current device status so that the subdirectories can be used for matching the device resources. For example, the qualifiers subdirectory **zh_CN-car-ldpi** cannot be used for matching the resource files labeled **en_US**. - If the qualifiers subdirectories contain the **MCC, MNC, language, script, screen orientation, device type, and color mode** qualifiers, their values must be consistent with the current device status so that the subdirectories can be used for matching the device resources. For example, the qualifiers subdirectory **zh\_CN-car-ldpi** cannot be used for matching the resource files labeled **en\_US**.
### Resource Group Subdirectories ### Resource Group Subdirectory
You can create resource group subdirectories (including element, media, and profile) in the **base** and qualifiers subdirectories to store resource files of specific types. You can create resource group subdirectories (including element, media, and profile) in the **base** and qualifiers subdirectories to store resource files of specific types.
**Table 3** Resource group subdirectories **Table 3** Resource group subdirectories
| Resource Group Subdirectory | Description | Resource File | | Resource Group Subdirectory | Description | Resource File |
| ------- | ---------------------------------------- | ---------------------------------------- | | ------- | ---------------------------------------- | ---------------------------------------- |
| element | Indicates element resources. Each type of data is represented by a JSON file. (Only files are supported in this directory.) The options are as follows:<br>- **boolean**: boolean data<br>- **color**: color data<br>- **float**: floating-point data<br>- **intarray**: array of integers<br>- **integer**: integer data<br>- **pattern**: pattern data<br>- **plural**: plural form data<br>- **strarray**: array of strings<br>- **string**: string data| It is recommended that files in the **element** subdirectory be named the same as the following files, each of which can contain only data of the same type:<br>- boolean.json<br>- color.json<br>- float.json<br>- intarray.json<br>- integer.json<br>- pattern.json<br>- plural.json<br>- strarray.json<br>- string.json | | element | Element resources. Each type of data is represented by a JSON file. (Only files are supported in this directory.) The options are as follows:<br>- **boolean**: boolean data<br>- **color**: color data<br>- **float**: floating-point data<br>- **intarray**: array of integers<br>- **integer**: integer data<br>- **pattern**: pattern data<br>- **plural**: plural form data<br>- **strarray**: array of strings<br>- **string**: string data| It is recommended that files in the **element** subdirectory be named the same as the following files, each of which can contain only data of the same type:<br>-&nbsp;boolean.json<br>-&nbsp;color.json<br>-&nbsp;float.json<br>-&nbsp;intarray.json<br>-&nbsp;integer.json<br>-&nbsp;pattern.json<br>-&nbsp;plural.json<br>-&nbsp;strarray.json<br>-&nbsp;string.json |
| media | Indicates media resources, including non-text files such as images, audios, and videos. (Only files are supported in this directory.) | The file name can be customized, for example, **icon.png**. | | media | Media resources, including non-text files such as images, audios, and videos. (Only files are supported in this directory.) | The file name can be customized, for example, **icon.png**. |
| profile | Indicates a custom configuration file. You can obtain the file content by using the [getProfileByAbility](../reference/apis/js-apis-bundleManager.md#bundlemanagergetprofilebyability) API. (Only files are supported in this directory.) | The file name can be customized, for example, **test_profile.json**. | | profile | Custom configuration file. You can obtain the file content by using the [getProfileByAbility](../reference/apis/js-apis-bundleManager.md#bundlemanagergetprofilebyability) API. (Only files are supported in this directory.) | The file name can be customized, for example, **test_profile.json**. |
| rawfile | Indicates other types of files, which are stored in their raw formats after the application is built as an HAP file. They will not be integrated into the **resources.index** file.| The file name can be customized. |
**Media Resource Types** **Media Resource Types**
...@@ -197,41 +212,41 @@ The content of the **plural.json** file is as follows: ...@@ -197,41 +212,41 @@ The content of the **plural.json** file is as follows:
**Creating a Resource File** **Creating a Resource File**
You can create a subdirectory and its files under the **resources** directory based on the preceding descriptions of the qualifiers subdirectories and resource group subdirectories. You can create a subdirectory and its files under the **resources** directory based on the above descriptions of the qualifiers subdirectories and resource group subdirectories.
DevEco Studio provides a wizard for you to create resource directories and resource files. DevEco Studio provides a wizard for you to create resource directories and resource files.
- Creating a Resource Directory and Resource File - Creating a resource directory and resource file
Right-click the **resources** directory and choose **New > Resource File**. If no qualifier is selected, the file is created in a resource type subdirectory under **base**. If one or more qualifiers are selected, the system automatically generates a subdirectory and creates the file in this subdirectory. To select a qualifier, highlight it under **Available qualifiers** and click the right arrow. To deselect a qualifier, highlight it under **Selected qualifiers** and click the left arrow. In **File name**, enter the name of the resource file to create. In **Resource type**, select the type of the resource group, which is **element** by default. In **Root Element**, select a resource type. The created subdirectory is automatically named in the format of *Qualifiers.Resource group type*. For example, if you create a subdirectory by setting **Color Mode** to **Dark** and **Resource type** to **Element**, the system automatically generates a subdirectory named **dark.element**. Right-click the **resources** directory and choose **New > Resource File**. This operation creates a subdirectory and a resource file simultaneously. If no qualifier is selected, the file is created in a resource type subdirectory under **base**. If one or more qualifiers are selected, the system automatically generates a subdirectory and creates the file in this subdirectory. To select a qualifier, highlight it under **Available qualifiers** and click the right arrow. To deselect a qualifier, highlight it under **Selected qualifiers** and click the left arrow. In **File name**, enter the name of the resource file to create. In **Resource type**, select the type of the resource group, which is **element** by default. In **Root Element**, select a resource type. The created subdirectory is automatically named in the format of *Qualifiers.Resource group type*. For example, if you create a subdirectory by setting **Color Mode** to **Dark** and **Resource type** to **Element**, the system automatically generates a subdirectory named **dark.element**.
![create-resource-file-1](figures/create-resource-file-1.png) ![create-resource-file-1](figures/create-resource-file-1.png)
- Creating a Resource Directory - Creating a resource directory
Right-click the **resources** directory and choose **New > Resource Directory** to create a subdirectory only. By default, the **base** subdirectory is created. You can create qualifiers subdirectories as required, by specifying the qualifier and resource group type. Right-click the **resources** directory and choose **New > Resource Directory**. This operation creates a subdirectory only. By default, the **base** subdirectory is created. You can create qualifiers subdirectories as required, by specifying the qualifier and resource group type. After determining the qualifier, select a resource group type. Currently, the resource group type can be **Element**, **Media**, or **Profile**. After a resource group is created, a directory name is automatically generated.
![create-resource-file-2](figures/create-resource-file-2.png) ![create-resource-file-2](figures/create-resource-file-2.png)
- Creating a Resource File - Creating a resource file
Right-click a subdirectory under **resources** and choose **New > *XXX* Resource File**. This operation creates a resource file under this subdirectory. For example, you can create an element resource file in the **element** subdirectory. Right-click a subdirectory under **resources** and choose **New > *example* Resource File**. This operation creates a resource file under this subdirectory. For example, you can create an element resource file in the **element** subdirectory.
![create-resource-file-3](figures/create-resource-file-3.png) ![create-resource-file-3](figures/create-resource-file-3.png)
**Accessing Application Resources** **Accessing Application Resources**
To reference an application resource in a project, use the **"$r('app.type.name')"** format. **app** indicates the resource defined in the **resources** directory of the application. **type** indicates the resource type (or the location where the resource is stored). The value can be **color**, **float**, **string**, **plural**, or **media**. **name** indicates the resource name, which you set when defining the resource. To reference an application resource in a project, use the `"$r('app.type.name')"` format. **app** indicates the resource defined in the **resources** directory of the application. **type** indicates the resource type (or the location where the resource is stored). The value can be **color**, **float**, **string**, **plural**, or **media**. **name** indicates the resource name, which you set when defining the resource.
When referencing resources in the **rawfile** subdirectory, use the **"$rawfile('filename')"** format. Wherein **filename** indicates the relative path of a file in the **rawfile** subdirectory, which must contain the file name extension and cannot start with a slash (/). When referencing resources in the **rawfile** subdirectory, use the `"$rawfile('filename')"` format. Wherein **filename** indicates the relative path of a file in the **rawfile** subdirectory, which must contain the file name extension and cannot start with a slash (/).
> **NOTE** > **NOTE**
> >
> Resource descriptors accept only strings, such as **'app.type.name'**, and cannot be combined. > Resource descriptors accept only strings, such as `'app.type.name'`, and cannot be combined.
> >
> The return value of **$r** is a **Resource** object. You can obtain the corresponding string by using the [getStringValue](../reference/apis/js-apis-resource-manager.md#getstringvalue9) API. > The return value of `$r` is a Resource object. You can obtain the corresponding string by using the [getStringValue](../reference/apis/js-apis-resource-manager.md#getstringvalue9) method.
In the **.ets** file, you can use the resources defined in the **resources** directory. The following is a resource usage example based on the resource file examples in [Resource Group Sub-directories](#resource-group-subdirectories): In the ***example*.ets** file, you can use the resources defined in the **resources** directory. The following is a resource usage example based on the resource file examples in [Resource Group Subdirectories](#resource-group-subdirectories):
```ts ```ts
Text($r('app.string.string_hello')) Text($r('app.string.string_hello'))
...@@ -242,8 +257,8 @@ Text($r('app.string.string_world')) ...@@ -242,8 +257,8 @@ Text($r('app.string.string_world'))
.fontColor($r('app.color.color_world')) .fontColor($r('app.color.color_world'))
.fontSize($r('app.float.font_world')) .fontSize($r('app.float.font_world'))
// Reference string resources. The second parameter of $r is used to replace %s, and value is "We will arrive at five'o clock". // Reference string resources. The second parameter of $r is used to replace %s, and value is "We will arrive at five of the clock".
Text($r('app.string.message_arrive', "five'o clock")) Text($r('app.string.message_arrive', "five of the clock"))
.fontColor($r('app.color.color_hello')) .fontColor($r('app.color.color_hello'))
.fontSize($r('app.float.font_hello')) .fontSize($r('app.float.font_hello'))
...@@ -264,13 +279,13 @@ Image($rawfile('newDir/newTest.png')) // Reference an image in the rawfile ...@@ -264,13 +279,13 @@ Image($rawfile('newDir/newTest.png')) // Reference an image in the rawfile
System resources include colors, rounded corners, fonts, spacing, character strings, and images. By using system resources, you can develop different applications with the same visual style. System resources include colors, rounded corners, fonts, spacing, character strings, and images. By using system resources, you can develop different applications with the same visual style.
To reference a system resource, use the **"$r('sys.type.resource_id')"** format. Wherein: **sys** indicates a system resource; **type** indicates the resource type, which can be **color**, **float**, **string**, or **media**; **resource_id** indicates the resource ID. To reference a system resource, use the `"$r('sys.type.resource_id')"` format. Wherein: **sys** indicates a system resource; **type** indicates the resource type, which can be **color**, **float**, **string**, or **media**; **resource_id** indicates the resource ID.
> **NOTE** > **NOTE**
> >
> - Use of system resources is supported in the declarative development paradigm, but not in the web-like development paradigm. > - Use of system resources is supported in the declarative development paradigm, but not in the web-like development paradigm.
> >
> - For details about the implementation of preconfigured resources, visit the [OpenHarmony/resources repository](https://gitee.com/openharmony/resources/tree/master/systemres/main/resources). The directory structure there is similar to that of the **resources** directory in the project. Resource qualifiers are used to match resources with different devices and device states. > - For details about the implementation of preconfigured resources, visit the [OpenHarmony/resources repository](https://gitee.com/openharmony/resources/tree/master/systemres/main/resources). The directory structure there is similar to that of the **resources** directory in the project. Resource qualifiers are used to match resources with different devices and device status.
```ts ```ts
Text('Hello') Text('Hello')
......
# Geolocation # @ohos.geolocation (Geolocation)
The **geolocation** module provides a wide array of location services, including GNSS positioning, network positioning, geocoding, reverse geocoding, and geofencing. The **geolocation** module provides a wide array of location services, including GNSS positioning, network positioning, geocoding, reverse geocoding, and geofencing.
......
# @ohos.hidebug (HiDebug) # @ohos.hidebug (HiDebug)
The **hidebug** module provides APIs for you to obtain the memory usage of an application, including the static heap memory (native heap) and proportional set size (PSS) occupied by the application process. You can also export VM memory slices and collect VM CPU profiling data. > **NOTE**
>
> **NOTE**<br>
> 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. > 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.
The **hidebug** module provides APIs for you to obtain the memory usage of an application, including the static heap memory (native heap) and proportional set size (PSS) occupied by the application process. You can also export VM memory slices and collect VM CPU profiling data.
## Modules to Import ## Modules to Import
...@@ -19,8 +19,6 @@ getNativeHeapSize(): bigint ...@@ -19,8 +19,6 @@ getNativeHeapSize(): bigint
Obtains the total heap memory size of this application. Obtains the total heap memory size of this application.
This API is defined but not implemented in OpenHarmony 3.1 Release.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value** **Return value**
...@@ -42,8 +40,6 @@ getNativeHeapAllocatedSize(): bigint ...@@ -42,8 +40,6 @@ getNativeHeapAllocatedSize(): bigint
Obtains the allocated heap memory size of this application. Obtains the allocated heap memory size of this application.
This API is defined but not implemented in OpenHarmony 3.1 Release.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value** **Return value**
...@@ -65,8 +61,6 @@ getNativeHeapFreeSize(): bigint ...@@ -65,8 +61,6 @@ getNativeHeapFreeSize(): bigint
Obtains the free heap memory size of this application. Obtains the free heap memory size of this application.
This API is defined but not implemented in OpenHarmony 3.1 Release.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value** **Return value**
...@@ -163,76 +157,6 @@ For example, if the CPU usage is **50%**, **0.5** is returned. ...@@ -163,76 +157,6 @@ For example, if the CPU usage is **50%**, **0.5** is returned.
let cpuUsage = hidebug.getCpuUsage(); let cpuUsage = hidebug.getCpuUsage();
``` ```
## hidebug.startProfiling<sup>(deprecated)</sup>
startProfiling(filename : string) : void
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.startJsCpuProfiling](#hidebugstartjscpuprofiling9) instead.
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`.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ |
| filename | string | Yes | User-defined profile name. The `filename.json` file is generated in the `files` directory of the application based on the specified `filename`.|
**Example**
```js
hidebug.startProfiling("cpuprofiler-20220216");
// code block
// ...
// code block
hidebug.stopProfiling();
```
## hidebug.stopProfiling<sup>(deprecated)</sup>
stopProfiling() : void
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.stopJsCpuProfiling](#hidebugstopjscpuprofiling9) instead.
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`.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Example**
```js
hidebug.startProfiling("cpuprofiler-20220216");
// code block
// ...
// code block
hidebug.stopProfiling();
```
## hidebug.dumpHeapData<sup>(deprecated)</sup>
dumpHeapData(filename : string) : void
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.dumpJsHeapData](#hidebugdumpjsheapdata9) instead.
Exports the heap data.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ |
| filename | string | Yes | User-defined heap file name. The `filename.heapsnapshot` file is generated in the `files` directory of the application based on the specified `filename`.|
**Example**
```js
hidebug.dumpHeapData("heap-20220216");
```
## hidebug.getServiceDump<sup>9+<sup> ## hidebug.getServiceDump<sup>9+<sup>
getServiceDump(serviceid : number, fd : number, args : Array\<string>) : void getServiceDump(serviceid : number, fd : number, args : Array\<string>) : void
...@@ -251,11 +175,10 @@ Obtains system service information. ...@@ -251,11 +175,10 @@ Obtains system service information.
| fd | number | Yes | File descriptor to which data is written by the API.| | fd | number | Yes | File descriptor to which data is written by the API.|
| args | Array\<string> | Yes | Parameter list corresponding to the **Dump** API of the system service.| | args | Array\<string> | Yes | Parameter list corresponding to the **Dump** API of the system service.|
**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'
...@@ -263,7 +186,7 @@ let context = featureAbility.getContext(); ...@@ -263,7 +186,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 {
...@@ -272,7 +195,7 @@ context.getFilesDir().then((data) => { ...@@ -272,7 +195,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);
}) })
``` ```
...@@ -360,3 +283,79 @@ try { ...@@ -360,3 +283,79 @@ try {
console.info(error.message) console.info(error.message)
} }
``` ```
## hidebug.startProfiling<sup>(deprecated)</sup>
startProfiling(filename : string) : void
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [hidebug.startJsCpuProfiling](#hidebugstartjscpuprofiling9).
Starts the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ |
| filename | string | Yes | User-defined profile name. The `filename.json` file is generated in the `files` directory of the application based on the specified `filename`.|
**Example**
```js
hidebug.startProfiling("cpuprofiler-20220216");
// code block
// ...
// code block
hidebug.stopProfiling();
```
## hidebug.stopProfiling<sup>(deprecated)</sup>
stopProfiling() : void
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [hidebug.stopJsCpuProfiling](#hidebugstopjscpuprofiling9).
Stops the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Example**
```js
hidebug.startProfiling("cpuprofiler-20220216");
// code block
// ...
// code block
hidebug.stopProfiling();
```
## hidebug.dumpHeapData<sup>(deprecated)</sup>
dumpHeapData(filename : string) : void
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [hidebug.dumpJsHeapData](#hidebugdumpjsheapdata9).
Exports the heap data.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ |
| filename | string | Yes | User-defined heap file name. The `filename.heapsnapshot` file is generated in the `files` directory of the application based on the specified `filename`.|
**Example**
```js
hidebug.dumpHeapData("heap-20220216");
```
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
The **http** module provides the HTTP data request capability. An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**. The **http** module provides the HTTP data request capability. An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**.
>**NOTE** > **NOTE**
> >
>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. >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.
> >
...@@ -35,11 +35,11 @@ httpRequest.request( ...@@ -35,11 +35,11 @@ httpRequest.request(
header: { header: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}, },
// This field is used to transfer data when the POST request is used. // This parameter 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 parameter 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.
...@@ -82,6 +82,7 @@ Creates an HTTP request. You can use this API to initiate or destroy an HTTP req ...@@ -82,6 +82,7 @@ Creates an HTTP request. You can use this API to initiate or destroy an HTTP req
```js ```js
import http from '@ohos.net.http'; import http from '@ohos.net.http';
let httpRequest = http.createHttp(); let httpRequest = http.createHttp();
``` ```
...@@ -95,8 +96,8 @@ request(url: string, callback: AsyncCallback\<HttpResponse\>):void ...@@ -95,8 +96,8 @@ request(url: string, callback: AsyncCallback\<HttpResponse\>):void
Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result. Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result.
>**NOTE** > **NOTE**
>This API supports only transfer of data not greater than 5 MB. > This API supports only transfer of data not greater than 5 MB.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -121,7 +122,7 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback ...@@ -121,7 +122,7 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback
| 2300052 | Server returned nothing (no headers, no data). | | 2300052 | Server returned nothing (no headers, no data). |
| 2300999 | Unknown Other Error. | | 2300999 | Unknown Other Error. |
>**NOTE** > **NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). > For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html). > The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html).
...@@ -146,8 +147,8 @@ request(url: string, options: HttpRequestOptions, callback: AsyncCallback\<HttpR ...@@ -146,8 +147,8 @@ request(url: string, options: HttpRequestOptions, callback: AsyncCallback\<HttpR
Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result. Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result.
>**NOTE** > **NOTE**
>This API supports only transfer of data not greater than 5 MB. > This API supports only transfer of data not greater than 5 MB.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -197,7 +198,7 @@ Initiates an HTTP request containing specified options to a given URL. This API ...@@ -197,7 +198,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
| 2300094 | An authentication function returned an error. | | 2300094 | An authentication function returned an error. |
| 2300999 | Unknown Other Error. | | 2300999 | Unknown Other Error. |
>**NOTE** > **NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). > For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html). > The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html).
...@@ -205,14 +206,14 @@ Initiates an HTTP request containing specified options to a given URL. This API ...@@ -205,14 +206,14 @@ Initiates an HTTP request containing specified options to a given URL. This API
```js ```js
httpRequest.request("EXAMPLE_URL", httpRequest.request("EXAMPLE_URL",
{ {
method: http.RequestMethod.GET, method: http.RequestMethod.GET,
header: { header: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}, },
readTimeout: 60000, readTimeout: 60000,
connectTimeout: 60000 connectTimeout: 60000
}, (err, data) => { }, (err, data) => {
if (!err) { if (!err) {
console.info('Result:' + data.result); console.info('Result:' + data.result);
console.info('code:' + data.responseCode); console.info('code:' + data.responseCode);
...@@ -223,7 +224,7 @@ httpRequest.request("EXAMPLE_URL", ...@@ -223,7 +224,7 @@ httpRequest.request("EXAMPLE_URL",
} else { } else {
console.info('error:' + JSON.stringify(err)); console.info('error:' + JSON.stringify(err));
} }
}); });
``` ```
### request ### request
...@@ -232,8 +233,8 @@ request(url: string, options? : HttpRequestOptions): Promise\<HttpResponse\> ...@@ -232,8 +233,8 @@ request(url: string, options? : HttpRequestOptions): Promise\<HttpResponse\>
Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result. Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result.
>**NOTE** > **NOTE**
>This API supports only transfer of data not greater than 5 MB. > This API supports only transfer of data not greater than 5 MB.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -288,7 +289,7 @@ Initiates an HTTP request containing specified options to a given URL. This API ...@@ -288,7 +289,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
| 2300094 | An authentication function returned an error. | | 2300094 | An authentication function returned an error. |
| 2300999 | Unknown Other Error. | | 2300999 | Unknown Other Error. |
>**NOTE** > **NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md). > For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html). > The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html).
...@@ -335,8 +336,8 @@ on(type: 'headerReceive', callback: AsyncCallback\<Object\>): void ...@@ -335,8 +336,8 @@ on(type: 'headerReceive', callback: AsyncCallback\<Object\>): void
Registers an observer for HTTP Response Header events. Registers an observer for HTTP Response Header events.
>**NOTE** > **NOTE**
>This API has been deprecated. You are advised to use [on('headersReceive')<sup>8+</sup>](#onheadersreceive8). > This API has been deprecated. You are advised to use [on('headersReceive')<sup>8+</sup>](#onheadersreceive8).
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -361,7 +362,7 @@ off(type: 'headerReceive', callback?: AsyncCallback\<Object\>): void ...@@ -361,7 +362,7 @@ off(type: 'headerReceive', callback?: AsyncCallback\<Object\>): void
Unregisters the observer for HTTP Response Header events. Unregisters the observer for HTTP Response Header events.
>**NOTE** > **NOTE**
> >
>1. This API has been deprecated. You are advised to use [off('headersReceive')<sup>8+</sup>](#offheadersreceive8). >1. This API has been deprecated. You are advised to use [off('headersReceive')<sup>8+</sup>](#offheadersreceive8).
> >
...@@ -411,8 +412,8 @@ off(type: 'headersReceive', callback?: Callback\<Object\>): void ...@@ -411,8 +412,8 @@ off(type: 'headersReceive', callback?: Callback\<Object\>): void
Unregisters the observer for HTTP Response Header events. Unregisters the observer for HTTP Response Header events.
>**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
...@@ -460,11 +461,11 @@ Specifies the type and value range of the optional parameters in the HTTP reques ...@@ -460,11 +461,11 @@ Specifies the type and value range of the optional parameters in the HTTP reques
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | | -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
| method | [RequestMethod](#requestmethod) | No | Request method. | | method | [RequestMethod](#requestmethod) | No | Request method. The default value is **GET**. |
| extraData | string \| Object \| ArrayBuffer<sup>6+</sup> | No | Additional data of the request.<br>- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.<br>- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.<sup>6+</sup><br>- To pass in a string object, you first need to encode the object on your own.<sup>6+</sup> | | extraData | string<sup>6+</sup> \| Object<sup>6+</sup> \| ArrayBuffer<sup>8+</sup> | No | Additional data for sending a request. This parameter is not used by default.<br>- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request and is encoded in UTF-8 format.<sup>6+</sup><br>- If the HTTP request uses the GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter serves as a supplement to HTTP request parameters. Parameters of the string type need to be encoded before being passed to the HTTP request. Parameters of the object type do not need to be precoded and will be directly concatenated to the URL. Parameters of the ArrayBuffer type will not be concatenated to the URL.<sup>6+</sup> |
| expectDataType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | No | Type of the return data. If this parameter is set, the system returns the specified type of data preferentially.| | expectDataType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | No | Type of the returned data. This parameter is not used by default. If this parameter is set, the system returns the specified type of data preferentially.|
| usingCache<sup>9+</sup> | boolean | No | Whether to use the cache. The default value is **true**. | | usingCache<sup>9+</sup> | boolean | No | Whether to use the cache. The default value is **true**. |
| priority<sup>9+</sup> | number | No | Priority. The value range is \[1,1000]. The default value is **1**. | | priority<sup>9+</sup> | number | No | Priority. The value range is \[0, 1000]. The default value is **0**. |
| header | Object | No | HTTP request header. The default value is **{'Content-Type': 'application/json'}**. | | header | Object | No | HTTP request header. The default value is **{'Content-Type': 'application/json'}**. |
| readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. | | readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. |
| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. | | connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. |
...@@ -539,10 +540,10 @@ Defines the response to an HTTP request. ...@@ -539,10 +540,10 @@ Defines the response to an HTTP request.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | | -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
| result | string \| Object \| ArrayBuffer<sup>6+</sup> | Yes | Response content returned based on **Content-type** in the response header:<br>- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.<br>- application/octet-stream: ArrayBuffer<br>- Others: string| | result | string<sup>6+</sup> \| Object<sup>deprecated 8+</sup> \| ArrayBuffer<sup>8+</sup> | Yes | Response content returned based on **Content-type** in the response header:<br>- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.<br>- application/octet-stream: ArrayBuffer<br>- Others: string|
| resultType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | Yes | Type of the return value. | | resultType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | Yes | Type of the return value. |
| responseCode | [ResponseCode](#responsecode) \| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**.| | responseCode | [ResponseCode](#responsecode) \| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**.|
| header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:<br>- Content-Type: header['Content-Type'];<br>- Status-Line: header['Status-Line'];<br>- Date: header.Date/header['Date'];<br>- Server: header.Server/header['Server'];| | header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:<br>- content-type: header['content-type'];<br>- status-line: header['status-line'];<br>- date: header.date/header['date'];<br>- server: header.server/header['server'];|
| cookies<sup>8+</sup> | string | Yes | Cookies returned by the server. | | cookies<sup>8+</sup> | string | Yes | Cookies returned by the server. |
## http.createHttpResponseCache<sup>9+</sup> ## http.createHttpResponseCache<sup>9+</sup>
...@@ -569,6 +570,7 @@ Creates a default object to store responses to HTTP access requests. ...@@ -569,6 +570,7 @@ Creates a default object to store responses to HTTP access requests.
```js ```js
import http from '@ohos.net.http'; import http from '@ohos.net.http';
let httpResponseCache = http.createHttpResponseCache(); let httpResponseCache = http.createHttpResponseCache();
``` ```
...@@ -651,6 +653,7 @@ httpResponseCache.delete(err => { ...@@ -651,6 +653,7 @@ httpResponseCache.delete(err => {
console.info('delete success'); console.info('delete success');
}); });
``` ```
### delete<sup>9+</sup> ### delete<sup>9+</sup>
delete(): Promise\<void\> delete(): Promise\<void\>
......
...@@ -10,6 +10,7 @@ The network connection management module provides basic network management capab ...@@ -10,6 +10,7 @@ The network connection management module provides basic network management capab
```js ```js
import connection from '@ohos.net.connection' import connection from '@ohos.net.connection'
``` ```
## connection.createNetConnection ## connection.createNetConnection
createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection
...@@ -34,10 +35,10 @@ Creates a **NetConnection** object. **netSpecifier** specifies the network, and ...@@ -34,10 +35,10 @@ Creates a **NetConnection** object. **netSpecifier** specifies the network, and
**Example** **Example**
```js ```js
// Default network // For the default network, you do not need to pass in parameters.
let netConnection = connection.createNetConnection() let netConnection = connection.createNetConnection()
// Cellular network // For the cellular network, you need to pass in related network parameters. If the timeout parameter is not specified, the timeout value is 0 by default.
let netConnectionCellular = connection.createNetConnection({ let netConnectionCellular = connection.createNetConnection({
netCapabilities: { netCapabilities: {
bearerTypes: [connection.NetBearType.BEARER_CELLULAR] bearerTypes: [connection.NetBearType.BEARER_CELLULAR]
...@@ -164,7 +165,7 @@ Obtains information about the network bound to an application. This API uses an ...@@ -164,7 +165,7 @@ Obtains information about the network bound to an application. This API uses an
**Example** **Example**
```js ```js
connection.getAppNet(function(error, data) { connection.getAppNet(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
...@@ -774,8 +775,7 @@ connection.disableAirplaneMode().then(function (error) { ...@@ -774,8 +775,7 @@ connection.disableAirplaneMode().then(function (error) {
reportNetConnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void reportNetConnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void
Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. Reports connection of the data network to the network management module. This API uses an asynchronous callback to return the result.
This API uses an asynchronous callback to return the result.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
...@@ -812,8 +812,7 @@ connection.getDefaultNet().then(function (netHandle) { ...@@ -812,8 +812,7 @@ connection.getDefaultNet().then(function (netHandle) {
reportNetConnected(netHandle: NetHandle): Promise&lt;void&gt; reportNetConnected(netHandle: NetHandle): Promise&lt;void&gt;
Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. Reports connection of the data network to the network management module. This API uses a promise to return the result.
This API uses a promise to return the result.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
...@@ -854,8 +853,7 @@ connection.getDefaultNet().then(function (netHandle) { ...@@ -854,8 +853,7 @@ connection.getDefaultNet().then(function (netHandle) {
reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void
Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. Reports disconnection of the data network to the network management module. This API uses an asynchronous callback to return the result.
This API uses an asynchronous callback to return the result.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
...@@ -892,8 +890,7 @@ connection.getDefaultNet().then(function (netHandle) { ...@@ -892,8 +890,7 @@ connection.getDefaultNet().then(function (netHandle) {
reportNetDisconnected(netHandle: NetHandle): Promise&lt;void&gt; reportNetDisconnected(netHandle: NetHandle): Promise&lt;void&gt;
Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. Reports disconnection of the data network to the network management module. This API uses a promise to return the result.
This API uses a promise to return the result.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
...@@ -1038,7 +1035,6 @@ Registers a listener for network status changes. ...@@ -1038,7 +1035,6 @@ Registers a listener for network status changes.
| 2101008 | The callback is not exists. | | 2101008 | The callback is not exists. |
| 2101022 | The number of requests exceeded the maximum. | | 2101022 | The number of requests exceeded the maximum. |
**Example** **Example**
```js ```js
...@@ -1196,7 +1192,8 @@ netCon.unregister(function (error) { ...@@ -1196,7 +1192,8 @@ netCon.unregister(function (error) {
### on('netConnectionPropertiesChange') ### on('netConnectionPropertiesChange')
on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHandle, connectionProperties:
ConnectionProperties }>): void
Registers a listener for **netConnectionPropertiesChange** events. Registers a listener for **netConnectionPropertiesChange** events.
...@@ -1209,7 +1206,7 @@ Registers a listener for **netConnectionPropertiesChange** events. ...@@ -1209,7 +1206,7 @@ Registers a listener for **netConnectionPropertiesChange** events.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The value is fixed to **netConnectionPropertiesChange**.<br>**netConnectionPropertiesChange**: event indicating that network connection properties have changed.| | type | string | Yes | Event type. The value is fixed to **netConnectionPropertiesChange**.<br>**netConnectionPropertiesChange**: event indicating that network connection properties have changed.|
| callback | Callback<{ netHandle: [NetHandle](#nethandle), connectionProperties: [ConnectionProperties](#connectionproperties) }> | Yes | Callback used to return the network handle (**netHandle**) and capability information (**netCap**).| | callback | Callback<{ netHandle: [NetHandle](#nethandle), connectionProperties: [ConnectionProperties](#connectionproperties) }> | Yes | Callback used to return the network handle (**netHandle**) and conection information (**connectionProperties**).|
**Example** **Example**
...@@ -1353,6 +1350,7 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses ...@@ -1353,6 +1350,7 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses
```js ```js
import socket from "@ohos.net.socket"; import socket from "@ohos.net.socket";
connection.getDefaultNet().then((netHandle) => { connection.getDefaultNet().then((netHandle) => {
var tcp = socket.constructTCPSocketInstance(); var tcp = socket.constructTCPSocketInstance();
var udp = socket.constructUDPSocketInstance(); var udp = socket.constructUDPSocketInstance();
...@@ -1363,6 +1361,7 @@ connection.getDefaultNet().then((netHandle) => { ...@@ -1363,6 +1361,7 @@ connection.getDefaultNet().then((netHandle) => {
}, error => { }, error => {
if (error) { if (error) {
console.log('bind fail'); console.log('bind fail');
return;
} }
netHandle.bindSocket(tcp, (error, data) => { netHandle.bindSocket(tcp, (error, data) => {
if (error) { if (error) {
...@@ -1382,6 +1381,7 @@ connection.getDefaultNet().then((netHandle) => { ...@@ -1382,6 +1381,7 @@ connection.getDefaultNet().then((netHandle) => {
}, error => { }, error => {
if (error) { if (error) {
console.log('bind fail'); console.log('bind fail');
return;
} }
udp.on('message', (data) => { udp.on('message', (data) => {
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
...@@ -1431,6 +1431,7 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses ...@@ -1431,6 +1431,7 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses
```js ```js
import socket from "@ohos.net.socket"; import socket from "@ohos.net.socket";
connection.getDefaultNet().then((netHandle) => { connection.getDefaultNet().then((netHandle) => {
var tcp = socket.constructTCPSocketInstance(); var tcp = socket.constructTCPSocketInstance();
var udp = socket.constructUDPSocketInstance(); var udp = socket.constructUDPSocketInstance();
...@@ -1441,6 +1442,7 @@ connection.getDefaultNet().then((netHandle) => { ...@@ -1441,6 +1442,7 @@ connection.getDefaultNet().then((netHandle) => {
}, error => { }, error => {
if (error) { if (error) {
console.log('bind fail'); console.log('bind fail');
return;
} }
netHandle.bindSocket(tcp).then((data) => { netHandle.bindSocket(tcp).then((data) => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
...@@ -1458,6 +1460,7 @@ connection.getDefaultNet().then((netHandle) => { ...@@ -1458,6 +1460,7 @@ connection.getDefaultNet().then((netHandle) => {
}, error => { }, error => {
if (error) { if (error) {
console.log('bind fail'); console.log('bind fail');
return;
} }
udp.on('message', (data) => { udp.on('message', (data) => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
...@@ -1732,8 +1735,8 @@ Defines a network address. ...@@ -1732,8 +1735,8 @@ Defines a network address.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Mandatory| Description | | Name| Type| Mandatory| Description|
| ------- | ------ | -- |------------------------------ | | ------- | ------ | -- |------------------------------ |
| address | string | Yes|Network address. | | address | string | Yes|Network address.|
| family | number | No|Address family identifier. The value is **1** for IPv4 and **2** for IPv6. The default value is **1**.| | family | number | No|Address family identifier. The value is **1** for IPv4 and **2** for IPv6. The default value is **1**.|
| port | number | No|Port number. The value ranges from **0** to **65535**. | | port | number | No|Port number. The value ranges from **0** to **65535**.|
...@@ -386,6 +386,74 @@ ethernet.getAllActiveIfaces().then((data) => { ...@@ -386,6 +386,74 @@ ethernet.getAllActiveIfaces().then((data) => {
}); });
``` ```
## 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.
......
...@@ -46,7 +46,9 @@ policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))), (error, da ...@@ -46,7 +46,9 @@ policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))), (error, da
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,7 +86,7 @@ Sets a background network policy. This API uses a promise to return the result. ...@@ -84,7 +86,7 @@ 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))
}) })
...@@ -151,7 +153,7 @@ Obtains the background network policy. This API uses a promise to return the res ...@@ -151,7 +153,7 @@ 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))
}) })
...@@ -236,7 +238,7 @@ Sets an application-specific network policy. This API uses a promise to return t ...@@ -236,7 +238,7 @@ Sets an application-specific network policy. This API uses a promise to return t
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))
}) })
...@@ -313,7 +315,7 @@ Obtains an application-specific network policy by **uid**. This API uses a promi ...@@ -313,7 +315,7 @@ 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))
}) })
...@@ -390,7 +392,7 @@ Obtains the UID array of applications configured with a certain application-spec ...@@ -390,7 +392,7 @@ 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))
}) })
...@@ -456,7 +458,7 @@ Obtains the network quota policies. This API uses a promise to return the result ...@@ -456,7 +458,7 @@ 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,8 +495,18 @@ Sets an array of network quota policies. This API uses an asynchronous callback ...@@ -493,8 +495,18 @@ 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) => {
...@@ -537,11 +549,21 @@ Sets an array of network quota policies. This API uses a promise to return the r ...@@ -537,11 +549,21 @@ 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))
}) })
...@@ -619,7 +641,7 @@ Restores all the policies (cellular network, background network, firewall, and a ...@@ -619,7 +641,7 @@ 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))
}) })
...@@ -706,7 +728,7 @@ Checks whether an application is allowed to access metered networks. This API us ...@@ -706,7 +728,7 @@ Checks whether an application is allowed to access metered networks. This API us
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))
}) })
...@@ -792,7 +814,7 @@ Checks whether an application is allowed to access the given network. This API u ...@@ -792,7 +814,7 @@ Checks whether an application is allowed to access the given network. This API u
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))
}) })
...@@ -877,7 +899,7 @@ Sets whether to add an application to the device idle allowlist. This API uses a ...@@ -877,7 +899,7 @@ Sets whether to add an application to the device idle allowlist. This API uses a
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))
}) })
...@@ -943,7 +965,7 @@ Obtains the UID array of applications that are on the device idle allowlist. Thi ...@@ -943,7 +965,7 @@ 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))
}) })
...@@ -1021,7 +1043,7 @@ Obtains the background network policies configured for the given application. Th ...@@ -1021,7 +1043,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)).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))
}) })
...@@ -1098,11 +1120,11 @@ Restores all the policies (cellular network, background network, firewall, and a ...@@ -1098,11 +1120,11 @@ 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))
}) })
...@@ -1189,7 +1211,7 @@ Updates a reminder policy. This API uses a promise to return the result. ...@@ -1189,7 +1211,7 @@ Updates a reminder policy. This API uses a promise to return the result.
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))
}) })
...@@ -1274,7 +1296,7 @@ Sets whether to add an application to the power-saving allowlist. This API uses ...@@ -1274,7 +1296,7 @@ Sets whether to add an application to the power-saving allowlist. This API uses
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))
}) })
...@@ -1340,7 +1362,7 @@ Obtains the UID array of applications that are on the device idle allowlist. Thi ...@@ -1340,7 +1362,7 @@ 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))
}) })
......
...@@ -194,7 +194,8 @@ Starts network sharing of a specified type. This API uses an asynchronous callba ...@@ -194,7 +194,8 @@ 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,7 +244,8 @@ Starts network sharing of a specified type. This API uses a promise to return th ...@@ -243,7 +244,8 @@ 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 => {
...@@ -287,7 +289,8 @@ Stops network sharing of a specified type. This API uses an asynchronous callbac ...@@ -287,7 +289,8 @@ 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,7 +337,8 @@ Stops network sharing of a specified type. This API uses a promise to return the ...@@ -334,7 +337,8 @@ 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 => {
...@@ -588,7 +592,8 @@ Obtains the names of NICs in the specified network sharing state. This API uses ...@@ -588,7 +592,8 @@ 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,7 +638,8 @@ Obtains the names of NICs in the specified network sharing state. This API uses ...@@ -633,7 +638,8 @@ 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 => {
...@@ -674,7 +680,8 @@ Obtains the network sharing state of the specified type. This API uses an asynch ...@@ -674,7 +680,8 @@ 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,7 +726,8 @@ Obtains the network sharing state of the specified type. This API uses a promise ...@@ -719,7 +726,8 @@ 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 => {
...@@ -760,7 +768,8 @@ Obtains regular expressions of NICs of a specified type. This API uses an asynch ...@@ -760,7 +768,8 @@ 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,7 +814,8 @@ Obtains regular expressions of NICs of a specified type. This API uses a promise ...@@ -805,7 +814,8 @@ 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 => {
...@@ -842,7 +852,7 @@ Subscribes to network sharing state changes. This API uses an asynchronous callb ...@@ -842,7 +852,7 @@ 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));
}); });
``` ```
...@@ -910,8 +920,8 @@ Subscribes to network sharing state changes of a specified NIC. This API uses an ...@@ -910,8 +920,8 @@ 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));
}); });
``` ```
...@@ -978,8 +988,8 @@ Subscribes to upstream network changes. This API uses an asynchronous callback t ...@@ -978,8 +988,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));
}); });
``` ```
......
...@@ -26,14 +26,12 @@ Creates a **UDPSocket** object. ...@@ -26,14 +26,12 @@ Creates a **UDPSocket** object.
| :--------------------------------- | :---------------------- | | :--------------------------------- | :---------------------- |
| [UDPSocket](#udpsocket) | **UDPSocket** object.| | [UDPSocket](#udpsocket) | **UDPSocket** object.|
**Example** **Example**
```js ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
``` ```
## UDPSocket ## UDPSocket
Defines a **UDPSocket** connection. Before invoking UDPSocket APIs, you need to call [socket.constructUDPSocketInstance](#socketconstructudpsocketinstance) to create a **UDPSocket** object. Defines a **UDPSocket** connection. Before invoking UDPSocket APIs, you need to call [socket.constructUDPSocketInstance](#socketconstructudpsocketinstance) to create a **UDPSocket** object.
...@@ -75,7 +73,6 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { ...@@ -75,7 +73,6 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
}) })
``` ```
### bind ### bind
bind(address: NetAddress): Promise\<void\> bind(address: NetAddress): Promise\<void\>
...@@ -110,14 +107,13 @@ Binds the IP address and port number. The port number can be specified or random ...@@ -110,14 +107,13 @@ Binds the IP address and port number. The port number can be specified or random
```js ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
let promise = udp.bind({address: '192.168.xx.xxx', port: 8080, family: 1}); let promise = udp.bind({address: '192.168.xx.xxx', port: 8080, family: 1});
promise .then(() => { promise.then(() => {
console.log('bind success'); console.log('bind success');
}).catch(err => { }).catch(err => {
console.log('bind fail'); console.log('bind fail');
}); });
``` ```
### send ### send
send(options: UDPSendOptions, callback: AsyncCallback\<void\>): void send(options: UDPSendOptions, callback: AsyncCallback\<void\>): void
...@@ -149,13 +145,13 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p ...@@ -149,13 +145,13 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p
```js ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
udp.send({ udp.send({
data:'Hello, server!', data: 'Hello, server!',
address: { address: {
address:'192.168.xx.xxx', address: '192.168.xx.xxx',
port:xxxx, port: xxxx,
family:1 family: 1
} }
}, err=> { }, err => {
if (err) { if (err) {
console.log('send fail'); console.log('send fail');
return; return;
...@@ -164,7 +160,6 @@ udp.send({ ...@@ -164,7 +160,6 @@ udp.send({
}) })
``` ```
### send ### send
send(options: UDPSendOptions): Promise\<void\> send(options: UDPSendOptions): Promise\<void\>
...@@ -201,11 +196,11 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p ...@@ -201,11 +196,11 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p
```js ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
let promise = udp.send({ let promise = udp.send({
data:'Hello, server!', data: 'Hello, server!',
address: { address: {
address:'192.168.xx.xxx', address: '192.168.xx.xxx',
port:xxxx, port: xxxx,
family:1 family: 1
} }
}); });
promise.then(() => { promise.then(() => {
...@@ -215,7 +210,6 @@ promise.then(() => { ...@@ -215,7 +210,6 @@ promise.then(() => {
}); });
``` ```
### close ### close
close(callback: AsyncCallback\<void\>): void close(callback: AsyncCallback\<void\>): void
...@@ -245,7 +239,6 @@ udp.close(err => { ...@@ -245,7 +239,6 @@ udp.close(err => {
}) })
``` ```
### close ### close
close(): Promise\<void\> close(): Promise\<void\>
...@@ -274,15 +267,14 @@ promise.then(() => { ...@@ -274,15 +267,14 @@ promise.then(() => {
}); });
``` ```
### getState ### getState
getState(callback: AsyncCallback\<SocketStateBase\>): void getState(callback: AsyncCallback\<SocketStateBase\>): void
Obtains the status of the UDPSocket connection. This API uses an asynchronous callback to return the result. Obtains the status of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE** > **NOTE**
>This API can be called only after **bind** is successfully called. > This API can be called only after **bind** is successfully called.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -320,15 +312,14 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { ...@@ -320,15 +312,14 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
}) })
``` ```
### getState ### getState
getState(): Promise\<SocketStateBase\> getState(): Promise\<SocketStateBase\>
Obtains the status of the UDPSocket connection. This API uses a promise to return the result. Obtains the status of the UDPSocket connection. This API uses a promise to return the result.
>**NOTE** > **NOTE**
>This API can be called only after **bind** is successfully called. > This API can be called only after **bind** is successfully called.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -344,7 +335,8 @@ Obtains the status of the UDPSocket connection. This API uses a promise to retur ...@@ -344,7 +335,8 @@ Obtains the status of the UDPSocket connection. This API uses a promise to retur
```js ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { let promise = udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1});
promise.then(err => {
if (err) { if (err) {
console.log('bind fail'); console.log('bind fail');
return; return;
...@@ -356,18 +348,17 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { ...@@ -356,18 +348,17 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
}).catch(err => { }).catch(err => {
console.log('getState fail'); console.log('getState fail');
}); });
}) });
``` ```
### setExtraOptions ### setExtraOptions
setExtraOptions(options: UDPExtraOptions, callback: AsyncCallback\<void\>): void setExtraOptions(options: UDPExtraOptions, callback: AsyncCallback\<void\>): void
Sets other attributes of the UDPSocket connection. This API uses an asynchronous callback to return the result. Sets other attributes of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE** > **NOTE**
>This API can be called only after **bind** is successfully called. > This API can be called only after **bind** is successfully called.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -391,19 +382,19 @@ Sets other attributes of the UDPSocket connection. This API uses an asynchronous ...@@ -391,19 +382,19 @@ Sets other attributes of the UDPSocket connection. This API uses an asynchronous
```js ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
udp.bind({address:'192.168.xx.xxx', port:xxxx, family:1}, err=> { udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) { if (err) {
console.log('bind fail'); console.log('bind fail');
return; return;
} }
console.log('bind success'); console.log('bind success');
udp.setExtraOptions({ udp.setExtraOptions({
receiveBufferSize:1000, receiveBufferSize: 1000,
sendBufferSize:1000, sendBufferSize: 1000,
reuseAddress:false, reuseAddress: false,
socketTimeout:6000, socketTimeout: 6000,
broadcast:true broadcast: true
}, err=> { }, err => {
if (err) { if (err) {
console.log('setExtraOptions fail'); console.log('setExtraOptions fail');
return; return;
...@@ -413,15 +404,14 @@ udp.bind({address:'192.168.xx.xxx', port:xxxx, family:1}, err=> { ...@@ -413,15 +404,14 @@ udp.bind({address:'192.168.xx.xxx', port:xxxx, family:1}, err=> {
}) })
``` ```
### setExtraOptions ### setExtraOptions
setExtraOptions(options: UDPExtraOptions): Promise\<void\> setExtraOptions(options: UDPExtraOptions): Promise\<void\>
Sets other attributes of the UDPSocket connection. This API uses a promise to return the result. Sets other attributes of the UDPSocket connection. This API uses a promise to return the result.
>**NOTE** > **NOTE**
>This API can be called only after **bind** is successfully called. > This API can be called only after **bind** is successfully called.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -450,15 +440,15 @@ Sets other attributes of the UDPSocket connection. This API uses a promise to re ...@@ -450,15 +440,15 @@ Sets other attributes of the UDPSocket connection. This API uses a promise to re
```js ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
let promise = udp.bind({address:'192.168.xx.xxx', port:xxxx, family:1}); let promise = udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1});
promise.then(() => { promise.then(() => {
console.log('bind success'); console.log('bind success');
let promise1 = udp.setExtraOptions({ let promise1 = udp.setExtraOptions({
receiveBufferSize:1000, receiveBufferSize: 1000,
sendBufferSize:1000, sendBufferSize: 1000,
reuseAddress:false, reuseAddress: false,
socketTimeout:6000, socketTimeout: 6000,
broadcast:true broadcast: true
}); });
promise1.then(() => { promise1.then(() => {
console.log('setExtraOptions success'); console.log('setExtraOptions success');
...@@ -470,7 +460,6 @@ promise.then(() => { ...@@ -470,7 +460,6 @@ promise.then(() => {
}); });
``` ```
### on('message') ### on('message')
on(type: 'message', callback: Callback\<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void on(type: 'message', callback: Callback\<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void
...@@ -495,15 +484,14 @@ udp.on('message', value => { ...@@ -495,15 +484,14 @@ udp.on('message', value => {
}); });
``` ```
### off('message') ### off('message')
off(type: 'message', callback?: Callback\<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void off(type: 'message', callback?: Callback\<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void
Disables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result. Disables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE** > **NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. > 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
...@@ -518,7 +506,7 @@ Disables listening for message receiving events of the UDPSocket connection. Thi ...@@ -518,7 +506,7 @@ Disables listening for message receiving events of the UDPSocket connection. Thi
```js ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
let callback = value =>{ let callback = value => {
console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
} }
udp.on('message', callback); udp.on('message', callback);
...@@ -527,7 +515,6 @@ udp.off('message', callback); ...@@ -527,7 +515,6 @@ udp.off('message', callback);
udp.off('message'); udp.off('message');
``` ```
### on('listening' | 'close') ### on('listening' | 'close')
on(type: 'listening' | 'close', callback: Callback\<void\>): void on(type: 'listening' | 'close', callback: Callback\<void\>): void
...@@ -551,19 +538,18 @@ udp.on('listening', () => { ...@@ -551,19 +538,18 @@ udp.on('listening', () => {
console.log("on listening success"); console.log("on listening success");
}); });
udp.on('close', () => { udp.on('close', () => {
console.log("on close success" ); console.log("on close success");
}); });
``` ```
### off('listening' | 'close') ### off('listening' | 'close')
off(type: 'listening' | 'close', callback?: Callback\<void\>): void off(type: 'listening' | 'close', callback?: Callback\<void\>): void
Disables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result. Disables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE** > **NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. > 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
...@@ -578,14 +564,14 @@ Disables listening for data packet message events or close events of the UDPSock ...@@ -578,14 +564,14 @@ Disables listening for data packet message events or close events of the UDPSock
```js ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
let callback1 = () =>{ let callback1 = () => {
console.log("on listening, success"); console.log("on listening, success");
} }
udp.on('listening', callback1); udp.on('listening', callback1);
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. // You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
udp.off('listening', callback1); udp.off('listening', callback1);
udp.off('listening'); udp.off('listening');
let callback2 = () =>{ let callback2 = () => {
console.log("on close, success"); console.log("on close, success");
} }
udp.on('close', callback2); udp.on('close', callback2);
...@@ -594,7 +580,6 @@ udp.off('close', callback2); ...@@ -594,7 +580,6 @@ udp.off('close', callback2);
udp.off('close'); udp.off('close');
``` ```
### on('error') ### on('error')
on(type: 'error', callback: ErrorCallback): void on(type: 'error', callback: ErrorCallback): void
...@@ -619,15 +604,14 @@ udp.on('error', err => { ...@@ -619,15 +604,14 @@ udp.on('error', err => {
}); });
``` ```
### off('error') ### off('error')
off(type: 'error', callback?: ErrorCallback): void off(type: 'error', callback?: ErrorCallback): void
Disables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result. Disables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE** > **NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. > 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
...@@ -642,7 +626,7 @@ Disables listening for error events of the UDPSocket connection. This API uses a ...@@ -642,7 +626,7 @@ Disables listening for error events of the UDPSocket connection. This API uses a
```js ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
let callback = err =>{ let callback = err => {
console.log("on error, err:" + JSON.stringify(err)); console.log("on error, err:" + JSON.stringify(err));
} }
udp.on('error', callback); udp.on('error', callback);
...@@ -651,7 +635,6 @@ udp.off('error', callback); ...@@ -651,7 +635,6 @@ udp.off('error', callback);
udp.off('error'); udp.off('error');
``` ```
## NetAddress ## NetAddress
Defines the destination address. Defines the destination address.
...@@ -730,9 +713,9 @@ Creates a **TCPSocket** object. ...@@ -730,9 +713,9 @@ Creates a **TCPSocket** object.
**Return value** **Return value**
| Type | Description | | Type | Description |
| :--------------------------------- | :---------------------- | | :--------------------------------- | :---------------------- |
| [TCPSocket](#tcpsocket) | **TCPSocket** object.| | [TCPSocket](#tcpsocket) | **TCPSocket** object.|
**Example** **Example**
...@@ -740,7 +723,6 @@ Creates a **TCPSocket** object. ...@@ -740,7 +723,6 @@ Creates a **TCPSocket** object.
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
``` ```
## TCPSocket ## TCPSocket
Defines a TCPSocket connection. Before invoking TCPSocket APIs, you need to call [socket.constructTCPSocketInstance](#socketconstructtcpsocketinstance) to create a **TCPSocket** object. Defines a TCPSocket connection. Before invoking TCPSocket APIs, you need to call [socket.constructTCPSocketInstance](#socketconstructtcpsocketinstance) to create a **TCPSocket** object.
...@@ -782,7 +764,6 @@ tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { ...@@ -782,7 +764,6 @@ tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
}) })
``` ```
### bind ### bind
bind(address: NetAddress): Promise\<void\> bind(address: NetAddress): Promise\<void\>
...@@ -824,15 +805,14 @@ promise.then(() => { ...@@ -824,15 +805,14 @@ promise.then(() => {
}); });
``` ```
### connect ### connect
connect(options: TCPConnectOptions, callback: AsyncCallback\<void\>): void connect(options: TCPConnectOptions, callback: AsyncCallback\<void\>): void
Sets up a connection to the specified IP address and port number. This API uses an asynchronous callback to return the result. Sets up a connection to the specified IP address and port number. This API uses an asynchronous callback to return the result.
>**NOTE** > **NOTE**
>This API can be called only after **bind** is successfully called. > This API can be called only after **bind** is successfully called.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -856,7 +836,7 @@ Sets up a connection to the specified IP address and port number. This API uses ...@@ -856,7 +836,7 @@ Sets up a connection to the specified IP address and port number. This API uses
```js ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}, err => { tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}, err => {
if (err) { if (err) {
console.log('connect fail'); console.log('connect fail');
return; return;
...@@ -865,7 +845,6 @@ tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , time ...@@ -865,7 +845,6 @@ tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , time
}) })
``` ```
### connect ### connect
connect(options: TCPConnectOptions): Promise\<void\> connect(options: TCPConnectOptions): Promise\<void\>
...@@ -899,7 +878,7 @@ Sets up a connection to the specified IP address and port number. This API uses ...@@ -899,7 +878,7 @@ Sets up a connection to the specified IP address and port number. This API uses
```js ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); let promise = tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000});
promise.then(() => { promise.then(() => {
console.log('connect success') console.log('connect success')
}).catch(err => { }).catch(err => {
...@@ -907,15 +886,14 @@ promise.then(() => { ...@@ -907,15 +886,14 @@ promise.then(() => {
}); });
``` ```
### send ### send
send(options: TCPSendOptions, callback: AsyncCallback\<void\>): void send(options: TCPSendOptions, callback: AsyncCallback\<void\>): void
Sends data over a TCPSocket connection. This API uses an asynchronous callback to return the result. Sends data over a TCPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE** > **NOTE**
>This API can be called only after **connect** is successfully called. > This API can be called only after **connect** is successfully called.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -939,32 +917,29 @@ Sends data over a TCPSocket connection. This API uses an asynchronous callback t ...@@ -939,32 +917,29 @@ Sends data over a TCPSocket connection. This API uses an asynchronous callback t
```js ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}, () => {
promise.then(() => {
console.log('connect success'); console.log('connect success');
tcp.send({ tcp.send({
data:'Hello, server!' data: 'Hello, server!'
},err => { // Encoding is omitted here. The UTF-8 encoding format is used by default.
}, err => {
if (err) { if (err) {
console.log('send fail'); console.log('send fail');
return; return;
} }
console.log('send success'); console.log('send success');
}) })
}).catch(err => { })
console.log('connect fail');
});
``` ```
### send ### send
send(options: TCPSendOptions): Promise\<void\> send(options: TCPSendOptions): Promise\<void\>
Sends data over a TCPSocket connection. This API uses a promise to return the result. Sends data over a TCPSocket connection. This API uses a promise to return the result.
>**NOTE** > **NOTE**
>This API can be called only after **connect** is successfully called. > This API can be called only after **connect** is successfully called.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -993,11 +968,11 @@ Sends data over a TCPSocket connection. This API uses a promise to return the re ...@@ -993,11 +968,11 @@ Sends data over a TCPSocket connection. This API uses a promise to return the re
```js ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
let promise1 = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); let promise1 = tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000});
promise1.then(() => { promise1.then(() => {
console.log('connect success'); console.log('connect success');
let promise2 = tcp.send({ let promise2 = tcp.send({
data:'Hello, server!' data: 'Hello, server!'
}); });
promise2.then(() => { promise2.then(() => {
console.log('send success'); console.log('send success');
...@@ -1009,7 +984,6 @@ promise1.then(() => { ...@@ -1009,7 +984,6 @@ promise1.then(() => {
}); });
``` ```
### close ### close
close(callback: AsyncCallback\<void\>): void close(callback: AsyncCallback\<void\>): void
...@@ -1045,7 +1019,6 @@ tcp.close(err => { ...@@ -1045,7 +1019,6 @@ tcp.close(err => {
}) })
``` ```
### close ### close
close(): Promise\<void\> close(): Promise\<void\>
...@@ -1080,15 +1053,14 @@ promise.then(() => { ...@@ -1080,15 +1053,14 @@ promise.then(() => {
}); });
``` ```
### getRemoteAddress ### getRemoteAddress
getRemoteAddress(callback: AsyncCallback\<NetAddress\>): void getRemoteAddress(callback: AsyncCallback\<NetAddress\>): void
Obtains the remote address of a socket connection. This API uses an asynchronous callback to return the result. Obtains the remote address of a socket connection. This API uses an asynchronous callback to return the result.
>**NOTE** > **NOTE**
>This API can be called only after **connect** is successfully called. > This API can be called only after **connect** is successfully called.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -1110,8 +1082,7 @@ Obtains the remote address of a socket connection. This API uses an asynchronous ...@@ -1110,8 +1082,7 @@ Obtains the remote address of a socket connection. This API uses an asynchronous
```js ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}, () => {
promise.then(() => {
console.log('connect success'); console.log('connect success');
tcp.getRemoteAddress((err, data) => { tcp.getRemoteAddress((err, data) => {
if (err) { if (err) {
...@@ -1120,20 +1091,17 @@ promise.then(() => { ...@@ -1120,20 +1091,17 @@ promise.then(() => {
} }
console.log('getRemoteAddresssuccess:' + JSON.stringify(data)); console.log('getRemoteAddresssuccess:' + JSON.stringify(data));
}) })
}).catch(err => {
console.log('connect fail');
}); });
``` ```
### getRemoteAddress ### getRemoteAddress
getRemoteAddress(): Promise\<NetAddress\> getRemoteAddress(): Promise\<NetAddress\>
Obtains the remote address of a socket connection. This API uses a promise to return the result. Obtains the remote address of a socket connection. This API uses a promise to return the result.
>**NOTE** > **NOTE**
>This API can be called only after **connect** is successfully called. > This API can be called only after **connect** is successfully called.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -1155,7 +1123,7 @@ Obtains the remote address of a socket connection. This API uses a promise to re ...@@ -1155,7 +1123,7 @@ Obtains the remote address of a socket connection. This API uses a promise to re
```js ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
let promise1 = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); let promise1 = tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000});
promise1.then(() => { promise1.then(() => {
console.log('connect success'); console.log('connect success');
let promise2 = tcp.getRemoteAddress(); let promise2 = tcp.getRemoteAddress();
...@@ -1169,15 +1137,14 @@ promise1.then(() => { ...@@ -1169,15 +1137,14 @@ promise1.then(() => {
}); });
``` ```
### getState ### getState
getState(callback: AsyncCallback\<SocketStateBase\>): void getState(callback: AsyncCallback\<SocketStateBase\>): void
Obtains the status of the TCPSocket connection. This API uses an asynchronous callback to return the result. Obtains the status of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE** > **NOTE**
>This API can be called only after **bind** or **connect** is successfully called. > This API can be called only after **bind** or **connect** is successfully called.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -1199,8 +1166,7 @@ Obtains the status of the TCPSocket connection. This API uses an asynchronous ca ...@@ -1199,8 +1166,7 @@ Obtains the status of the TCPSocket connection. This API uses an asynchronous ca
```js ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); let promise = tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}, () => {
promise.then(() => {
console.log('connect success'); console.log('connect success');
tcp.getState((err, data) => { tcp.getState((err, data) => {
if (err) { if (err) {
...@@ -1209,20 +1175,17 @@ promise.then(() => { ...@@ -1209,20 +1175,17 @@ promise.then(() => {
} }
console.log('getState success:' + JSON.stringify(data)); console.log('getState success:' + JSON.stringify(data));
}); });
}).catch(err => {
console.log('connect fail');
}); });
``` ```
### getState ### getState
getState(): Promise\<SocketStateBase\> getState(): Promise\<SocketStateBase\>
Obtains the status of the TCPSocket connection. This API uses a promise to return the result. Obtains the status of the TCPSocket connection. This API uses a promise to return the result.
>**NOTE** > **NOTE**
>This API can be called only after **bind** or **connect** is successfully called. > This API can be called only after **bind** or **connect** is successfully called.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -1244,7 +1207,7 @@ Obtains the status of the TCPSocket connection. This API uses a promise to retur ...@@ -1244,7 +1207,7 @@ Obtains the status of the TCPSocket connection. This API uses a promise to retur
```js ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); let promise = tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000});
promise.then(() => { promise.then(() => {
console.log('connect success'); console.log('connect success');
let promise1 = tcp.getState(); let promise1 = tcp.getState();
...@@ -1258,15 +1221,14 @@ promise.then(() => { ...@@ -1258,15 +1221,14 @@ promise.then(() => {
}); });
``` ```
### setExtraOptions ### setExtraOptions
setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\<void\>): void setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\<void\>): void
Sets other properties of the TCPSocket connection. This API uses an asynchronous callback to return the result. Sets other properties of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE** > **NOTE**
>This API can be called only after **bind** or **connect** is successfully called. > This API can be called only after **bind** or **connect** is successfully called.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -1290,39 +1252,35 @@ Sets other properties of the TCPSocket connection. This API uses an asynchronous ...@@ -1290,39 +1252,35 @@ Sets other properties of the TCPSocket connection. This API uses an asynchronous
```js ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); let promise = tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}, () => {
promise.then(() => {
console.log('connect success'); console.log('connect success');
tcp.setExtraOptions({ tcp.setExtraOptions({
keepAlive: true, keepAlive: true,
OOBInline: true, OOBInline: true,
TCPNoDelay: true, TCPNoDelay: true,
socketLinger: { on:true, linger:10 }, socketLinger: {on: true, linger: 10},
receiveBufferSize: 1000, receiveBufferSize: 1000,
sendBufferSize: 1000, sendBufferSize: 1000,
reuseAddress: true, reuseAddress: true,
socketTimeout: 3000, socketTimeout: 3000,
},err => { }, err => {
if (err) { if (err) {
console.log('setExtraOptions fail'); console.log('setExtraOptions fail');
return; return;
} }
console.log('setExtraOptions success'); console.log('setExtraOptions success');
}); });
}).catch(err => {
console.log('connect fail');
}); });
``` ```
### setExtraOptions ### setExtraOptions
setExtraOptions(options: TCPExtraOptions): Promise\<void\> setExtraOptions(options: TCPExtraOptions): Promise\<void\>
Sets other properties of the TCPSocket connection. This API uses a promise to return the result. Sets other properties of the TCPSocket connection. This API uses a promise to return the result.
>**NOTE** > **NOTE**
>This API can be called only after **bind** or **connect** is successfully called. > This API can be called only after **bind** or **connect** is successfully called.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -1351,14 +1309,14 @@ Sets other properties of the TCPSocket connection. This API uses a promise to re ...@@ -1351,14 +1309,14 @@ Sets other properties of the TCPSocket connection. This API uses a promise to re
```js ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); let promise = tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000});
promise.then(() => { promise.then(() => {
console.log('connect success'); console.log('connect success');
let promise1 = tcp.setExtraOptions({ let promise1 = tcp.setExtraOptions({
keepAlive: true, keepAlive: true,
OOBInline: true, OOBInline: true,
TCPNoDelay: true, TCPNoDelay: true,
socketLinger: { on:true, linger:10 }, socketLinger: {on: true, linger: 10},
receiveBufferSize: 1000, receiveBufferSize: 1000,
sendBufferSize: 1000, sendBufferSize: 1000,
reuseAddress: true, reuseAddress: true,
...@@ -1374,7 +1332,6 @@ promise.then(() => { ...@@ -1374,7 +1332,6 @@ promise.then(() => {
}); });
``` ```
### on('message') ### on('message')
on(type: 'message', callback: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void on(type: 'message', callback: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void
...@@ -1399,15 +1356,14 @@ tcp.on('message', value => { ...@@ -1399,15 +1356,14 @@ tcp.on('message', value => {
}); });
``` ```
### off('message') ### off('message')
off(type: 'message', callback?: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void off(type: 'message', callback?: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void
Disables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result. Disables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE** > **NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. > 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
...@@ -1422,7 +1378,7 @@ Disables listening for message receiving events of the TCPSocket connection. Thi ...@@ -1422,7 +1378,7 @@ Disables listening for message receiving events of the TCPSocket connection. Thi
```js ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
let callback = value =>{ let callback = value => {
console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
} }
tcp.on('message', callback); tcp.on('message', callback);
...@@ -1431,7 +1387,6 @@ tcp.off('message', callback); ...@@ -1431,7 +1387,6 @@ tcp.off('message', callback);
tcp.off('message'); tcp.off('message');
``` ```
### on('connect' | 'close') ### on('connect' | 'close')
on(type: 'connect' | 'close', callback: Callback\<void\>): void on(type: 'connect' | 'close', callback: Callback\<void\>): void
...@@ -1459,15 +1414,14 @@ tcp.on('close', data => { ...@@ -1459,15 +1414,14 @@ tcp.on('close', data => {
}); });
``` ```
### off('connect' | 'close') ### off('connect' | 'close')
off(type: 'connect' | 'close', callback?: Callback\<void\>): void off(type: 'connect' | 'close', callback?: Callback\<void\>): void
Disables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result. Disables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE** > **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
...@@ -1482,14 +1436,14 @@ Disables listening for connection or close events of the TCPSocket connection. T ...@@ -1482,14 +1436,14 @@ Disables listening for connection or close events of the TCPSocket connection. T
```js ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
let callback1 = () =>{ let callback1 = () => {
console.log("on connect success"); console.log("on connect success");
} }
tcp.on('connect', callback1); tcp.on('connect', callback1);
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. // You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
tcp.off('connect', callback1); tcp.off('connect', callback1);
tcp.off('connect'); tcp.off('connect');
let callback2 = () =>{ let callback2 = () => {
console.log("on close success"); console.log("on close success");
} }
tcp.on('close', callback2); tcp.on('close', callback2);
...@@ -1498,7 +1452,6 @@ tcp.off('close', callback2); ...@@ -1498,7 +1452,6 @@ tcp.off('close', callback2);
tcp.off('close'); tcp.off('close');
``` ```
### on('error') ### on('error')
on(type: 'error', callback: ErrorCallback): void on(type: 'error', callback: ErrorCallback): void
...@@ -1523,15 +1476,14 @@ tcp.on('error', err => { ...@@ -1523,15 +1476,14 @@ tcp.on('error', err => {
}); });
``` ```
### off('error') ### off('error')
off(type: 'error', callback?: ErrorCallback): void off(type: 'error', callback?: ErrorCallback): void
Disables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result. Disables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE** > **NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. > 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
...@@ -1546,7 +1498,7 @@ Disables listening for error events of the TCPSocket connection. This API uses a ...@@ -1546,7 +1498,7 @@ Disables listening for error events of the TCPSocket connection. This API uses a
```js ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
let callback = err =>{ let callback = err => {
console.log("on error, err:" + JSON.stringify(err)); console.log("on error, err:" + JSON.stringify(err));
} }
tcp.on('error', callback); tcp.on('error', callback);
...@@ -1555,7 +1507,6 @@ tcp.off('error', callback); ...@@ -1555,7 +1507,6 @@ tcp.off('error', callback);
tcp.off('error'); tcp.off('error');
``` ```
## TCPConnectOptions ## TCPConnectOptions
Defines TCPSocket connection parameters. Defines TCPSocket connection parameters.
...@@ -1769,12 +1720,11 @@ Obtains the status of the TLSSocket connection. This API uses a promise to retur ...@@ -1769,12 +1720,11 @@ Obtains the status of the TLSSocket connection. This API uses a promise to retur
**Example** **Example**
```js ```js
tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { let promiseBind = tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1});
if (err) { promiseBind.then(() => {
console.log('bind fail');
return;
}
console.log('bind success'); console.log('bind success');
}).catch((err) => {
console.log('bind fail');
}); });
let promise = tls.getState(); let promise = tls.getState();
promise.then(() => { promise.then(() => {
...@@ -1822,18 +1772,19 @@ tls.setExtraOptions({ ...@@ -1822,18 +1772,19 @@ tls.setExtraOptions({
keepAlive: true, keepAlive: true,
OOBInline: true, OOBInline: true,
TCPNoDelay: true, TCPNoDelay: true,
socketLinger: { on:true, linger:10 }, socketLinger: {on: true, linger: 10},
receiveBufferSize: 1000, receiveBufferSize: 1000,
sendBufferSize: 1000, sendBufferSize: 1000,
reuseAddress: true, reuseAddress: true,
socketTimeout: 3000, socketTimeout: 3000,
},err => { }, err => {
if (err) { if (err) {
console.log('setExtraOptions fail'); console.log('setExtraOptions fail');
return; return;
} }
console.log('setExtraOptions success'); console.log('setExtraOptions success');
}); });
``` ```
### setExtraOptions<sup>9+</sup> ### setExtraOptions<sup>9+</sup>
...@@ -1878,7 +1829,7 @@ let promise = tls.setExtraOptions({ ...@@ -1878,7 +1829,7 @@ let promise = tls.setExtraOptions({
keepAlive: true, keepAlive: true,
OOBInline: true, OOBInline: true,
TCPNoDelay: true, TCPNoDelay: true,
socketLinger: { on:true, linger:10 }, socketLinger: {on: true, linger: 10},
receiveBufferSize: 1000, receiveBufferSize: 1000,
sendBufferSize: 1000, sendBufferSize: 1000,
reuseAddress: true, reuseAddress: true,
...@@ -1956,12 +1907,12 @@ let options = { ...@@ -1956,12 +1907,12 @@ let options = {
}, },
}; };
tlsTwoWay.connect(options, (err, data) => { tlsTwoWay.connect(options, (err, data) => {
console.error("connect callback error"+err); console.error("connect callback error" + err);
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
tlsOneWay.bind({address: '192.168.xxx.xxx', port: 8080, family: 1}, err => { tlsOneWay.bind({address: '192.168.xxx.xxx', port: 8080, family: 1}, err => {
if (err) { if (err) {
console.log('bind fail'); console.log('bind fail');
return; return;
...@@ -1975,12 +1926,12 @@ let oneWayOptions = { ...@@ -1975,12 +1926,12 @@ let oneWayOptions = {
family: 1, family: 1,
}, },
secureOptions: { secureOptions: {
ca: ["xxxx","xxxx"], ca: ["xxxx", "xxxx"],
cipherSuite: "AES256-SHA256", cipherSuite: "AES256-SHA256",
}, },
}; };
tlsOneWay.connect(oneWayOptions, (err, data) => { tlsOneWay.connect(oneWayOptions, (err, data) => {
console.error("connect callback error"+err); console.error("connect callback error" + err);
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -2075,7 +2026,7 @@ let oneWayOptions = { ...@@ -2075,7 +2026,7 @@ let oneWayOptions = {
family: 1, family: 1,
}, },
secureOptions: { secureOptions: {
ca: ["xxxx","xxxx"], ca: ["xxxx", "xxxx"],
cipherSuite: "AES256-SHA256", cipherSuite: "AES256-SHA256",
}, },
}; };
...@@ -2551,7 +2502,7 @@ Sends a message to the server after a TLSSocket connection is established. This ...@@ -2551,7 +2502,7 @@ Sends a message to the server after a TLSSocket connection is established. This
**Example** **Example**
```js ```js
tls.send("xxxx").then(() =>{ tls.send("xxxx").then(() => {
console.log("send success"); console.log("send success");
}).catch(err => { }).catch(err => {
console.error(err); console.error(err);
...@@ -2619,7 +2570,7 @@ Closes a TLSSocket connection. This API uses a promise to return the result. ...@@ -2619,7 +2570,7 @@ Closes a TLSSocket connection. This API uses a promise to return the result.
**Example** **Example**
```js ```js
tls.close().then(() =>{ tls.close().then(() => {
console.log("close success"); console.log("close success");
}).catch(err => { }).catch(err => {
console.error(err); console.error(err);
......
# UI Appearance # @ohos.uiAppearance (UI Appearance)
The **uiAppearance** module provides basic capabilities for managing the system appearance. It allows for color mode configuration currently, and will introduce more features over time. The **uiAppearance** module provides basic capabilities for managing the system appearance. It allows for color mode configuration currently, and will introduce more features over time.
......
...@@ -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,9 +22,13 @@ import webSocket from '@ohos.net.webSocket'; ...@@ -21,9 +22,13 @@ 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) => {
if (err != undefined) {
console.log(JSON.stringify(err))
return
}
console.log("on open, status:" + value['status'] + ", message:" + value['message']); console.log("on open, status:" + value['status'] + ", message:" + value['message']);
// When receiving the on('open') event, the client can use the send() API to communicate with the server. // When receiving the on('open') event, the client can use the send() API to communicate with the server.
ws.send("Hello, server!", (err, value) => { ws.send("Hello, server!", (err, value) => {
...@@ -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
...@@ -125,13 +132,15 @@ ws.connect(url, (err, value) => { ...@@ -125,13 +132,15 @@ ws.connect(url, (err, value) => {
}); });
``` ```
### 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
...@@ -170,13 +179,15 @@ ws.connect(url, { ...@@ -170,13 +179,15 @@ ws.connect(url, {
}); });
``` ```
### 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
...@@ -214,7 +225,6 @@ promise.then((value) => { ...@@ -214,7 +225,6 @@ promise.then((value) => {
}); });
``` ```
### send ### send
send(data: string | ArrayBuffer, callback: AsyncCallback\<boolean\>): void send(data: string | ArrayBuffer, callback: AsyncCallback\<boolean\>): void
...@@ -255,7 +265,6 @@ ws.connect(url, (err, value) => { ...@@ -255,7 +265,6 @@ ws.connect(url, (err, value) => {
}); });
``` ```
### send ### send
send(data: string | ArrayBuffer): Promise\<boolean\> send(data: string | ArrayBuffer): Promise\<boolean\>
...@@ -300,7 +309,6 @@ ws.connect(url, (err, value) => { ...@@ -300,7 +309,6 @@ ws.connect(url, (err, value) => {
}); });
``` ```
### close ### close
close(callback: AsyncCallback\<boolean\>): void close(callback: AsyncCallback\<boolean\>): void
...@@ -328,7 +336,6 @@ Closes a WebSocket connection. This API uses an asynchronous callback to return ...@@ -328,7 +336,6 @@ 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")
...@@ -338,7 +345,6 @@ ws.close((err, value) => { ...@@ -338,7 +345,6 @@ ws.close((err, value) => {
}); });
``` ```
### close ### close
close(options: WebSocketCloseOptions, callback: AsyncCallback\<boolean\>): void close(options: WebSocketCloseOptions, callback: AsyncCallback\<boolean\>): void
...@@ -367,7 +373,6 @@ Closes a WebSocket connection carrying specified options such as **code** and ** ...@@ -367,7 +373,6 @@ 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"
...@@ -380,7 +385,6 @@ ws.close({ ...@@ -380,7 +385,6 @@ ws.close({
}); });
``` ```
### close ### close
close(options?: WebSocketCloseOptions): Promise\<boolean\> close(options?: WebSocketCloseOptions): Promise\<boolean\>
...@@ -414,7 +418,6 @@ Closes a WebSocket connection carrying specified options such as **code** and ** ...@@ -414,7 +418,6 @@ 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"
...@@ -426,7 +429,6 @@ promise.then((value) => { ...@@ -426,7 +429,6 @@ promise.then((value) => {
}); });
``` ```
### on('open') ### on('open')
on(type: 'open', callback: AsyncCallback\<Object\>): void on(type: 'open', callback: AsyncCallback\<Object\>): void
...@@ -442,7 +444,6 @@ Enables listening for the **open** events of a WebSocket connection. This API us ...@@ -442,7 +444,6 @@ 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
...@@ -452,15 +453,14 @@ ws.on('open', (err, value) => { ...@@ -452,15 +453,14 @@ ws.on('open', (err, value) => {
}); });
``` ```
### 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
...@@ -483,15 +483,14 @@ ws.on('open', callback1); ...@@ -483,15 +483,14 @@ ws.on('open', callback1);
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
...@@ -511,16 +510,15 @@ ws.on('message', (err, value) => { ...@@ -511,16 +510,15 @@ ws.on('message', (err, 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
...@@ -563,15 +560,14 @@ ws.on('close', (err, value) => { ...@@ -563,15 +560,14 @@ ws.on('close', (err, value) => {
}); });
``` ```
### 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,7 +598,7 @@ Enables listening for the **error** events of a WebSocket connection. This API u ...@@ -603,7 +598,7 @@ 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**
...@@ -614,15 +609,14 @@ ws.on('error', (err) => { ...@@ -614,15 +609,14 @@ ws.on('error', (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.
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册