提交 8540c6b1 编写于 作者: S shawn_he

update doc

Signed-off-by: Nshawn_he <shawn.he@huawei.com>
上级 30241b2b
# Fault Logger # Fault Logger
> **NOTE**<br/> > **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.
......
# HiAppEvent # HiAppEvent
This module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration. The HiAppEvent module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration.
> **NOTE** > **NOTE**
> - The APIs provided by this module are deprecated since API version 9. You are advised to use [`@ohos.hiviewdfx.hiAppEvent`](js-apis-hiviewdfx-hiappevent.md) instead. > - The APIs provided by this module are deprecated since API version 9. You are advised to use [`@ohos.hiviewdfx.hiAppEvent`](js-apis-hiviewdfx-hiappevent.md) instead.
......
# HiDebug # HiDebug
> **NOTE** > **NOTE**
>
> 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.
This 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. 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
...@@ -24,7 +25,7 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. ...@@ -24,7 +25,7 @@ This API is defined but not implemented in OpenHarmony 3.1 Release.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | --------------------------- | | ------ | --------------------------- |
| bigint | Total heap memory size of the application, in KB.| | bigint | Total heap memory size of the application, in KB.|
......
...@@ -45,7 +45,7 @@ Enumerates the log levels. ...@@ -45,7 +45,7 @@ Enumerates the log levels.
**System capability**: SystemCapability.HiviewDFX.HiLog **System capability**: SystemCapability.HiviewDFX.HiLog
| Name | Default Value| Description | | Name | Value| Description |
| ----- | ------ | ------------------------------------------------------------ | | ----- | ------ | ------------------------------------------------------------ |
| DEBUG | 3 | Log level used to record more detailed process information than INFO logs to help developers analyze service processes and locate faults.| | DEBUG | 3 | Log level used to record more detailed process information than INFO logs to help developers analyze service processes and locate faults.|
| INFO | 4 | Log level used to record key service process nodes and exceptions that occur during service running,<br>for example, no network signal or login failure.<br>These logs should be recorded by the dominant module in the service to avoid repeated logging conducted by multiple invoked modules or low-level functions.| | INFO | 4 | Log level used to record key service process nodes and exceptions that occur during service running,<br>for example, no network signal or login failure.<br>These logs should be recorded by the dominant module in the service to avoid repeated logging conducted by multiple invoked modules or low-level functions.|
......
...@@ -18,9 +18,9 @@ import http from '@ohos.net.http'; ...@@ -18,9 +18,9 @@ import http from '@ohos.net.http';
```js ```js
import http from '@ohos.net.http'; import http from '@ohos.net.http';
// Each HttpRequest corresponds to an HttpRequestTask object and cannot be reused. // Each httpRequest corresponds to an HTTP request task and cannot be reused.
let httpRequest = http.createHttp(); let httpRequest = http.createHttp();
// Subscribe to the HTTP response header, which is returned earlier than httpRequest. Whether to subscribe to the HTTP response header is up to your decision. // This API is used to listen for the HTTP Response Header event, which is returned earlier than the result of the HTTP request. It is up to you whether to listen for HTTP Response Header events.
// on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8. // on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8.
httpRequest.on('headersReceive', (header) => { httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header)); console.info('header: ' + JSON.stringify(header));
...@@ -38,14 +38,18 @@ httpRequest.request( ...@@ -38,14 +38,18 @@ httpRequest.request(
extraData: { extraData: {
"data": "data to send", "data": "data to send",
}, },
connectTimeout: 60000, // Optional. The default value is 60000, in ms. expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data.
usingCache: true, // Optional. The default value is true.
priority: 1, // Optional. The default value is 1.
connectTimeout: 60000 // Optional. The default value is 60000, in ms.
readTimeout: 60000, // Optional. The default value is 60000, in ms. readTimeout: 60000, // Optional. The default value is 60000, in ms.
usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system.
}, (err, data) => { }, (err, data) => {
if (!err) { if (!err) {
// data.result contains the HTTP response. Parse the response based on service requirements. // data.result carries the HTTP response. Parse the response based on service requirements.
console.info('Result:' + data.result); console.info('Result:' + data.result);
console.info('code:' + data.responseCode); console.info('code:' + data.responseCode);
// data.header contains the HTTP response header. Parse the content based on service requirements. // data.header carries the HTTP response header. Parse the content based on service requirements.
console.info('header:' + JSON.stringify(data.header)); console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + data.cookies); // 8+ console.info('cookies:' + data.cookies); // 8+
} else { } else {
...@@ -78,10 +82,9 @@ import http from '@ohos.net.http'; ...@@ -78,10 +82,9 @@ import http from '@ohos.net.http';
let httpRequest = http.createHttp(); let httpRequest = http.createHttp();
``` ```
## HttpRequest ## HttpRequest
HTTP request task. Before invoking APIs provided by **HttpRequest**, you must call [createHttp\(\)](#httpcreatehttp) to create an **HttpRequestTask** object. Defines an HTTP request task. Before invoking APIs provided by **HttpRequest**, you must call [createHttp\(\)](#httpcreatehttp) to create an **HttpRequestTask** object.
### request ### request
...@@ -89,7 +92,7 @@ request\(url: string, callback: AsyncCallback\<HttpResponse\>\):void ...@@ -89,7 +92,7 @@ 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.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -121,7 +124,7 @@ request\(url: string, options: HttpRequestOptions, callback: AsyncCallback<HttpR ...@@ -121,7 +124,7 @@ 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.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -158,14 +161,13 @@ httpRequest.request("EXAMPLE_URL", ...@@ -158,14 +161,13 @@ httpRequest.request("EXAMPLE_URL",
}); });
``` ```
### request ### request
request\(url: string, options? : HttpRequestOptions\): Promise<HttpResponse\> request\(url: string, options? : HttpRequestOptions\): Promise<HttpResponse\>
Initiates an HTTP request to a given URL. This API uses a promise to return the result. Initiates an HTTP request to a given URL. This API uses a promise to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -174,7 +176,7 @@ Initiates an HTTP request to a given URL. This API uses a promise to return the ...@@ -174,7 +176,7 @@ Initiates an HTTP request to a given URL. This API uses a promise to return the
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ------------------ | ---- | ----------------------------------------------- | | ------- | ------------------ | ---- | ----------------------------------------------- |
| url | string | Yes | URL for initiating an HTTP request. | | url | string | Yes | URL for initiating an HTTP request. |
| options | HttpRequestOptions | Yes | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| | options | HttpRequestOptions | No | Request options. For details, see [HttpRequestOptions](#httprequestoptions).|
**Return value** **Return value**
...@@ -226,7 +228,7 @@ on\(type: 'headerReceive', callback: AsyncCallback<Object\>\): void ...@@ -226,7 +228,7 @@ on\(type: 'headerReceive', callback: AsyncCallback<Object\>\): void
Registers an observer for HTTP Response Header events. Registers an observer for HTTP Response Header events.
>![](public_sys-resources/icon-note.gif) **NOTE** >**NOTE**
>This API has been deprecated. You are advised to use [on\('headersReceive'\)<sup>8+</sup>](#onheadersreceive8) instead. >This API has been deprecated. You are advised to use [on\('headersReceive'\)<sup>8+</sup>](#onheadersreceive8) instead.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -250,14 +252,13 @@ httpRequest.on('headerReceive', (err, data) => { ...@@ -250,14 +252,13 @@ httpRequest.on('headerReceive', (err, data) => {
}); });
``` ```
### off\('headerReceive'\) ### off\('headerReceive'\)
off\(type: 'headerReceive', callback?: AsyncCallback<Object\>\): void off\(type: 'headerReceive', callback?: AsyncCallback<Object\>\): void
Unregisters the observer for HTTP Response Header events. Unregisters the observer for HTTP Response Header events.
>![](public_sys-resources/icon-note.gif) **NOTE** >**NOTE**
> >
>1. This API has been deprecated. You are advised to use [off\('headersReceive'\)<sup>8+</sup>](#offheadersreceive8) instead. >1. This API has been deprecated. You are advised to use [off\('headersReceive'\)<sup>8+</sup>](#offheadersreceive8) instead.
> >
...@@ -301,14 +302,13 @@ httpRequest.on('headersReceive', (header) => { ...@@ -301,14 +302,13 @@ httpRequest.on('headersReceive', (header) => {
}); });
``` ```
### off\('headersReceive'\)<sup>8+</sup> ### off\('headersReceive'\)<sup>8+</sup>
off\(type: 'headersReceive', callback?: Callback<Object\>\): void off\(type: 'headersReceive', callback?: Callback<Object\>\): void
Unregisters the observer for HTTP Response Header events. Unregisters the observer for HTTP Response Header events.
>![](public_sys-resources/icon-note.gif) **NOTE** >**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. >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
...@@ -358,10 +358,14 @@ Specifies the type and value range of the optional parameters in the HTTP reques ...@@ -358,10 +358,14 @@ 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. |
| 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>8+</sup> | | 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> |
| 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.|
| 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**. |
| 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. |
| usingProtocol<sup>9+</sup> | [HttpProtocol](#httpprotocol9) | No | Protocol. The default value is automatically specified by the system. |
## RequestMethod ## RequestMethod
...@@ -371,14 +375,14 @@ Defines an HTTP request method. ...@@ -371,14 +375,14 @@ Defines an HTTP request method.
| Name | Value | Description | | Name | Value | Description |
| :------ | ------- | :------------------ | | :------ | ------- | :------------------ |
| OPTIONS | OPTIONS | OPTIONS method.| | OPTIONS | "OPTIONS" | OPTIONS method.|
| GET | GET | GET method. | | GET | "GET" | GET method. |
| HEAD | HEAD | HEAD method. | | HEAD | "HEAD" | HEAD method. |
| POST | POST | POST method. | | POST | "POST" | POST method. |
| PUT | PUT | PUT method. | | PUT | "PUT" | PUT method. |
| DELETE | DELETE | DELETE method. | | DELETE | "DELETE" | DELETE method. |
| TRACE | TRACE | TRACE method. | | TRACE | "TRACE" | TRACE method. |
| CONNECT | CONNECT | CONNECT method.| | CONNECT | "CONNECT" | CONNECT method.|
## ResponseCode ## ResponseCode
...@@ -388,7 +392,7 @@ Enumerates the response codes for an HTTP request. ...@@ -388,7 +392,7 @@ Enumerates the response codes for an HTTP request.
| Name | Value | Description | | Name | Value | Description |
| ----------------- | ---- | ------------------------------------------------------------ | | ----------------- | ---- | ------------------------------------------------------------ |
| OK | 200 | Request succeeded. The request has been processed successfully. This return code is generally used for GET and POST requests. | | OK | 200 | The request is successful. The request has been processed successfully. This return code is generally used for GET and POST requests. |
| CREATED | 201 | "Created." The request has been successfully sent and a new resource is created. | | CREATED | 201 | "Created." The request has been successfully sent and a new resource is created. |
| ACCEPTED | 202 | "Accepted." The request has been accepted, but the processing has not been completed. | | ACCEPTED | 202 | "Accepted." The request has been accepted, but the processing has not been completed. |
| NOT_AUTHORITATIVE | 203 | "Non-Authoritative Information." The request is successful. | | NOT_AUTHORITATIVE | 203 | "Non-Authoritative Information." The request is successful. |
...@@ -433,17 +437,171 @@ Defines the response to an HTTP request. ...@@ -433,17 +437,171 @@ 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 \| Object \| ArrayBuffer<sup>6+</sup> | Yes | Response content returned based on **Content-type** in the response header:<br>- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.<br>- application/octet-stream: ArrayBuffer<br>- Others: string|
| resultType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | Yes | Type of the return value. |
| responseCode | [ResponseCode](#responsecode) \| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**. For details, see [Error Codes](#error-codes).| | responseCode | [ResponseCode](#responsecode) \| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**. For details, see [Error Codes](#error-codes).|
| header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:<br>- Content-Type: header['Content-Type'];<br>- Status-Line: header['Status-Line'];<br>- Date: header.Date/header['Date'];<br>- Server: header.Server/header['Server'];| | header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:<br>- Content-Type: header['Content-Type'];<br>- Status-Line: header['Status-Line'];<br>- Date: header.Date/header['Date'];<br>- Server: header.Server/header['Server'];|
| cookies<sup>8+</sup> | Array\<string\> | Yes | Cookies returned by the server. | | cookies<sup>8+</sup> | Array\<string\> | Yes | Cookies returned by the server. |
## http.createHttpResponseCache<sup>9+</sup>
createHttpResponseCache(cacheSize?: number): HttpResponseCache
Creates a default object to store responses to HTTP access requests.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| cacheSize | number | No| Cache size. The maximum value is 10\*1024\*1024 (10 MB). By default, the maximum value is used.|
**Return value**
| Type | Description |
| :---------- | :----------------------------------------------------------- |
| [HttpResponseCache](#httpresponsecache9) | Object that stores the response to the HTTP request.|
**Example**
```js
import http from '@ohos.net.http';
let httpResponseCache = http.createHttpResponseCache();
```
## HttpResponseCache<sup>9+</sup>
Defines an object that stores the response to an HTTP request.
### flush<sup>9+</sup>
flush(callback: AsyncCallback\<void>): void
Flushes data in the cache to the file system so that the cached data can be accessed in the next HTTP request. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Example**
```js
httpResponseCache.flush(err => {
if (err) {
console.log('flush fail');
return;
}
console.log('flush success');
});
```
### flush<sup>9+</sup>
flush(): Promise\<void>
Flushes data in the cache to the file system so that the cached data can be accessed in the next HTTP request. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<void>> | Promise used to return the result.|
**Example**
```js
httpResponseCache.flush().then(() => {
console.log('flush success');
}).catch(err => {
console.log('flush fail');
});
```
### delete<sup>9+</sup>
delete(callback: AsyncCallback\<void>): void
Disables the cache and deletes the data in it. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Example**
```js
httpResponseCache.delete(err => {
if (err) {
console.log('delete fail');
return;
}
console.log('delete success');
});
```
### delete<sup>9+</sup>
delete(): Promise\<void>
Disables the cache and deletes the data in it. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result.|
**Example**
```js
httpResponseCache.delete().then(() => {
console.log('delete success');
}).catch(err => {
console.log('delete fail');
});
```
## Error Codes ## Error Codes
| Error Code| Description | | Error Code| Description |
| ------ | ------------------------------------------------------------ | | ------ | ------------------------------------------------------------ |
| -1 | Incorrect parameters. | | -1 | Incorrect parameter. Check whether the number and type of parameters are correct. |
| 3 | Incorrect URL format. | | 3 | Incorrect URL format. Check whether the format and syntax of the URL are correct. |
| 4 | Built-in request function, protocol, or option not found during build. | | 4 | Built-in request function, protocol, or option not found during build. If a function or option is not enabled or explicitly disabled, you need to rebuild a libcurl in order to access its functions. |
| 5 | Unable to resolve the proxy. | | 5 | Unable to resolve the proxy because of a failure to resolve the specified proxy server. You are advised perform the following: 1. Check whether the URL is correct. 2. Check whether the network connection is normal and whether the network can communicate with external networks. 3. Check whether the network access permission is available. |
| 6 | Unable to resolve the host. | | 6 | Unable to resolve the host because of a failure to resolve the specified remote host. You are advised perform the following: 1. Check whether the URL is correct. 2. Check whether the network connection is normal and whether the network can communicate with external networks. 3. Check whether the network access permission is available. |
| 7 | Unable to connect to the proxy or host. | | 7 | Unable to connect to the proxy or host. You are advised perform the following: 1. Check whether the port number is correct. 2. Check whether the HTTP proxy is enabled on the local host. |
## HttpDataType<sup>9+</sup>
Enumerates HTTP data types.
**System capability**: SystemCapability.Communication.NetStack
| Name| Value| Description |
| ------------------ | -- | ----------- |
| STRING | 0 | String type.|
| OBJECT | 1 | Object type. |
| ARRAY_BUFFER | 2 | Binary array type.|
## HttpProtocol<sup>9+</sup>
Enumerates HTTP protocol versions.
**System capability**: SystemCapability.Communication.NetStack
| Name | Description |
| :-------- | :----------- |
| HTTP1_1 | HTTP1.1 |
| HTTP2 | HTTP2 |
# Socket Connection # Socket Connection
>![](public_sys-resources/icon-note.gif) **NOTE:** > **NOTE**
>
>The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> >
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
``` ```js
import socket from '@ohos.net.socket'; import socket from '@ohos.net.socket';
``` ```
...@@ -19,7 +18,7 @@ Creates a **UDPSocket** object. ...@@ -19,7 +18,7 @@ Creates a **UDPSocket** object.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------------------- | :---------------------- | | :--------------------------------- | :---------------------- |
...@@ -28,7 +27,7 @@ Creates a **UDPSocket** object. ...@@ -28,7 +27,7 @@ Creates a **UDPSocket** object.
**Example** **Example**
``` ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
``` ```
...@@ -43,7 +42,7 @@ bind\(address: NetAddress, callback: AsyncCallback<void\>\): void ...@@ -43,7 +42,7 @@ bind\(address: NetAddress, callback: AsyncCallback<void\>\): void
Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result. Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -56,7 +55,7 @@ Binds the IP address and port number. The port number can be specified or random ...@@ -56,7 +55,7 @@ Binds the IP address and port number. The port number can be specified or random
**Example** **Example**
``` ```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) {
...@@ -74,7 +73,7 @@ bind\(address: NetAddress\): Promise<void\> ...@@ -74,7 +73,7 @@ bind\(address: NetAddress\): Promise<void\>
Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result. Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -85,7 +84,7 @@ Binds the IP address and port number. The port number can be specified or random ...@@ -85,7 +84,7 @@ Binds the IP address and port number. The port number can be specified or random
| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| | address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------- | :----------------------------------------- | | :-------------- | :----------------------------------------- |
...@@ -93,7 +92,7 @@ Binds the IP address and port number. The port number can be specified or random ...@@ -93,7 +92,7 @@ Binds the IP address and port number. The port number can be specified or random
**Example** **Example**
``` ```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(() => {
...@@ -112,7 +111,7 @@ Sends data over a UDPSocket connection. This API uses an asynchronous callback t ...@@ -112,7 +111,7 @@ Sends data over a UDPSocket connection. This API uses an asynchronous callback t
Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and port. Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and port.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -125,7 +124,7 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p ...@@ -125,7 +124,7 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p
**Example** **Example**
``` ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
udp.send({ udp.send({
data:'Hello, server!', data:'Hello, server!',
...@@ -152,7 +151,7 @@ Sends data over a UDPSocket connection. This API uses a promise to return the re ...@@ -152,7 +151,7 @@ Sends data over a UDPSocket connection. This API uses a promise to return the re
Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and port. Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and port.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -162,7 +161,7 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p ...@@ -162,7 +161,7 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p
| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | | ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).| | options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------- | :--------------------------------------------- | | :-------------- | :--------------------------------------------- |
...@@ -170,7 +169,7 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p ...@@ -170,7 +169,7 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p
**Example** **Example**
``` ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
let promise = udp.send({ let promise = udp.send({
data:'Hello, server!', data:'Hello, server!',
...@@ -194,7 +193,7 @@ close\(callback: AsyncCallback<void\>\): void ...@@ -194,7 +193,7 @@ close\(callback: AsyncCallback<void\>\): void
Closes a UDPSocket connection. This API uses an asynchronous callback to return the result. Closes a UDPSocket connection. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -206,7 +205,7 @@ Closes a UDPSocket connection. This API uses an asynchronous callback to return ...@@ -206,7 +205,7 @@ Closes a UDPSocket connection. This API uses an asynchronous callback to return
**Example** **Example**
``` ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
udp.close(err => { udp.close(err => {
if (err) { if (err) {
...@@ -224,11 +223,11 @@ close\(\): Promise<void\> ...@@ -224,11 +223,11 @@ close\(\): Promise<void\>
Closes a UDPSocket connection. This API uses a promise to return the result. Closes a UDPSocket connection. This API uses a promise to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------- | :----------------------------------------- | | :-------------- | :----------------------------------------- |
...@@ -236,7 +235,7 @@ Closes a UDPSocket connection. This API uses a promise to return the result. ...@@ -236,7 +235,7 @@ Closes a UDPSocket connection. This API uses a promise to return the result.
**Example** **Example**
``` ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
let promise = udp.close(); let promise = udp.close();
promise.then(() => { promise.then(() => {
...@@ -253,10 +252,10 @@ getState\(callback: AsyncCallback<SocketStateBase\>\): void ...@@ -253,10 +252,10 @@ 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.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>This API can be called only after [bind](#bind) is successfully called. >This API can be called only after [bind](#bind) is successfully called.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -268,7 +267,7 @@ Obtains the status of the UDPSocket connection. This API uses an asynchronous ca ...@@ -268,7 +267,7 @@ Obtains the status of the UDPSocket connection. This API uses an asynchronous ca
**Example** **Example**
``` ```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) {
...@@ -293,14 +292,14 @@ getState\(\): Promise<SocketStateBase\> ...@@ -293,14 +292,14 @@ 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.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>This API can be called only after [bind](#bind) is successfully called. >This API can be called only after [bind](#bind) is successfully called.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :----------------------------------------------- | :----------------------------------------- | | :----------------------------------------------- | :----------------------------------------- |
...@@ -308,7 +307,7 @@ Obtains the status of the UDPSocket connection. This API uses a promise to retur ...@@ -308,7 +307,7 @@ Obtains the status of the UDPSocket connection. This API uses a promise to retur
**Example** **Example**
``` ```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) {
...@@ -332,10 +331,10 @@ setExtraOptions\(options: UDPExtraOptions, callback: AsyncCallback<void\>\): voi ...@@ -332,10 +331,10 @@ setExtraOptions\(options: UDPExtraOptions, callback: AsyncCallback<void\>\): voi
Sets other properties of the UDPSocket connection. This API uses an asynchronous callback to return the result. Sets other properties of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>This API can be called only after [bind](#bind) is successfully called. >This API can be called only after [bind](#bind) is successfully called.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -349,7 +348,7 @@ Sets other properties of the UDPSocket connection. This API uses an asynchronous ...@@ -349,7 +348,7 @@ Sets other properties of the UDPSocket connection. This API uses an asynchronous
**Example** **Example**
``` ```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) {
...@@ -380,10 +379,10 @@ setExtraOptions\(options: UDPExtraOptions\): Promise<void\> ...@@ -380,10 +379,10 @@ setExtraOptions\(options: UDPExtraOptions\): Promise<void\>
Sets other properties of the UDPSocket connection. This API uses a promise to return the result. Sets other properties of the UDPSocket connection. This API uses a promise to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>This API can be called only after [bind](#bind) is successfully called. >This API can be called only after [bind](#bind) is successfully called.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -393,7 +392,7 @@ Sets other properties of the UDPSocket connection. This API uses a promise to re ...@@ -393,7 +392,7 @@ Sets other properties of the UDPSocket connection. This API uses a promise to re
| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | | ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [UDPExtraOptions](#udpextraoptions) | Yes | Other properties of the UDPSocket connection. For details, see [UDPExtraOptions](#udpextraoptions).| | options | [UDPExtraOptions](#udpextraoptions) | Yes | Other properties of the UDPSocket connection. For details, see [UDPExtraOptions](#udpextraoptions).|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------- | :--------------------------------------------------- | | :-------------- | :--------------------------------------------------- |
...@@ -401,7 +400,7 @@ Sets other properties of the UDPSocket connection. This API uses a promise to re ...@@ -401,7 +400,7 @@ Sets other properties of the UDPSocket connection. This API uses a promise to re
**Example** **Example**
``` ```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(() => {
...@@ -436,12 +435,12 @@ Enables listening for message receiving events of the UDPSocket connection. This ...@@ -436,12 +435,12 @@ Enables listening for message receiving events of the UDPSocket connection. This
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | Yes | Event type. <br />**message**: message receiving event| | type | string | Yes | Type of the event to subscribe to.<br /> **message**: message receiving event|
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | Yes | Callback used to return the result. | | callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | Yes | Callback used to return the result. |
**Example** **Example**
``` ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
udp.on('message', value => { udp.on('message', value => {
console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
...@@ -455,7 +454,7 @@ off\(type: 'message', callback?: Callback<\{message: ArrayBuffer, remoteInfo: So ...@@ -455,7 +454,7 @@ off\(type: 'message', callback?: Callback<\{message: ArrayBuffer, remoteInfo: So
Disables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result. Disables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. >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
...@@ -464,18 +463,18 @@ Disables listening for message receiving events of the UDPSocket connection. Thi ...@@ -464,18 +463,18 @@ Disables listening for message receiving events of the UDPSocket connection. Thi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | Yes | Event type. <br />**message**: message receiving event| | type | string | Yes | Type of the event to subscribe to.<br /> **message**: message receiving event|
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No | Callback used to return the result. | | callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No | Callback used to return the result. |
**Example** **Example**
``` ```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);
// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. // You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
udp.off('message', callback); udp.off('message', callback);
udp.off('message'); udp.off('message');
``` ```
...@@ -493,12 +492,12 @@ Enables listening for data packet message events or close events of the UDPSocke ...@@ -493,12 +492,12 @@ Enables listening for data packet message events or close events of the UDPSocke
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------------- | ---- | ------------------------------------------------------------ | | -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type.<br>- **listening**: data packet message event<br>- **close**: close event| | type | string | Yes | Type of the event to subscribe to.<br /><br>- **listening**: data packet message event<br>- **close**: close event|
| callback | Callback\<void\> | Yes | Callback used to return the result. | | callback | Callback\<void\> | Yes | Callback used to return the result. |
**Example** **Example**
``` ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
udp.on('listening', () => { udp.on('listening', () => {
console.log("on listening success"); console.log("on listening success");
...@@ -515,7 +514,7 @@ off\(type: 'listening' | 'close', callback?: Callback<void\>\): void ...@@ -515,7 +514,7 @@ 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.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. >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
...@@ -524,25 +523,25 @@ Disables listening for data packet message events or close events of the UDPSock ...@@ -524,25 +523,25 @@ Disables listening for data packet message events or close events of the UDPSock
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------------- | ---- | ------------------------------------------------------------ | | -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type.<br>- **listening**: data packet message event<br>- **close**: close event| | type | string | Yes | Type of the event to subscribe to.<br>- **listening**: data packet message event<br>- **close**: close event|
| callback | Callback\<void\> | No | Callback used to return the result. | | callback | Callback\<void\> | No | Callback used to return the result. |
**Example** **Example**
``` ```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 function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. // You can pass the **callback** of the **on** 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);
// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. // You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
udp.off('close', callback2); udp.off('close', callback2);
udp.off('close'); udp.off('close');
``` ```
...@@ -560,13 +559,13 @@ Enables listening for error events of the UDPSocket connection. This API uses an ...@@ -560,13 +559,13 @@ Enables listening for error events of the UDPSocket connection. This API uses an
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------------ | | -------- | ------------- | ---- | ------------------------------------ |
| type | string | Yes | Event type. <br />**error**: error event| | type | string | Yes | Type of the event to subscribe to.<br /> **error**: error event|
| callback | ErrorCallback | Yes | Callback used to return the result. | | callback | ErrorCallback | Yes | Callback used to return the result. |
**Example** **Example**
``` ```js
let udp = socket.constructUDPSocketInstance(); let udp = socket.constructUDPSocketInstance();
udp.on('error', err => { udp.on('error', err => {
console.log("on error, err:" + JSON.stringify(err)) console.log("on error, err:" + JSON.stringify(err))
...@@ -580,7 +579,7 @@ off\(type: 'error', callback?: ErrorCallback\): void ...@@ -580,7 +579,7 @@ off\(type: 'error', callback?: ErrorCallback\): void
Disables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result. Disables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. >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,18 +588,18 @@ Disables listening for error events of the UDPSocket connection. This API uses a ...@@ -589,18 +588,18 @@ Disables listening for error events of the UDPSocket connection. This API uses a
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------------ | | -------- | ------------- | ---- | ------------------------------------ |
| type | string | Yes | Event type. <br />**error**: error event| | type | string | Yes | Type of the event to subscribe to.<br /> **error**: error event|
| callback | ErrorCallback | No | Callback used to return the result. | | callback | ErrorCallback | No | Callback used to return the result. |
**Example** **Example**
``` ```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);
// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. // You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
udp.off('error', callback); udp.off('error', callback);
udp.off('error'); udp.off('error');
``` ```
...@@ -626,7 +625,7 @@ Defines the parameters for sending data over the UDPSocket connection. ...@@ -626,7 +625,7 @@ Defines the parameters for sending data over the UDPSocket connection.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ---------------------------------- | ---- | -------------- | | ------- | ---------------------------------- | ---- | -------------- |
| data | string \| ArrayBuffer<sup>7+</sup> | Yes | Data to send. | | data | string \| ArrayBuffer<sup>7+</sup> | Yes | Data to send. |
| address | [NetAddress](#netaddress) | Yes | Destination address.| | address | [NetAddress](#netaddress) | Yes | Destination address.|
## UDPExtraOptions ## UDPExtraOptions
...@@ -645,7 +644,7 @@ Defines other properties of the UDPSocket connection. ...@@ -645,7 +644,7 @@ Defines other properties of the UDPSocket connection.
## SocketStateBase ## SocketStateBase
Defines the status of the UDPSocket connection. Defines the status of the socket connection.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -657,7 +656,7 @@ Defines the status of the UDPSocket connection. ...@@ -657,7 +656,7 @@ Defines the status of the UDPSocket connection.
## SocketRemoteInfo ## SocketRemoteInfo
Defines information about the UDPSocket connection. Defines information about the socket connection.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -676,7 +675,7 @@ Creates a **TCPSocket** object. ...@@ -676,7 +675,7 @@ Creates a **TCPSocket** object.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------------------- | :---------------------- | | :--------------------------------- | :---------------------- |
...@@ -684,7 +683,7 @@ Creates a **TCPSocket** object. ...@@ -684,7 +683,7 @@ Creates a **TCPSocket** object.
**Example** **Example**
``` ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
``` ```
...@@ -699,7 +698,7 @@ bind\(address: NetAddress, callback: AsyncCallback<void\>\): void ...@@ -699,7 +698,7 @@ bind\(address: NetAddress, callback: AsyncCallback<void\>\): void
Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result. Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -713,7 +712,7 @@ Binds the IP address and port number. The port number can be specified or random ...@@ -713,7 +712,7 @@ Binds the IP address and port number. The port number can be specified or random
**Example** **Example**
``` ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) { if (err) {
...@@ -731,7 +730,7 @@ bind\(address: NetAddress\): Promise<void\> ...@@ -731,7 +730,7 @@ bind\(address: NetAddress\): Promise<void\>
Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result. Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -741,7 +740,7 @@ Binds the IP address and port number. The port number can be specified or random ...@@ -741,7 +740,7 @@ Binds the IP address and port number. The port number can be specified or random
| ------- | ---------------------------------- | ---- | ------------------------------------------------------ | | ------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| | address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------- | :------------------------------------------------------- | | :-------------- | :------------------------------------------------------- |
...@@ -749,7 +748,7 @@ Binds the IP address and port number. The port number can be specified or random ...@@ -749,7 +748,7 @@ Binds the IP address and port number. The port number can be specified or random
**Example** **Example**
``` ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
let promise = tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}); let promise = tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1});
promise.then(() => { promise.then(() => {
...@@ -766,7 +765,7 @@ connect\(options: TCPConnectOptions, callback: AsyncCallback<void\>\): void ...@@ -766,7 +765,7 @@ 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.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -779,7 +778,7 @@ Sets up a connection to the specified IP address and port number. This API uses ...@@ -779,7 +778,7 @@ Sets up a connection to the specified IP address and port number. This API uses
**Example** **Example**
``` ```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) {
...@@ -797,7 +796,7 @@ connect\(options: TCPConnectOptions\): Promise<void\> ...@@ -797,7 +796,7 @@ connect\(options: TCPConnectOptions\): Promise<void\>
Sets up a connection to the specified IP address and port number. This API uses a promise to return the result. Sets up a connection to the specified IP address and port number. This API uses a promise to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -807,7 +806,7 @@ Sets up a connection to the specified IP address and port number. This API uses ...@@ -807,7 +806,7 @@ Sets up a connection to the specified IP address and port number. This API uses
| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | | ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPConnectOptions](#tcpconnectoptions) | Yes | TCPSocket connection parameters. For details, see [TCPConnectOptions](#tcpconnectoptions).| | options | [TCPConnectOptions](#tcpconnectoptions) | Yes | TCPSocket connection parameters. For details, see [TCPConnectOptions](#tcpconnectoptions).|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------- | :--------------------------------------------------------- | | :-------------- | :--------------------------------------------------------- |
...@@ -815,7 +814,7 @@ Sets up a connection to the specified IP address and port number. This API uses ...@@ -815,7 +814,7 @@ Sets up a connection to the specified IP address and port number. This API uses
**Example** **Example**
``` ```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(() => {
...@@ -832,10 +831,10 @@ send\(options: TCPSendOptions, callback: AsyncCallback<void\>\): void ...@@ -832,10 +831,10 @@ 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.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>This API can be called only after [connect](#connect) is successfully called. >This API can be called only after [connect](#connect) is successfully called.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -848,7 +847,7 @@ Sends data over a TCPSocket connection. This API uses an asynchronous callback t ...@@ -848,7 +847,7 @@ Sends data over a TCPSocket connection. This API uses an asynchronous callback t
**Example** **Example**
``` ```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(() => {
...@@ -874,10 +873,10 @@ send\(options: TCPSendOptions\): Promise<void\> ...@@ -874,10 +873,10 @@ 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.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>This API can be called only after [connect](#connect) is successfully called. >This API can be called only after [connect](#connect) is successfully called.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -887,7 +886,7 @@ Sends data over a TCPSocket connection. This API uses a promise to return the re ...@@ -887,7 +886,7 @@ Sends data over a TCPSocket connection. This API uses a promise to return the re
| ------- | --------------------------------------- | ---- | ------------------------------------------------------------ | | ------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPSendOptions](#tcpsendoptions) | Yes | Parameters for sending data over the TCPSocket connection. For details, see [TCPSendOptions](#tcpsendoptions).| | options | [TCPSendOptions](#tcpsendoptions) | Yes | Parameters for sending data over the TCPSocket connection. For details, see [TCPSendOptions](#tcpsendoptions).|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------- | :------------------------------------------------- | | :-------------- | :------------------------------------------------- |
...@@ -895,7 +894,7 @@ Sends data over a TCPSocket connection. This API uses a promise to return the re ...@@ -895,7 +894,7 @@ Sends data over a TCPSocket connection. This API uses a promise to return the re
**Example** **Example**
``` ```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(() => {
...@@ -920,7 +919,7 @@ close\(callback: AsyncCallback<void\>\): void ...@@ -920,7 +919,7 @@ close\(callback: AsyncCallback<void\>\): void
Closes a TCPSocket connection. This API uses an asynchronous callback to return the result. Closes a TCPSocket connection. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -933,7 +932,7 @@ Closes a TCPSocket connection. This API uses an asynchronous callback to return ...@@ -933,7 +932,7 @@ Closes a TCPSocket connection. This API uses an asynchronous callback to return
**Example** **Example**
``` ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
tcp.close(err => { tcp.close(err => {
if (err) { if (err) {
...@@ -951,11 +950,11 @@ close\(\): Promise<void\> ...@@ -951,11 +950,11 @@ close\(\): Promise<void\>
Closes a TCPSocket connection. This API uses a promise to return the result. Closes a TCPSocket connection. This API uses a promise to return the result.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------- | :----------------------------------------- | | :-------------- | :----------------------------------------- |
...@@ -963,7 +962,7 @@ Closes a TCPSocket connection. This API uses a promise to return the result. ...@@ -963,7 +962,7 @@ Closes a TCPSocket connection. This API uses a promise to return the result.
**Example** **Example**
``` ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
let promise = tcp.close(); let promise = tcp.close();
promise.then(() => { promise.then(() => {
...@@ -978,12 +977,12 @@ promise.then(() => { ...@@ -978,12 +977,12 @@ promise.then(() => {
getRemoteAddress\(callback: AsyncCallback<NetAddress\>\): void getRemoteAddress\(callback: AsyncCallback<NetAddress\>\): void
Obtains the remote address of a TCPSocket 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.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>This API can be called only after [connect](#connect) is successfully called. >This API can be called only after [connect](#connect) is successfully called.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -995,7 +994,7 @@ Obtains the remote address of a TCPSocket connection. This API uses an asynchron ...@@ -995,7 +994,7 @@ Obtains the remote address of a TCPSocket connection. This API uses an asynchron
**Example** **Example**
``` ```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(() => {
...@@ -1017,16 +1016,16 @@ promise.then(() => { ...@@ -1017,16 +1016,16 @@ promise.then(() => {
getRemoteAddress\(\): Promise<NetAddress\> getRemoteAddress\(\): Promise<NetAddress\>
Obtains the remote address of a TCPSocket 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.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>This API can be called only after [connect](#connect) is successfully called. >This API can be called only after [connect](#connect) is successfully called.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :------------------------------------------ | :------------------------------------------ | | :------------------------------------------ | :------------------------------------------ |
...@@ -1034,7 +1033,7 @@ Obtains the remote address of a TCPSocket connection. This API uses a promise to ...@@ -1034,7 +1033,7 @@ Obtains the remote address of a TCPSocket connection. This API uses a promise to
**Example** **Example**
``` ```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(() => {
...@@ -1057,10 +1056,10 @@ getState\(callback: AsyncCallback<SocketStateBase\>\): void ...@@ -1057,10 +1056,10 @@ 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.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. >This API can be called only after [bind](#bind) or [connect](#connect) is successfully called.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -1073,7 +1072,7 @@ Obtains the status of the TCPSocket connection. This API uses an asynchronous ca ...@@ -1073,7 +1072,7 @@ Obtains the status of the TCPSocket connection. This API uses an asynchronous ca
**Example** **Example**
``` ```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(() => {
...@@ -1097,14 +1096,14 @@ getState\(\): Promise<SocketStateBase\> ...@@ -1097,14 +1096,14 @@ 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.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. >This API can be called only after [bind](#bind) or [connect](#connect) is successfully called.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :----------------------------------------------- | :----------------------------------------- | | :----------------------------------------------- | :----------------------------------------- |
...@@ -1113,7 +1112,7 @@ Obtains the status of the TCPSocket connection. This API uses a promise to retur ...@@ -1113,7 +1112,7 @@ Obtains the status of the TCPSocket connection. This API uses a promise to retur
**Example** **Example**
``` ```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(() => {
...@@ -1136,10 +1135,10 @@ setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback<void\>\): voi ...@@ -1136,10 +1135,10 @@ setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback<void\>\): voi
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.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. >This API can be called only after [bind](#bind) or [connect](#connect) is successfully called.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -1152,7 +1151,7 @@ Sets other properties of the TCPSocket connection. This API uses an asynchronous ...@@ -1152,7 +1151,7 @@ Sets other properties of the TCPSocket connection. This API uses an asynchronous
**Example** **Example**
``` ```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(() => {
...@@ -1185,10 +1184,10 @@ setExtraOptions\(options: TCPExtraOptions\): Promise<void\> ...@@ -1185,10 +1184,10 @@ 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.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. >This API can be called only after [bind](#bind) or [connect](#connect) is successfully called.
**Required permission**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -1198,7 +1197,7 @@ Sets other properties of the TCPSocket connection. This API uses a promise to re ...@@ -1198,7 +1197,7 @@ Sets other properties of the TCPSocket connection. This API uses a promise to re
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).| | options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------- | :--------------------------------------------------- | | :-------------- | :--------------------------------------------------- |
...@@ -1207,7 +1206,7 @@ Sets other properties of the TCPSocket connection. This API uses a promise to re ...@@ -1207,7 +1206,7 @@ Sets other properties of the TCPSocket connection. This API uses a promise to re
**Example** **Example**
``` ```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(() => {
...@@ -1245,12 +1244,12 @@ Enables listening for message receiving events of the TCPSocket connection. This ...@@ -1245,12 +1244,12 @@ Enables listening for message receiving events of the TCPSocket connection. This
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | Yes | Event type. <br />**message**: message receiving event| | type | string | Yes | Type of the event to subscribe to.<br /> **message**: message receiving event|
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | Yes | Callback used to return the result. | | callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | Yes | Callback used to return the result. |
**Example** **Example**
``` ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
tcp.on('message', value => { tcp.on('message', value => {
console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo) console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo)
...@@ -1264,7 +1263,7 @@ off\(type: 'message', callback?: Callback<\{message: ArrayBuffer, remoteInfo: So ...@@ -1264,7 +1263,7 @@ off\(type: 'message', callback?: Callback<\{message: ArrayBuffer, remoteInfo: So
Disables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result. Disables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. >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
...@@ -1273,18 +1272,18 @@ Disables listening for message receiving events of the TCPSocket connection. Thi ...@@ -1273,18 +1272,18 @@ Disables listening for message receiving events of the TCPSocket connection. Thi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | Yes | Event type. <br />**message**: message receiving event| | type | string | Yes | Type of the event to subscribe to.<br /> **message**: message receiving event|
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No | Callback used to return the result. | | callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No | Callback used to return the result. |
**Example** **Example**
``` ```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);
// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. // You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
tcp.off('message', callback); tcp.off('message', callback);
tcp.off('message'); tcp.off('message');
``` ```
...@@ -1302,13 +1301,13 @@ Enables listening for connection or close events of the TCPSocket connection. Th ...@@ -1302,13 +1301,13 @@ Enables listening for connection or close events of the TCPSocket connection. Th
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------------- | ---- | ------------------------------------------------------------ | | -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type.<br>- **connect**: connection event<br>- **close**: close event| | type | string | Yes | Type of the event to subscribe to.<br /><br>- **connect**: connection event<br>- **close**: close event|
| callback | Callback\<void\> | Yes | Callback used to return the result. | | callback | Callback\<void\> | Yes | Callback used to return the result. |
**Example** **Example**
``` ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
tcp.on('connect', () => { tcp.on('connect', () => {
console.log("on connect success") console.log("on connect success")
...@@ -1325,7 +1324,7 @@ off\(type: 'connect' | 'close', callback?: Callback<void\>\): void ...@@ -1325,7 +1324,7 @@ 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.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. >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
...@@ -1334,25 +1333,25 @@ Disables listening for connection or close events of the TCPSocket connection. T ...@@ -1334,25 +1333,25 @@ Disables listening for connection or close events of the TCPSocket connection. T
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------------- | ---- | ------------------------------------------------------------ | | -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type.<br>- **connect**: connection event<br>- **close**: close event| | type | string | Yes | Type of the event to subscribe to.<br /><br>- **connect**: connection event<br>- **close**: close event|
| callback | Callback\<void\> | No | Callback used to return the result. | | callback | Callback\<void\> | No | Callback used to return the result. |
**Example** **Example**
``` ```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 function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. // You can pass the **callback** of the **on** 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);
// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. // You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
tcp.off('close', callback2); tcp.off('close', callback2);
tcp.off('close'); tcp.off('close');
``` ```
...@@ -1370,12 +1369,12 @@ Enables listening for error events of the TCPSocket connection. This API uses an ...@@ -1370,12 +1369,12 @@ Enables listening for error events of the TCPSocket connection. This API uses an
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------------ | | -------- | ------------- | ---- | ------------------------------------ |
| type | string | Yes | Event type. <br />**error**: error event| | type | string | Yes | Type of the event to subscribe to.<br /> **error**: error event|
| callback | ErrorCallback | Yes | Callback used to return the result. | | callback | ErrorCallback | Yes | Callback used to return the result. |
**Example** **Example**
``` ```js
let tcp = socket.constructTCPSocketInstance(); let tcp = socket.constructTCPSocketInstance();
tcp.on('error', err => { tcp.on('error', err => {
console.log("on error, err:" + JSON.stringify(err)) console.log("on error, err:" + JSON.stringify(err))
...@@ -1389,7 +1388,7 @@ off\(type: 'error', callback?: ErrorCallback\): void ...@@ -1389,7 +1388,7 @@ off\(type: 'error', callback?: ErrorCallback\): void
Disables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result. Disables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:** >**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. >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
...@@ -1398,18 +1397,18 @@ Disables listening for error events of the TCPSocket connection. This API uses a ...@@ -1398,18 +1397,18 @@ Disables listening for error events of the TCPSocket connection. This API uses a
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------------ | | -------- | ------------- | ---- | ------------------------------------ |
| type | string | Yes | Event type. <br />**error**: error event| | type | string | Yes | Type of the event to subscribe to.<br /> **error**: error event|
| callback | ErrorCallback | No | Callback used to return the result. | | callback | ErrorCallback | No | Callback used to return the result. |
**Example** **Example**
``` ```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);
// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. // You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
tcp.off('error', callback); tcp.off('error', callback);
tcp.off('error'); tcp.off('error');
``` ```
...@@ -1434,7 +1433,7 @@ Defines the parameters for sending data over the TCPSocket connection. ...@@ -1434,7 +1433,7 @@ Defines the parameters for sending data over the TCPSocket connection.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ | | -------- | ------ | ---- | ------------------------------------------------------------ |
| data | string\| ArrayBuffer<sup>7+</sup> | Yes | Data to send. | | data | string\| ArrayBuffer<sup>7+</sup> | Yes | Data to send. |
| encoding | string | No | Character encoding format. The options are as follows: **UTF-8**, **UTF-16BE**, **UTF-16LE**, **UTF-16**, **US-AECII**, and **ISO-8859-1**. The default value is **UTF-8**.| | encoding | string | No | Character encoding format. The options are as follows: **UTF-8**, **UTF-16BE**, **UTF-16LE**, **UTF-16**, **US-AECII**, and **ISO-8859-1**. The default value is **UTF-8**.|
## TCPExtraOptions ## TCPExtraOptions
...@@ -1453,3 +1452,1080 @@ Defines other properties of the TCPSocket connection. ...@@ -1453,3 +1452,1080 @@ Defines other properties of the TCPSocket connection.
| sendBufferSize | number | No | Size of the send buffer, in bytes. | | sendBufferSize | number | No | Size of the send buffer, in bytes. |
| reuseAddress | boolean | No | Whether to reuse addresses. The default value is **false**. | | reuseAddress | boolean | No | Whether to reuse addresses. The default value is **false**. |
| socketTimeout | number | No | Timeout duration of the TCPSocket connection, in ms. | | socketTimeout | number | No | Timeout duration of the TCPSocket connection, in ms. |
## socket.constructTLSSocketInstance<sup>9+</sup>
constructTLSSocketInstance(): TLSSocket
Creates a **TLSSocket** object.
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| :--------------------------------- | :---------------------- |
| [TLSSocket](#tlssocket9) | **TLSSocket** object.|
**Example**
```js
let tls = socket.constructTLSSocketInstance();
```
## TLSSocket<sup>9+</sup>
Defines a TLSSocket connection. Before invoking TLSSocket APIs, you need to call [socket.constructTLSSocketInstance](#socketconstructtlssocketinstance9) to create a **TLSSocket** object.
### bind<sup>9+</sup>
bind\(address: NetAddress, callback: AsyncCallback<void\>\): void
Binds the IP address and port number. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation is successful, the result of binding the local IP address and port number is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2303198 | Address already in use. |
| 2300002 | System internal error. |
**Example**
```js
tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
```
### bind<sup>9+</sup>
bind\(address: NetAddress\): Promise<void\>
Binds the IP address and port number. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).|
**Return value**
| Type | Description |
| :-------------- | :------------------------------------------------------- |
| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2303198 | Address already in use. |
| 2300002 | System internal error. |
**Example**
```js
let promise = tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1});
promise.then(() => {
console.log('bind success');
}).catch(err => {
console.log('bind fail');
});
```
### getState<sup>9+</sup>
getState\(callback: AsyncCallback<SocketStateBase\>\): void
Obtains the status of the TLSSocket connection. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------ | ---- | ---------- |
| callback | AsyncCallback\<[SocketStateBase](#socketstatebase)> | Yes | Callback used to return the result. If the operation is successful, the status of the TLSSocket connection is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ------------------------------ |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**Example**
```js
let promise = tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
tls.getState((err, data) => {
if (err) {
console.log('getState fail');
return;
}
console.log('getState success:' + JSON.stringify(data));
});
```
### getState<sup>9+</sup>
getState\(\): Promise<SocketStateBase\>
Obtains the status of the TLSSocket connection. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| :----------------------------------------------- | :----------------------------------------- |
| Promise\<[SocketStateBase](#socketstatebase)> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ------------------------------ |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**Example**
```js
tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let promise = tls.getState();
promise.then(() => {
console.log('getState success');
}).catch(err => {
console.log('getState fail');
});
```
### setExtraOptions<sup>9+</sup>
setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback<void\>\): void
Sets other properties of the TCPSocket connection after successful binding of the local IP address and port number of the TLSSocket connection. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation is successful, the result of setting other properties of the TCPSocket connection is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 401 | Parameter error. |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**Example**
```js
tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
tls.setExtraOptions({
keepAlive: true,
OOBInline: true,
TCPNoDelay: true,
socketLinger: { on:true, linger:10 },
receiveBufferSize: 1000,
sendBufferSize: 1000,
reuseAddress: true,
socketTimeout: 3000,
},err => {
if (err) {
console.log('setExtraOptions fail');
return;
}
console.log('setExtraOptions success');
});
```
### setExtraOptions<sup>9+</sup>
setExtraOptions\(options: TCPExtraOptions\): Promise<void\>
Sets other properties of the TCPSocket connection after successful binding of the local IP address and port number of the TLSSocket connection. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).|
**Return value**
| Type | Description |
| :-------------- | :--------------------------------------------------- |
| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ------------------------------ |
| 401 | Parameter error. |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**Example**
```js
tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let promise = tls.setExtraOptions({
keepAlive: true,
OOBInline: true,
TCPNoDelay: true,
socketLinger: { on:true, linger:10 },
receiveBufferSize: 1000,
sendBufferSize: 1000,
reuseAddress: true,
socketTimeout: 3000,
});
promise.then(() => {
console.log('setExtraOptions success');
}).catch(err => {
console.log('setExtraOptions fail');
});
```
### connect<sup>9+</sup>
connect(options: TLSConnectOptions, callback: AsyncCallback\<void>): void
Sets up a TLSSocket connection, and creates and initializes a TLS session after successful binding of the local IP address and port number of the TLSSocket connection. During this process, a TLS/SSL handshake is performed between the application and the server to implement data transmission. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description|
| -------- | ---------------------------------------| ----| --------------- |
| options | [TLSConnectOptions](#tlsconnectoptions9) | Yes | Parameters required for the TLSSocket connection.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 401 | Parameter error. |
| 2303104 | Interrupted system call. |
| 2303109 | Bad file number. |
| 2303111 | Resource temporarily unavailable try again. |
| 2303113 | System permission denied. |
| 2303188 | Socket operation on non-socket. |
| 2303191 | Protocol wrong type for socket. |
| 2303198 | Address already in use. |
| 2303199 | Cannot assign requested address. |
| 2303210 | Connection timed out. |
| 2303501 | SSL is null. |
| 2303502 | Error in tls reading. |
| 2303503 | Error in tls writing |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**Example**
```js
let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let options = {
ALPNProtocols: ["spdy/1", "http/1.1"],
address: {
address: "192.168.xx.xxx",
port: xxxx,
family: 1,
},
secureOptions: {
key: "xxxx",
cert: "xxxx",
ca: ["xxxx"],
passwd: "xxxx",
protocols: [socket.Protocol.TLSv12],
useRemoteCipherPrefer: true,
signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
cipherSuite: "AES256-SHA256",
},
};
tlsTwoWay.connect(options, (err, data) => {
console.error(err);
console.log(data);
});
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let oneWayOptions = {
address: {
address: "192.168.xxx.xxx",
port: xxxx,
family: 1,
},
secureOptions: {
ca: ["xxxx","xxxx"],
cipherSuite: "AES256-SHA256",
},
};
tlsOneWay.connect(oneWayOptions, (err, data) => {
console.error(err);
console.log(data);
});
```
### connect<sup>9+</sup>
connect(options: TLSConnectOptions): Promise\<void>
Sets up a TLSSocket connection, and creates and initializes a TLS session after successful binding of the local IP address and port number of the TLSSocket connection. During this process, a TLS/SSL handshake is performed between the application and the server to implement data transmission. Both two-way and one-way authentication modes are supported. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description|
| -------- | --------------------------------------| ----| --------------- |
| options | [TLSConnectOptions](#tlsconnectoptions9) | Yes | Parameters required for the connection.|
**Return value**
| Type | Description |
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 401 | Parameter error. |
| 2303104 | Interrupted system call. |
| 2303109 | Bad file number. |
| 2303111 | Resource temporarily unavailable try again. |
| 2303113 | System permission denied. |
| 2303188 | Socket operation on non-socket. |
| 2303191 | Protocol wrong type for socket. |
| 2303198 | Address already in use. |
| 2303199 | Cannot assign requested address. |
| 2303210 | Connection timed out. |
| 2303501 | SSL is null. |
| 2303502 | Error in tls reading. |
| 2303503 | Error in tls writing |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**Example**
```js
let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let options = {
ALPNProtocols: ["spdy/1", "http/1.1"],
address: {
address: "xxxx",
port: xxxx,
family: 1,
},
secureOptions: {
key: "xxxx",
cert: "xxxx",
ca: ["xxxx"],
passwd: "xxxx",
protocols: [socket.Protocol.TLSv12],
useRemoteCipherPrefer: true,
signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
cipherSuite: "AES256-SHA256",
},
};
tlsTwoWay.connect(options).then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let oneWayOptions = {
address: {
address: "192.168.xxx.xxx",
port: xxxx,
family: 1,
},
secureOptions: {
ca: ["xxxx","xxxx"],
cipherSuite: "AES256-SHA256",
},
};
tlsOneWay.connect(oneWayOptions).then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getRemoteAddress<sup>9+</sup>
getRemoteAddress\(callback: AsyncCallback<NetAddress\>\): void
Obtains the remote address of a TLSSocket connection. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<[NetAddress](#netaddress)> | Yes | Callback used to return the result. If the operation is successful, the remote address is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**Example**
```js
tls.getRemoteAddress((err, data) => {
if (err) {
console.log('getRemoteAddress fail');
return;
}
console.log('getRemoteAddress success:' + JSON.stringify(data));
});
```
### getRemoteAddress<sup>9+</sup>
getRemoteAddress\(\): Promise\<NetAddress>
Obtains the remote address of a TLSSocket connection. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| :------------------------------------------ | :------------------------------------------ |
| Promise\<[NetAddress](#netaddress)> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ------------------------------ |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**Example**
```js
let promise = tls.getRemoteAddress();
promise.then(() => {
console.log('getRemoteAddress success');
}).catch(err => {
console.log('getRemoteAddress fail');
});
```
### getCertificate<sup>9+</sup>
getCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)>): void
Obtains the local digital certificate after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description|
| -------- | ----------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)> | Yes | Callback used to return the result. If the operation is successful, the local certificate is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303504 | Error looking up x509. |
| 2300002 | System internal error. |
**Example**
```js
tls.getCertificate((err, data) => {
if (err) {
console.log("getCertificate callback error = " + err);
} else {
console.log("getCertificate callback = " + data);
}
});
```
### getCertificate<sup>9+</sup>
getCertificate():Promise\<[X509CertRawData](#x509certrawdata9)>
Obtains the local digital certificate after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| -------------- | -------------------- |
| Promise\<[X509CertRawData](#x509certrawdata9)> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303504 | Error looking up x509. |
| 2300002 | System internal error. |
**Example**
```js
tls.getCertificate().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getRemoteCertificate<sup>9+</sup>
getRemoteCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)>): void
Obtains the digital certificate of the server after a TLSSocket connection is established. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ----------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)> | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2300002 | System internal error. |
**Example**
```js
tls.getRemoteCertificate((err, data) => {
if (err) {
console.log("getRemoteCertificate callback error = " + err);
} else {
console.log("getRemoteCertificate callback = " + data);
}
});
```
### getRemoteCertificate<sup>9+</sup>
getRemoteCertificate():Promise\<[X509CertRawData](#x509certrawdata9)>
Obtains the digital certificate of the server after a TLSSocket connection is established. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| -------------- | -------------------- |
| Promise\<[X509CertRawData](#x509certrawdata9)> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2300002 | System internal error. |
**Example**
```js
tls.getRemoteCertificate().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getProtocol<sup>9+</sup>
getProtocol(callback: AsyncCallback\<string>): void
Obtains the communication protocol version after a TLSSocket connection is established. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<string> | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------------- |
| 2303501 | SSL is null. |
| 2303505 | Error occurred in the tls system call. |
| 2300002 | System internal error. |
**Example**
```js
tls.getProtocol((err, data) => {
if (err) {
console.log("getProtocol callback error = " + err);
} else {
console.log("getProtocol callback = " + data);
}
});
```
### getProtocol<sup>9+</sup>
getProtocol():Promise\<string>
Obtains the communication protocol version after a TLSSocket connection is established. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| -------------- | -------------------- |
| Promise\<string> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303505 | Error occurred in the tls system call. |
| 2300002 | System internal error. |
**Example**
```js
tls.getProtocol().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getCipherSuite<sup>9+</sup>
getCipherSuite(callback: AsyncCallback\<Array\<string>>): void
Obtains the cipher suite negotiated by both communication parties after a TLSSocket connection is established. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description|
| -------- | ----------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<Array\<string>> | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303502 | Error in tls reading. |
| 2303505 | Error occurred in the tls system call. |
| 2300002 | System internal error. |
**Example**
```js
tls.getCipherSuite((err, data) => {
if (err) {
console.log("getCipherSuite callback error = " + err);
} else {
console.log("getCipherSuite callback = " + data);
}
});
```
### getCipherSuite<sup>9+</sup>
getCipherSuite(): Promise\<Array\<string>>
Obtains the cipher suite negotiated by both communication parties after a TLSSocket connection is established. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| ---------------------- | --------------------- |
| Promise\<Array\<string>> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303502 | Error in tls reading. |
| 2303505 | Error occurred in the tls system call. |
| 2300002 | System internal error. |
**Example**
```js
tls.getCipherSuite().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getSignatureAlgorithms<sup>9+</sup>
getSignatureAlgorithms(callback: AsyncCallback\<Array\<string>>): void
Obtains the signing algorithm negotiated by both communication parties after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<Array\<string>> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2300002 | System internal error. |
**Example**
```js
tls.getSignatureAlgorithms((err, data) => {
if (err) {
console.log("getSignatureAlgorithms callback error = " + err);
} else {
console.log("getSignatureAlgorithms callback = " + data);
}
});
```
### getSignatureAlgorithms<sup>9+</sup>
getSignatureAlgorithms(): Promise\<Array\<string>>
Obtains the signing algorithm negotiated by both communication parties after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| ---------------------- | -------------------- |
| Promise\<Array\<string>> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2300002 | System internal error. |
**Example**
```js
tls.getSignatureAlgorithms().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### send<sup>9+</sup>
send(data: string, callback: AsyncCallback\<void>): void
Sends a message to the server after a TLSSocket connection is established. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -----------------------------| ---- | ---------------|
| data | string | Yes | Data content of the message to send. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 401 | Parameter error. |
| 2303501 | SSL is null. |
| 2303503 | Error in tls writing |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**Example**
```js
tls.send("xxxx", (err) => {
if (err) {
console.log("send callback error = " + err);
} else {
console.log("send success");
}
});
```
### send<sup>9+</sup>
send(data: string): Promise\<void>
Sends a message to the server after a TLSSocket connection is established. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -----------------------------| ---- | ---------------|
| data | string | Yes | Data content of the message to send. |
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 401 | Parameter error. |
| 2303501 | SSL is null. |
| 2303503 | Error in tls writing |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**Return value**
| Type | Description |
| -------------- | -------------------- |
| Promise\<void> | Promise used to return the result. If the operation fails, an error message is returned.|
**Example**
```js
tls.send("xxxx").then(() =>{
console.log("send success");
}).catch(err => {
console.error(err);
});
```
### close<sup>9+</sup>
close(callback: AsyncCallback\<void>): void
Closes a TLSSocket connection. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -----------------------------| ---- | ---------------|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 2303501 | SSL is null. |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**Example**
```js
tls.close((err) => {
if (err) {
console.log("close callback error = " + err);
} else {
console.log("close success");
}
});
```
### close<sup>9+</sup>
close(): Promise\<void>
Closes a TLSSocket connection. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| -------------- | -------------------- |
| Promise\<void> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 2303501 | SSL is null. |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**Example**
```js
tls.close().then(() =>{
console.log("close success");
}).catch(err => {
console.error(err);
});
```
## TLSConnectOptions<sup>9+</sup>
Defines TLS connection options.
**System capability**: SystemCapability.Communication.NetStack
| Name | Type | Mandatory| Description |
| -------------- | ------------------------------------- | --- |-------------- |
| address | [NetAddress](#netaddress) | Yes | Gateway address. |
| secureOptions | [TLSSecureOptions](#tlssecureoptions9) | Yes| TLS security options.|
| ALPNProtocols | Array\<string> | No| Application Layer Protocol Negotiation (ALPN) protocols. |
## TLSSecureOptions<sup>9+</sup>
Defines TLS security options. The CA certificate is mandatory, and other parameters are optional. When **cert** (local certificate) and **key** (private key) are not empty, the two-way authentication mode is enabled. If **cert** or **key** is empty, one-way authentication is enabled.
**System capability**: SystemCapability.Communication.NetStack
| Name | Type | Mandatory| Description |
| --------------------- | ------------------------------------------------------ | --- |----------------------------------- |
| ca | string \| Array\<string> | Yes| CA certificate of the server, which is used to authenticate the digital certificate of the server.|
| cert | string | No| Digital certificate of the local client. |
| key | string | No| Private key of the local digital certificate. |
| passwd | string | No| Password for reading the private key. |
| protocols | [Protocol](#protocol9) \|Array\<[Protocol](#protocol9)> | No| TLS protocol version. |
| useRemoteCipherPrefer | boolean | No| Whether to use the remote cipher suite preferentially. |
| signatureAlgorithms | string | No| Signing algorithm used during communication. |
| cipherSuite | string | No| Cipher suite used during communication. |
## Protocol<sup>9+</sup>
Enumerates TLS protocol versions.
**System capability**: SystemCapability.Communication.NetStack
| Name | Value | Description |
| --------- | --------- |------------------ |
| TLSv12 | "TLSv1.2" | TLSv1.2.|
| TLSv13 | "TLSv1.3" | TLSv1.3.|
## X509CertRawData<sup>9+</sup>
Defines the certificate raw data.
**System capability**: SystemCapability.Communication.NetStack
| Type | Description |
| --------------------------------------------------------------------- | --------------------- |
|[cryptoFramework.EncodingBlob](js-apis-cryptoFramework.md#EncodingBlob) | Data and encoding format of the certificate.|
...@@ -348,7 +348,7 @@ let ret = usb.getFileDescriptor(devicepipe); ...@@ -348,7 +348,7 @@ let ret = usb.getFileDescriptor(devicepipe);
## usb.controlTransfer ## usb.controlTransfer
controlTransfer(pipe: USBDevicePipe, contrlparam: USBControlParams, timeout?: number): Promise&lt;number&gt; controlTransfer(pipe: USBDevicePipe, controlparam: USBControlParams, timeout?: number): Promise&lt;number&gt;
Performs control transfer. Performs control transfer.
...@@ -361,7 +361,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi ...@@ -361,7 +361,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the USB device.| | pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the USB device.|
| contrlparam | [USBControlParams](#usbcontrolparams) | Yes| Control transfer parameters.| | controlparam | [USBControlParams](#usbcontrolparams) | Yes| Control transfer parameters.|
| timeout | number | No| Timeout duration in ms. This parameter is optional. The default value is **0**, indicating no timeout.| | timeout | number | No| Timeout duration in ms. This parameter is optional. The default value is **0**, indicating no timeout.|
**Return value** **Return value**
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册