未验证 提交 e97fc035 编写于 作者: O openharmony_ci 提交者: Gitee

!2152 翻译已完成 1806#I4WQKA

Merge pull request !2152 from shawn_he/net-1
# Data Request
>![](public_sys-resources/icon-note.gif) **NOTE:**
>
>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
## Modules to Import
```
import http from '@ohos.net.http';
```
## Complete Example
```
import http from '@ohos.net.http';
// Each httpRequest corresponds to an HttpRequestTask object and cannot be reused.
let httpRequest = http.createHttp();
// This API is used to subscribe to the HTTP response header, which is returned earlier than httpRequest. It is up to you whether to listen for HTTP Response Header events.
// on('headerReceive', AsyncCallback) will be replaced by on('headersReceive', Callback) in API version 8. 8+
httpRequest.on('headersReceive', (data) => {
console.info('header: ' + data.header);
});
httpRequest.request(
// Customize EXAMPLE_URL on your own. It is up to you whether to add parameters to the URL. You can set the parameters of the GET request in extraData.
"EXAMPLE_URL",
{
method: 'POST', // Optional. The default value is GET.
// Add the header field based on your service requirements.
header: {
'Content-Type': 'application/json'
},
// This field is used to transfer content when the POST request is used. You can set request parameters in extraData as needed.
extraData: {
"data": "data to send",
},
connectTimeout: 60000, // Optional. The default value is **60000**, in ms.
readTimeout: 60000, // Optional. The default value is **60000**, in ms.
},(err, data) => {
if (!err) {
// data.result contains the HTTP response. It is up to you whether to parse the content.
console.info('Result:' + data.result);
console.info('code:' + data.responseCode);
// data.header contains the HTTP response header. It is up to you whether to parse the content.
console.info('header:' + data.header);
console.info('cookies:' + data.cookies); // 8+
} else {
console.info('error:' + err);
// Call the destroy function to destroy the request after use.
httpRequest.destroy();
}
}
);
```
## http.createHttp
createHttp\(\): HttpRequest
Creates an HTTP request. You can use this API to initiate or destroy an HTTP request, or enable or disable listening for HTTP Response Header events. An HttpRequest object corresponds to an HTTP request. To initiate multiple HTTP requests, you must create an HttpRequest object for each HTTP request.
**System capability**: SystemCapability.Communication.NetStack
**Return Value**
| Type | Description |
| :---------- | :----------------------------------------------------------- |
| HttpRequest | An **HttpRequest **object, which contains the **request**, **destroy**, **on**, or **off** method.|
**Example**
```
import http from '@ohos.net.http';
let httpRequest = http.createHttp();
```
## HttpRequest
Defines an **HttpRequest** object. Before invoking HttpRequest APIs, you must call [createHttp\(\)](#httpcreatehttp) to create an **HttpRequestTask** object.
### request
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.
**Required permission**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------- | ---- | ----------------------- |
| url | string | Yes | URL for initiating an HTTP request.|
| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | Yes | Callback used to return the result. |
**Example**
```
httpRequest.request("EXAMPLE_URL", (err, data) => {
if (!err) {
console.info('Result:' + data.result);
console.info('code:' + data.responseCode);
console.info('header:' + data.header);
console.info('cookies:' + data.cookies); // 8+
} else {
console.info('error:' + err.data);
}
});
```
### request
request\(url: string, options: HttpRequestOptions, callback: AsyncCallback<HttpResponse\>\):void
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
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- |
| url | string | Yes | URL for initiating an HTTP request. |
| options | HttpRequestOptions | Yes | Request options. For details, see [HttpRequestOptions](#httprequestoptions).|
| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | Yes | Callback used to return the result. |
**Example**
```
httpRequest.request("EXAMPLE_URL",
{
method: 'GET',
header: {
'Content-Type': 'application/json'
},
readTimeout: 60000,
connectTimeout: 60000
},(err, data) => {
if (!err) {
console.info('Result:' + data.result);
console.info('code:' + data.responseCode);
console.info('header:' + data.header);
console.info('cookies:' + data.cookies); // 8+
console.info('header['Content-Type']:' + data.header['Content-Type']);
console.info('header['Status-Line']:' + data.header['Status-Line']);
console.info('header.Date:' + data.header.Date);
console.info('header.Server:' + data.header.Server);
} else {
console.info('error:' + err.data);
}
});
```
### request
request\(url: string, options? : HttpRequestOptions\): Promise<HttpResponse\>
Initiates an HTTP request to a given URL. This API uses a promise to return the result.
**Required permission**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------------------ | ---- | -------------------------------------------------- |
| url | string | Yes | URL for initiating an HTTP request. |
| options | HttpRequestOptions | Yes | Request options. For details, see [HttpRequestOptions](#httprequestoptions).|
**Return Value**
| Type | Description |
| :-------------------- | :-------------------------------- |
| Promise<[HttpResponse](#httpresponse)> | Promise used to return the result.|
**Example**
```
let promise = httpRequest.request("EXAMPLE_URL", {
method: "GET",
connectTimeout: 60000,
readTimeout: 60000,
header: {
'Content-Type': 'application/json'
}
});
promise.then((value) => {
console.info('Result:' + value.result);
console.info('code:' + value.responseCode);
console.info('header:' + value.header);
console.info('cookies:' + value.cookies); // 8+
console.info('header['Content-Type']:' + value.header['Content-Type']);
console.info('header['Status-Line']:' + value.header['Status-Line']);
console.info('header.Date:' + value.header.Date);
console.info('header.Server:' + value.header.Server);
}).catch((err) => {
console.error(`errCode:${err.code}, errMessage:${err.data}`);
});
```
### destroy
destroy\(\): void
Destroys an HTTP request.
**System capability**: SystemCapability.Communication.NetStack
**Example**
```
httpRequest.destroy();
```
### on\('headerReceive'\)
on\(type: 'headerReceive', callback: AsyncCallback<Object\>\): void
Registers an observer for HTTP Response Header events.
>![](public_sys-resources/icon-note.gif) **NOTE:**
> This API has been deprecated. You are advised to use [on\('headersReceive'\)<sup>8+</sup>](#onheadersreceive8) instead.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | --------------------------------- |
| type | string | Yes | Event type. The value is **headerReceive**.|
| callback | AsyncCallback\<Object\> | Yes | Callback used to return the result. |
**Example**
```
httpRequest.on('headerReceive', (err, data) => {
if (!err) {
console.info('header: ' + data.header);
} else {
console.info('error:' + err.data);
}
});
```
### off\('headerReceive'\)
off\(type: 'headerReceive', callback?: AsyncCallback<Object\>\): void
Unregisters the observer for HTTP Response Header events.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>
>1. This API has been deprecated. You are advised to use [off\('headersReceive'\)<sup>8+</sup>](#offheadersreceive8) instead.
>
>2. You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | ------------------------------------- |
| type | string | Yes | Event type. The value is **headerReceive**.|
| callback | AsyncCallback\<Object\> | No | Callback used to return the result. |
**Example**
```
httpRequest.on('headerReceive', (err, data) => {
if (!err) {
console.info('header: ' + data.header);
} else {
console.info('error:' + err.data);
}
});
httpRequest.off('headerReceive');
```
### on\('headersReceive'\)<sup>8+</sup>
on\(type: 'headersReceive', callback: Callback<Object\>\): void
Registers an observer for HTTP Response Header events.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------ | ---- | ---------------------------------- |
| type | string | Yes | Event type. The value is **headersReceive**.|
| callback | Callback\<Object\> | Yes | Callback used to return the result. |
**Example**
```
httpRequest.on('headersReceive', (data) => {
console.info('header: ' + data.header);
});
```
### off\('headersReceive'\)<sup>8+</sup>
off\(type: 'headersReceive', callback?: Callback<Object\>\): void
Unregisters the observer for HTTP Response Header events.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------ | ---- | -------------------------------------- |
| type | string | Yes | Event type. The value is **headersReceive**.|
| callback | Callback\<Object\> | No | Callback used to return the result. |
**Example**
```
httpRequest.off('headersReceive');
```
### once\('headersReceive'\)<sup>8+</sup>
once\(type: 'headersReceive', callback: Callback<Object\>\): void
Registers a one-time observer for HTTP Response Header events. Once triggered, the observer will be removed. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------ | ---- | ---------------------------------- |
| type | string | Yes | Event type. The value is **headersReceive**.|
| callback | Callback\<Object\> | Yes | Callback used to return the result. |
**Example**
```
httpRequest.once('headersReceive', (data) => {
console.info('header: ' + data.header);
});
```
## HttpRequestOptions
Specifies the type and value range of the optional parameters in the HTTP request.
**System capability**: SystemCapability.Communication.NetStack
| Name | Type | Mandatory| Description |
| -------------- | ------------------------------------ | ---- | ---------------------------------------------------------- |
| method | [RequestMethod](#requestmethod) | No | Request method. |
| extraData | string \| Object \| ArrayBuffer<sup>8+</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>8+</sup><br>- To pass in a string object, you first need to encode the object on your own.<sup>8+</sup> |
| header | Object | No | HTTP request header. The default value is {'Content-Type': 'application/json'}.|
| readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. |
| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. |
## RequestMethod
Defines an HTTP request method.
**System capability**: SystemCapability.Communication.NetStack
| Name | Value | Description |
| :------ | ------- | :------------------ |
| OPTIONS | OPTIONS | OPTIONS method.|
| GET | GET | GET method. |
| HEAD | HEAD | HEAD method. |
| POST | POST | POST method. |
| PUT | PUT | PUT method. |
| DELETE | DELETE | DELETE method. |
| TRACE | TRACE | TRACE method. |
| CONNECT | CONNECT | CONNECT method.|
## ResponseCode
Enumerates the response codes for an HTTP request.
**System capability**: SystemCapability.Communication.NetStack
| Name | Value | Description |
| ----------------- | ---- | ------------------------------------------------------------ |
| OK | 200 | "OK." The request has been processed successfully. This return code is generally used for GET and POST requests. |
| CREATED | 201 | "Created." The request has been successfully sent and a new resource is created. |
| ACCEPTED | 202 | "Accepted." The request has been accepted, but the processing has not been completed. |
| NOT_AUTHORITATIVE | 203 | "Non-Authoritative Information." The request is successful. |
| NO_CONTENT | 204 | "No Content." The server has successfully fulfilled the request but there is no additional content to send in the response payload body. |
| RESET | 205 | "Reset Content." The server has successfully fulfilled the request and desires that the user agent reset the content. |
| PARTIAL | 206 | "Partial Content." The server has successfully fulfilled the partial GET request for a given resource. |
| MULT_CHOICE | 300 | "Multiple Choices." The requested resource corresponds to any one of a set of representations. |
| MOVED_PERM | 301 | "Moved Permanently." The requested resource has been assigned a new permanent URI and any future references to this resource will be redirected to this URI.|
| MOVED_TEMP | 302 | "Moved Temporarily." The requested resource is moved temporarily to a different URI. |
| SEE_OTHER | 303 | "See Other." The response to the request can be found under a different URI. |
| NOT_MODIFIED | 304 | "Not Modified." The client has performed a conditional GET request and access is allowed, but the content has not been modified. |
| USE_PROXY | 305 | "Use Proxy." The requested resource can only be accessed through the proxy. |
| BAD_REQUEST | 400 | "Bad Request." The request could not be understood by the server due to incorrect syntax. |
| UNAUTHORIZED | 401 | "Unauthorized." The request requires user authentication. |
| PAYMENT_REQUIRED | 402 | "Payment Required." This code is reserved for future use. |
| FORBIDDEN | 403 | "Forbidden." The server understands the request but refuses to process it. |
| NOT_FOUND | 404 | "Not Found." The server does not find anything matching the Request-URI. |
| BAD_METHOD | 405 | "Method Not Allowed." The method specified in the request is not allowed for the resource identified by the Request-URI. |
| NOT_ACCEPTABLE | 406 | "Not Acceptable." The server cannot fulfill the request according to the content characteristics of the request. |
| PROXY_AUTH | 407 | "Proxy Authentication Required." The request requires user authentication with the proxy. |
| CLIENT_TIMEOUT | 408 | "Request Timeout." The client fails to generate a request within the timeout period. |
| CONFLICT | 409 | "Conflict." The request cannot be fulfilled due to a conflict with the current state of the resource. Conflicts are most likely to occur in response to a PUT request. |
| GONE | 410 | "Gone." The requested resource has been deleted permanently and is no longer available. |
| LENGTH_REQUIRED | 411 | "Length Required." The server refuses to process the request without a defined Content-Length. |
| PRECON_FAILED | 412 | "Precondition Failed." The precondition in the request is incorrect. |
| ENTITY_TOO_LARGE | 413 | "Request Entity Too Large." The server refuses to process a request because the request entity is larger than the server is able to process. |
| REQ_TOO_LONG | 414 | "Request-URI Too Long." The Request-URI is too long for the server to process. |
| UNSUPPORTED_TYPE | 415 | "Unsupported Media Type." The server is unable to process the media format in the request. |
| INTERNAL_ERROR | 500 | "Internal Server Error." The server encounters an unexpected error that prevents it from fulfilling the request. |
| NOT_IMPLEMENTED | 501 | "Not Implemented." The server does not support the function required to fulfill the request. |
| BAD_GATEWAY | 502 | "Bad Gateway." The server acting as a gateway or proxy receives an invalid response from the upstream server.|
| UNAVAILABLE | 503 | "Service Unavailable." The server is currently unable to process the request due to a temporary overload or system maintenance. |
| GATEWAY_TIMEOUT | 504 | "Gateway Timeout." The server acting as a gateway or proxy does not receive requests from the remote server within the timeout period. |
| VERSION | 505 | "HTTP Version Not Supported." The server does not support the HTTP protocol version used in the request. |
## HttpResponse
Defines the response to an HTTP request.
**System capability**: SystemCapability.Communication.NetStack
| Name | Type | Mandatory| Description |
| -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
| result | string \| Object \| ArrayBuffer<sup>8+</sup> | Yes | Response content returned based on **Content-type** in the response header:<br>- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.<br>- application/octet-stream: ArrayBuffer<br>- Others: string|
| 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**. The error code can be one of the following:<br>- 200: common error<br>- 202: parameter error<br>- 300: I/O error|
| 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. |
# Network Connection Management
> **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.
## Modules to Import
```javascript
import connection from '@ohos.net.connection'
```
## connection.getDefaultNet
getDefaultNet(callback: AsyncCallback\<NetHandle>): void
Obtains the default active data network. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result.|
**Example**
```javascript
connection.getDefaultNet(function (error, netHandle) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(netHandle))
})
```
## connection.getDefaultNet
getDefaultNet(): Promise\<NetHandle>
Obtains the default active data network. This API uses a promise to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core
**Return Value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<[NetHandle](#nethandle)> | Promise used to return the result.|
**Example**
```javascript
connection.getDefaultNet().then(function (netHandle) {
console.log(JSON.stringify(netHandle))
})
```
## connection.hasDefaultNet
hasDefaultNet(callback: AsyncCallback\<boolean>): void
Checks whether the default data network is activated. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- |
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** indicates that the default data network is activated.|
**Example**
```javascript
connection.hasDefaultNet(function (error, has) {
console.log(JSON.stringify(error))
console.log(has)
})
```
## connection.hasDefaultNet
hasDefaultNet(): Promise\<boolean>
Checks whether the default data network is activated. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetManager.Core
**Return Value**
| Type | Description |
| ----------------- | ----------------------------------------------- |
| Promise\<boolean> | Promise used to return the result. The value **true** indicates that the default data network is activated.|
**Example**
```javascript
connection.hasDefaultNet().then(function (has) {
console.log(has)
})
```
## connection.getAllNets
getAllNets(callback: AsyncCallback&lt;Array&lt;NetHandle&gt;&gt;): void
Obtains the list of all active data networks. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;Array&lt;[NetHandle](#nethandle)&gt;&gt; | Yes| Callback used to return the result.|
**Example**
```
connection.getAllNets(function (error, nets) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(nets))
});
```
## connection.getAllNets
getAllNets(): Promise&lt;Array&lt;NetHandle&gt;&gt;
Obtains the list of all active data networks. This API uses a promise to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core
**Return Value**
| Type| Description|
| -------- | -------- |
| Promise&lt;Array&lt;[NetHandle](#nethandle)&gt;&gt; | Promise used to return the result.|
**Example**
```
connection.getAllNets().then(function (nets) {
console.log(JSON.stringify(nets))
});
```
## connection.getConnectionProperties
getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\<ConnectionProperties>): void
Obtains connection properties of the network corresponding to given network handle. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------------------ | ---- | ---------------- |
| netHandle | [NetHandle](#nethandle) | Yes | Network handle.|
| callback | AsyncCallback\<[ConnectionProperties](#connectionproperties)> | Yes | Callback used to return the result. |
**Example**
```javascript
connection.getDefaultNet().then(function (netHandle) {
connection.getConnectionProperties(netHandle, function (error, info) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(info))
})
})
```
## connection.getConnectionProperties
getConnectionProperties(netHandle: NetHandle): Promise\<ConnectionProperties>
Obtains connection properties of the network corresponding to **netHandle**. This API uses a promise to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ----------------------- | ---- | ---------------- |
| netHandle | [NetHandle](#nethandle) | Yes | Network handle.|
**Return Value**
| Type | Description |
| ------------------------------------------------------- | --------------------------------- |
| Promise\<[ConnectionProperties](#connectionproperties)> | Promise used to return the result.|
**Example**
```javascript
connection.getDefaultNet().then(function (netHandle) {
connection.getConnectionProperties(netHandle).then(function (info) {
console.log(JSON.stringify(info))
})
})
```
## connection.getNetCapabilities
getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback\<NetCapabilities>): void
Obtains capability information of the network corresponding to **netHandle**. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | --------------------------------------------------- | ---- | ---------------- |
| netHandle | [NetHandle](#nethandle) | Yes | Network handle.|
| callback | AsyncCallback\<[NetCapabilities](#netcapabilities)> | Yes | Callback used to return the result. |
**Example**
```javascript
connection.getDefaultNet().then(function (netHandle) {
connection.getNetCapabilities(netHandle, function (error, info) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(info))
})
})
```
## connection.getNetCapabilities
getNetCapabilities(netHandle: NetHandle): Promise\<NetCapabilities>
Obtains capability information of the network corresponding to **netHandle**. This API uses a promise to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ----------------------- | ---- | ---------------- |
| netHandle | [NetHandle](#nethandle) | Yes | Network handle.|
**Return Value**
| Type | Description |
| --------------------------------------------- | --------------------------------- |
| Promise\<[NetCapabilities](#netcapabilities)> | Promise used to return the result.|
**Example**
```javascript
connection.getDefaultNet().then(function (netHandle) {
connection.getNetCapabilities(netHandle).then(function (info) {
console.log(JSON.stringify(info))
})
})
```
## connection.reportNetConnected
reportNetConnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void
Reports connection of the data network. This API uses an asynchronous callback to return the result.
** Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Example**
```
connection.getDefaultNet().then(function (netHandle) {
connection.reportNetConnected(netHandle, function (error) {
console.log(JSON.stringify(error))
});
});
```
## connection.reportNetConnected
reportNetConnected(netHandle: NetHandle): Promise&lt;void&gt;
Reports connection of the data network. This API uses a promise to return the result.
** Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|
**Return Value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Example**
```
connection.getDefaultNet().then(function (netHandle) {
connection.reportNetConnected(netHandle).then(function () {
console.log(`report success`)
});
});
```
## connection.reportNetDisconnected
reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void
Reports disconnection of the data network. This API uses an asynchronous callback to return the result.
** Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Example**
```
connection.getDefaultNet().then(function (netHandle) {
connection.reportNetDisconnected(netHandle, function (error) {
console.log(JSON.stringify(error))
});
});
```
## connection.reportNetDisconnected
reportNetDisconnected(netHandle: NetHandle): Promise&lt;void&gt;
Reports disconnection of the data network. This API uses a promise to return the result.
** Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|
**Return Value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Example**
```
connection.getDefaultNet().then(function (netHandle) {
connection.reportNetDisconnected(netHandle).then(function () {
console.log(`report success`)
});
});
```
## connection.getAddressesByName
getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>): void
Resolves the host name by using the default network to obtain all IP addresses. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------- | ---- | ------------------ |
| host | string | Yes | Host name to be resolved.|
| callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | Yes | Callback used to return the result. |
**Example**
```
let host = "xxxx";
connection.getAddressesByName(host, function (error, addresses) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(addresses))
})
```
## connection.getAddressesByName
getAddressesByName(host: string): Promise\<Array\<NetAddress>>
Resolves the host name by using the default network to obtain all IP addresses. This API uses a promise to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------ |
| host | string | Yes | Host name to be resolved.|
**Return Value**
| Type | Description |
| ------------------------------------------- | ----------------------------- |
| Promise\<Array\<[NetAddress](#netaddress)>> | Promise used to return the result.|
**Example**
```
let host = "xxxx";
connection.getAddressesByName(host).then(function (addresses) {
console.log(JSON.stringify(addresses))
})
```
## connection.createNetConnection
createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection
Obtains the handle of the network specified by **netSpecifier**.
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
| netSpecifier | [NetSpecifier](#netspecifier) | No | Network specifier. If this parameter is not set, the default network is used. |
| timeout | number | No | Timeout interval for obtaining the network specified by **netSpecifier**. This parameter is valid only when **netSpecifier** is set.|
**Return Value**
| Type | Description |
| ------------------------------- | -------------------- |
| [NetConnection](#netconnection) | Handle of the network specified by **netSpecifier**.|
**Example**
```javascript
// Default network
let netConnection = connection.createNetConnection()
// Cellular network
let netConnectionCellular = connection.createNetConnection({
netCapabilities: {
bearerTypes: [NetBearType.BEARER_CELLULAR]
}
})
```
## NetConnection
Represents the network connection handle.
### on('netAvailable')
on(type: 'netAvailable', callback: Callback\<NetHandle>): void
Registers a listener for **netAvailable** events.
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The value is fixed to **netAvailable**.<br>**netAvailable**: event indicating that the data network is available.|
| callback | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result. |
**Example**
```javascript
netConnection.on('netAvailable', function (data) {
console.log(JSON.stringify(data))
})
```
### on('netCapabilitiesChange')
on(type: 'netCapabilitiesChange', callback: Callback<{ netHandle: NetHandle, netCap: NetCapabilities }>): void
Registers a listener for **netCapabilitiesChange** events.
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The value is fixed to **netCapabilitiesChange**.<br>**netCapabilitiesChange**: event indicating that he network capabilities have changed.|
| callback | Callback<{ netHandle: [NetHandle](#nethandle), netCap: [NetCapabilities](#netcapabilities) }> | Yes | Callback used to return the result. |
**Example**
```javascript
netConnection.on('netCapabilitiesChange', function (data) {
console.log(JSON.stringify(data))
})
```
### on('netConnectionPropertiesChange')
on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void
Registers a listener for **netConnectionPropertiesChange** events.
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The value is fixed to **netConnectionPropertiesChange**.<br>**netConnectionPropertiesChange**: event indicating that network connection properties have changed.|
| callback | Callback<{ netHandle: [NetHandle](#nethandle), connectionProperties: [ConnectionProperties](#connectionproperties) }> | Yes | Callback used to return the result. |
**Example**
```javascript
netConnection.on('netConnectionPropertiesChange', function (data) {
console.log(JSON.stringify(data))
})
```
### on('netBlockStatusChange')
on(type: 'netBlockStatusChange', callback: Callback&lt;{ netHandle: NetHandle, blocked: boolean }&gt;): void
Registers a listener for **netBlockStatusChange** events.
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The value is fixed to **netBlockStatusChange**.<br>**netBlockStatusChange**: event indicating a change in the network blocking status.|
| callback | Callback&lt;{&nbsp;netHandle:&nbsp;[NetHandle](#nethandle),&nbsp;blocked:&nbsp;boolean&nbsp;}&gt; | Yes | Callback used to return the result. |
**Example**
```javascript
netConnection.on('netBlockStatusChange', function (data) {
console.log(JSON.stringify(data))
})
```
### on('netLost')
on(type: 'netLost', callback: Callback\<NetHandle>): void
Registers a listener for **netLost** events.
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The value is fixed to **netLost**.<br>netLost: event indicating that the network is interrupted or normally disconnected.|
| callback | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result. |
**Example**
```javascript
let netConnection1 = connection.createNetConnection()
netConnection1.on('netLost', function (data) {
console.log(JSON.stringify(data))
})
```
### on('netUnavailable')
on(type: 'netUnavailable', callback: Callback\<void>): void
Registers a listener for **netUnavailable** events.
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The value is fixed to **netUnavailable**.<br>**netUnavailable**: event indicating that the network is unavailable.|
| callback | Callback\<void> | Yes | Callback used to return the result. |
**Example**
```javascript
netConnection.on('netUnavailable', function (data) {
console.log(JSON.stringify(data))
})
```
### register
register(callback: AsyncCallback\<void>): void
Registers a listener for network status changes.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Example**
```javascript
netConnection.register(function (error) {
console.log(JSON.stringify(error))
})
```
### unregister
unregister(callback: AsyncCallback\<void>): void
Unregisters the listener for network status changes.
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Example**
```javascript
netConnection.unregister(function (error) {
console.log(JSON.stringify(error))
})
```
## NetHandle
Defines the handle of the data network.
Before invoking NetHandle APIs, call **getNetHandle** to obtain a **NetHandle** object.
**System capability**: SystemCapability.Communication.NetManager.Core
### Parameters
| Name| Type | Description |
| ------ | ------ | ------------------------- |
| netId | number | Network ID. The value must be greater than or equal to 100.|
### bindSocket
bindSocket(socketParam: TCPSocket | UDPSocket, callback: AsyncCallback&lt;void&gt;): void
Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ----------- | ------------------------- | ---- | ---------------- |
| socketParam | TCPSocket \| UDPSocket | Yes | **TCPSocket** or **UDPSocket** object.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. |
**Example**
```
// Bind the TCPSocket object.
connection.getDefaultNet().then(function (netHandle) {
let tcpSocket = socket.constructTCPSocketInstance()
netHandle.bindSocket(tcpSocket, (function (error) {
console.log(JSON.stringify(error))
}))
})
// Bind the UDPSocket object.
connection.getDefaultNet().then(function (netHandle) {
let udpSocket = socket.constructUDPSocketInstance()
netHandle.bindSocket(udpSocket, (function (error) {
console.log(JSON.stringify(error))
}))
})
```
### bindSocket
bindSocket(socketParam: TCPSocket | UDPSocket): Promise&lt;void&gt;
Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| socketParam | TCPSocket \| UDPSocket | Yes | **TCPSocket** or **UDPSocket** object.|
**Return Value**
| Type | Description |
| ------------------- | --------------------------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Example**
```
// Bind the TCPSocket object.
connection.getDefaultNet().then(function (netHandle) {
let tcpSocket = socket.constructTCPSocketInstance()
netHandle.bindSocket(tcpSocket).then(function () {
console.log("bind socket success")
})
})
// Bind the UDPSocket object.
connection.getDefaultNet().then(function (netHandle) {
let udpSocket = socket.constructUDPSocketInstance()
netHandle.bindSocket(udpSocket).then(function () {
console.log("bind socket success")
})
})
```
### getAddressesByName
getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>): void
Resolves the host name by using the corresponding network to obtain all IP addresses. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------- | ---- | ------------------ |
| host | string | Yes | Host name to be resolved.|
| callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | Yes | Callback used to return the result. |
**Example**
```javascript
connection.getDefaultNet().then(function (netHandle) {
let host = "xxxx";
netHandle.getAddressesByName(host, function (error, addresses) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(addresses))
})
})
```
### getAddressesByName
getAddressesByName(host: string): Promise\<Array\<NetAddress>>
Resolves the host name by using the corresponding network to obtain all IP addresses. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------ |
| host | string | Yes | Host name to be resolved.|
**Return Value**
| Type | Description |
| ------------------------------------------- | ----------------------------- |
| Promise\<Array\<[NetAddress](#netaddress)>> | Promise used to return the result.|
**Example**
```javascript
connection.getDefaultNet().then(function (netHandle) {
let host = "xxxx";
netHandle.getAddressesByName(host).then(function (addresses) {
console.log(JSON.stringify(addresses))
})
})
```
### getAddressByName
getAddressByName(host: string, callback: AsyncCallback\<NetAddress>): void
Resolves the host name by using the corresponding network to obtain the first IP address. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------- | ---- | ------------------ |
| host | string | Yes | Host name to be resolved.|
| callback | AsyncCallback\<[NetAddress](#netaddress)> | Yes | Callback used to return the result. |
**Example**
```javascript
connection.getDefaultNet().then(function (netHandle) {
let host = "xxxx";
netHandle.getAddressByName(host, function (error, address) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(address))
})
})
```
### getAddressByName
getAddressByName(host: string): Promise\<NetAddress>
Resolves the host name by using the corresponding network to obtain the first IP address. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------ |
| host | string | Yes | Host name to be resolved.|
**Return Value**
| Type | Description |
| ----------------------------------- | ------------------------------- |
| Promise\<[NetAddress](#netaddress)> | Promise used to return the result.|
**Example**
```javascript
connection.getDefaultNet().then(function (netHandle) {
let host = "xxxx";
netHandle.getAddressByName(host).then(function (address) {
console.log(JSON.stringify(address))
})
})
```
## NetSpecifier
Provides an instance that bears data network capabilities.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Description |
| ----------------------- | ----------------------------------- | ------------------------------------------------------------ |
| netCapabilities | [NetCapabilities](#netcapabilities) | Network transmission capabilities and bearer types of the data network. |
| bearerPrivateIdentifier | string | Network identifier. The identifier of a Wi-Fi network is **wifi**, and that of a cellular network is **slot0** (corresponding to SIM card 1).|
## NetCapabilities
Defines the network capability set.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Description |
| --------------------- | ---------------------------------- | ------------------------ |
| linkUpBandwidthKbps | number | Uplink (from the device to the network) bandwidth.|
| linkDownBandwidthKbps | number | Downlink (from the network to the device) bandwidth.|
| networkCap | Array<[NetCap](#netcap)> | Network capability. |
| bearerTypes | Array<[NetBearType](#netbearType)> | Network type. |
## NetCap
Defines the network capability.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Value | Description |
| ------------------------ | ---- | ---------------------- |
| NET_CAPABILITY_MMS | 0 | The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages.|
| NET_CAPABILITY_NOT_METERED | 11 | The network traffic is not metered.|
| NET_CAPABILITY_INTERNET | 12 | The network can connect to the Internet.|
| NET_CAPABILITY_NOT_VPN | 15 | The network does not use a Virtual Private Network (VPN).|
| NET_CAPABILITY_VALIDATED | 16 | The network is available. |
## NetBearType
Defines the network type.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Value | Description |
| --------------- | ---- | ----------- |
| BEARER_CELLULAR | 0 | Cellular network |
| BEARER_WIFI | 1 | Wi-Fi network|
| BEARER_ETHERNET | 3 | Ethernet network|
## ConnectionProperties
Defines the network connection properties.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Description |
| ------------- | ---------------------------------- | ---------------- |
| interfaceName | string | NIC card name. |
| domains | string | Domain. The default value is **""**.|
| linkAddresses | Array<[LinkAddress](#linkaddress)> | Link information. |
| routes | Array<[RouteInfo](#routeinfo)> | Route information. |
| dnses | Array&lt;[NetAddress](#netaddress)&gt; | Network address. For details, see [NetAddress](#netaddress).|
| mtu | number | Maximum transmission unit (MTU). |
## LinkAddress
Network link information.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Description |
| ------------ | ------------------------- | -------------------- |
| address | [NetAddress](#netaddress) | Link address. |
| prefixLength | number | Length of the link address prefix.|
## RouteInfo
Network route information.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Description |
| -------------- | --------------------------- | ---------------- |
| interface | string | NIC card name. |
| destination | [LinkAddress](#linkaddress) | Destination IP address. |
| gateway | [NetAddress](#netaddress) | Gateway address. |
| hasGateway | boolean | Whether a gateway is present. |
| isDefaultRoute | boolean | Whether the route is the default route.|
## NetAddress
Defines the network address.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Description |
| ------- | ------ | ------------------------------ |
| address | string | Network address. |
| family | number | Address family identifier. The value is **1** for IPv4 and **2** for IPv6. The default value is **1**.|
| port | number | Port number. The value ranges from **0** to **65535**. |
# Socket
>![](public_sys-resources/icon-note.gif) **NOTE:**
>
>The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
## Modules to Import
```
import socket from '@ohos.net.socket';
```
## socket.constructUDPSocketInstance
constructUDPSocketInstance\(\): UDPSocket
Creates a **UDPSocket** object.
**System capability**: SystemCapability.Communication.NetStack
**Return Value**
| Type | Description |
| :--------------------------------- | :---------------------- |
| [UDPSocket](#udpsocket) | **UDPSocket** object.|
**Example**
```
let udp = socket.constructUDPSocketInstance();
```
## UDPSocket
Defines a **UDPSocket** connection. Before invoking UDPSocket APIs, you need to call [socket.constructUDPSocketInstance](#socketconstructudpsocketinstance) to create a **UDPSocket** object.
### bind
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.
**Required permission**: 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. |
**Example**
```
let udp = socket.constructUDPSocketInstance();
udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
})
```
### bind
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.
**Required permission**: 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.|
**Example**
```
let udp = socket.constructUDPSocketInstance();
let promise = udp.bind({address: '192.168.xx.xxx', port: 8080, family: 1});
promise .then(() => {
console.log('bind success');
}).catch(err => {
console.log('bind fail');
});
```
### send
send\(options: UDPSendOptions, callback: AsyncCallback<void\>\): void
Sends data over a UDPSocket connection. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
**Example**
```
let udp = socket.constructUDPSocketInstance();
udp.send({
data:'Hello, server!',
address: {
address:'192.168.xx.xxx',
port:xxxx,
family:1
}
}, err=> {
if (err) {
console.log('send fail');
return;
}
console.log('send success');
})
```
### send
send\(options: UDPSendOptions\): Promise<void\>
Sends data over a UDPSocket connection. This API uses a promise to return the result.
**Required permission**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).|
**Return Value**
| Type | Description |
| :-------------- | :--------------------------------------------- |
| Promise\<void\> | Promise used to return the result.|
**Example**
```
let udp = socket.constructUDPSocketInstance();
let promise = udp.send({
data:'Hello, server!',
address: {
address:'192.168.xx.xxx',
port:xxxx,
family:1
}
});
promise.then(() => {
console.log('send success');
}).catch(err => {
console.log('send fail');
});
```
### close
close\(callback: AsyncCallback<void\>\): void
Closes a UDPSocket connection. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ---------- |
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.|
**Example**
```
let udp = socket.constructUDPSocketInstance();
udp.close(err => {
if (err) {
console.log('close fail');
return;
}
console.log('close success');
})
```
### close
close\(\): Promise<void\>
Closes a UDPSocket connection. This API uses a promise to return the result.
**Required permission**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Return Value**
| Type | Description |
| :-------------- | :----------------------------------------- |
| Promise\<void\> | Promise used to return the result.|
**Example**
```
let udp = socket.constructUDPSocketInstance();
let promise = udp.close();
promise.then(() => {
console.log('close success');
}).catch(err => {
console.log('close fail');
});
```
### getState
getState\(callback: AsyncCallback<SocketStateBase\>\): void
Obtains the status of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>This API can be called only after [bind](#bind) is successfully called.
**Required permission**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------ | ---- | ---------- |
| callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | Yes | Callback used to return the result.|
**Example**
```
let udp = socket.constructUDPSocketInstance();
udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
udp.getState((err, data) => {
if (err) {
console.log('getState fail');
return;
}
console.log('getState success:' + JSON.stringify(data));
})
})
```
### getState
getState\(\): Promise<SocketStateBase\>
Obtains the status of the UDPSocket connection. This API uses a promise to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>This API can be called only after [bind](#bind) is successfully called.
**Required permission**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Return Value**
| Type | Description |
| :----------------------------------------------- | :----------------------------------------- |
| Promise<[SocketStateBase](#socketstatebase)> | Promise used to return the result.|
**Example**
```
let udp = socket.constructUDPSocketInstance();
udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
let promise = udp.getState({});
promise.then(data => {
console.log('getState success:' + JSON.stringify(data));
}).catch(err => {
console.log('getState fail');
});
})
```
### setExtraOptions
setExtraOptions\(options: UDPExtraOptions, callback: AsyncCallback<void\>\): void
Sets other properties of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>This API can be called only after [bind](#bind) is successfully called.
**Required permission**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [UDPExtraOptions](#udpextraoptions) | Yes | Other properties of the UDPSocket connection. For details, see [UDPExtraOptions](#udpextraoptions).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
**Example**
```
let udp = socket.constructUDPSocketInstance();
udp.bind({address:'192.168.xx.xxx', port:xxxx, family:1}, err=> {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
udp.setExtraOptions({
receiveBufferSize:1000,
sendBufferSize:1000,
reuseAddress:false,
socketTimeout:6000,
broadcast:true
}, err=> {
if (err) {
console.log('setExtraOptions fail');
return;
}
console.log('setExtraOptions success');
})
})
```
### setExtraOptions
setExtraOptions\(options: UDPExtraOptions\): Promise<void\>
Sets other properties of the UDPSocket connection. This API uses a promise to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>This API can be called only after [bind](#bind) is successfully called.
**Required permission**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [UDPExtraOptions](#udpextraoptions) | Yes | Other properties of the UDPSocket connection. For details, see [UDPExtraOptions](#udpextraoptions).|
**Return Value**
| Type | Description |
| :-------------- | :--------------------------------------------------- |
| Promise\<void\> | Promise used to return the result.|
**Example**
```
let udp = socket.constructUDPSocketInstance();
let promise = udp.bind({address:'192.168.xx.xxx', port:xxxx, family:1});
promise.then(() => {
console.log('bind success');
let promise1 = udp.setExtraOptions({
receiveBufferSize:1000,
sendBufferSize:1000,
reuseAddress:false,
socketTimeout:6000,
broadcast:true
});
promise1.then(() => {
console.log('setExtraOptions success');
}).catch(err => {
console.log('setExtraOptions fail');
});
}).catch(err => {
console.log('bind fail');
});
```
### on\('message'\)
on\(type: 'message', callback: Callback<\{message: ArrayBuffer, remoteInfo: SocketRemoteInfo\}\>\): void
Enables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | Yes | Event type. <br />**message**: message receiving event|
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | Yes | Callback used to return the result. |
**Example**
```
let udp = socket.constructUDPSocketInstance();
udp.on('message', value => {
console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
});
```
### off\('message'\)
off\(type: 'message', callback?: Callback<\{message: ArrayBuffer, remoteInfo: SocketRemoteInfo\}\>\): void
Disables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | Yes | Event type. <br />**message**: message receiving event|
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No | Callback used to return the result. |
**Example**
```
let udp = socket.constructUDPSocketInstance();
let callback = value =>{
console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
}
udp.on('message', callback);
// You can pass the callback of the on function 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');
```
### on\('listening' | 'close'\)
on\(type: 'listening' | 'close', callback: Callback<void\>\): void
Enables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type.<br>- **listening**: data packet message event<br>- **close**: close event|
| callback | Callback\<void\> | Yes | Callback used to return the result. |
**Example**
```
let udp = socket.constructUDPSocketInstance();
udp.on('listening', () => {
console.log("on listening success");
});
udp.on('close', () => {
console.log("on close success" );
});
```
### off\('listening' | 'close'\)
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.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type.<br>- **listening**: data packet message event<br>- **close**: close event|
| callback | Callback\<void\> | No | Callback used to return the result. |
**Example**
```
let udp = socket.constructUDPSocketInstance();
let callback1 = () =>{
console.log("on listening, success");
}
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.
udp.off('listening', callback1);
udp.off('listening');
let callback2 = () =>{
console.log("on close, success");
}
udp.on('close', callback2);
// You can pass the callback of the on function 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');
```
### on\('error'\)
on\(type: 'error', callback: ErrorCallback\): void
Enables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------------ |
| type | string | Yes | Event type. <br />**error**: error event|
| callback | ErrorCallback | Yes | Callback used to return the result. |
**Example**
```
let udp = socket.constructUDPSocketInstance()
udp.on('error', err => {
console.log("on error, err:" + JSON.stringify(err))
});
```
### off\('error'\)
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.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------------ |
| type | string | Yes | Event type. <br />**error**: error event|
| callback | ErrorCallback | No | Callback used to return the result. |
**Example**
```
let udp = socket.constructUDPSocketInstance()
let callback = err =>{
console.log("on error, err:" + JSON.stringify(err));
}
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.
udp.off('error', callback);
udp.off('error');
```
## NetAddress
Defines the destination address.
**System capability**: SystemCapability.Communication.NetStack
| Name | Type | Mandatory| Description |
| ------- | ------ | ---- | ------------------------------------------------------------ |
| address | string | Yes | Bound IP address. |
| port | number | No | Port number. The value ranges from **0** to **65535**. If this parameter is not specified, the system randomly allocates a port. |
| family | number | No | Network protocol type.<br>- **1**: IPv4<br>- **2**: IPv6<br>The default value is **1**.|
## UDPSendOptions
Defines the parameters for sending data over the UDPSocket connection.
**System capability**: SystemCapability.Communication.NetStack
| Name | Type | Mandatory| Description |
| ------- | ---------------------------------- | ---- | -------------- |
| data | string | Yes | Data to send. |
| address | [NetAddress](#netaddress) | Yes | Destination address.|
## UDPExtraOptions
Defines other properties of the UDPSocket connection.
**System capability**: SystemCapability.Communication.NetStack
| Name | Type | Mandatory| Description |
| ----------------- | ------- | ---- | -------------------------------- |
| broadcast | boolean | No | Whether to send broadcast messages. The default value is **false**. |
| receiveBufferSize | number | No | Size of the receive buffer, in bytes. |
| sendBufferSize | number | No | Size of the send buffer, in bytes. |
| reuseAddress | boolean | No | Whether to reuse addresses. The default value is **false**. |
| socketTimeout | number | No | Timeout duration of the UDPSocket connection, in ms.|
## SocketStateBase
Defines the status of the UDPSocket connection.
**System capability**: SystemCapability.Communication.NetStack
| Name | Type | Mandatory| Description |
| ----------- | ------- | ---- | ---------- |
| isBound | boolean | Yes | Whether the connection is in the bound state.|
| isClose | boolean | Yes | Whether the connection is in the closed state.|
| isConnected | boolean | Yes | Whether the connection is in the connected state.|
## SocketRemoteInfo
Defines information about the UDPSocket connection.
**System capability**: SystemCapability.Communication.NetStack
| Name | Type | Mandatory| Description |
| ------- | ------ | ---- | ------------------------------------------------------------ |
| address | string | Yes | Bound IP address. |
| family | string | Yes | Network protocol type.<br>- IPv4<br>- IPv6<br>The default value is **IPv4**.|
| port | number | Yes | Port number. The value ranges from **0** to **65535**. |
| size | number | Yes | Length of the server response message, in bytes. |
## socket.constructTCPSocketInstance
constructTCPSocketInstance\(\): TCPSocket
Creates a **TCPSocket** object.
**System capability**: SystemCapability.Communication.NetStack
**Return Value**
| Type | Description |
| :--------------------------------- | :---------------------- |
| [TCPSocket](#tcpsocket) | **TCPSocket** object.|
**Example**
```
let tcp = socket.constructTCPSocketInstance();
```
## TCPSocket
Defines a TCPSocket connection. Before invoking TCPSocket APIs, you need to call [socket.constructTCPSocketInstance](#socketconstructtcpsocketinstance) to create a **TCPSocket** object.
### bind
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.
**Required permission**: 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. |
**Example**
```
let tcp = socket.constructTCPSocketInstance();
tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
})
```
### bind
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.
**Required permission**: 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.|
**Example**
```
let tcp = socket.constructTCPSocketInstance();
let promise = tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1});
promise.then(() => {
console.log('bind success');
}).catch(err => {
console.log('bind fail');
});
```
### connect
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.
**Required permission**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPConnectOptions](#tcpconnectoptions) | Yes | TCPSocket connection parameters. For details, see [TCPConnectOptions](#tcpconnectoptions).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
**Example**
```
let tcp = socket.constructTCPSocketInstance();
tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}, err => {
if (err) {
console.log('connect fail');
return;
}
console.log('connect success');
})
```
### connect
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.
**Required permission**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPConnectOptions](#tcpconnectoptions) | Yes | TCPSocket connection parameters. For details, see [TCPConnectOptions](#tcpconnectoptions).|
**Return Value**
| Type | Description |
| :-------------- | :--------------------------------------------------------- |
| Promise\<void\> | Promise used to return the result.|
**Example**
```
let tcp = socket.constructTCPSocketInstance();
let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000});
promise.then(() => {
console.log('connect success')
}).catch(err => {
console.log('connect fail');
});
```
### send
send\(options: TCPSendOptions, callback: AsyncCallback<void\>\): void
Sends data over a TCPSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>This API can be called only after [connect](#connect) is successfully called.
**Required permission**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPSendOptions](#tcpsendoptions) | Yes | Parameters for sending data over the TCPSocket connection. For details, see [TCPSendOptions](#tcpsendoptions).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
**Example**
```
let tcp = socket.constructTCPSocketInstance();
let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000});
promise.then(() => {
console.log('connect success');
tcp.send({
data:'Hello, server!'
},err => {
if (err) {
console.log('send fail');
return;
}
console.log('send success');
})
}).catch(err => {
console.log('connect fail');
});
```
### send
send\(options: TCPSendOptions\): Promise<void\>
Sends data over a TCPSocket connection. This API uses a promise to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>This API can be called only after [connect](#connect) is successfully called.
**Required permission**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPSendOptions](#tcpsendoptions) | Yes | Parameters for sending data over the TCPSocket connection. For details, see [TCPSendOptions](#tcpsendoptions).|
**Return Value**
| Type | Description |
| :-------------- | :------------------------------------------------- |
| Promise\<void\> | Promise used to return the result.|
**Example**
```
let tcp = socket.constructTCPSocketInstance();
let promise1 = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000});
promise1.then(() => {
console.log('connect success');
let promise2 = tcp.send({
data:'Hello, server!'
});
promise2.then(() => {
console.log('send success');
}).catch(err => {
console.log('send fail');
});
}).catch(err => {
console.log('connect fail');
});
```
### close
close\(callback: AsyncCallback<void\>\): void
Closes a TCPSocket connection. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ---------- |
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.|
**Example**
```
let tcp = socket.constructTCPSocketInstance();
tcp.close(err => {
if (err) {
console.log('close fail');
return;
}
console.log('close success');
})
```
### close
close\(\): Promise<void\>
Closes a TCPSocket connection. This API uses a promise to return the result.
**Required permission**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Return Value**
| Type | Description |
| :-------------- | :----------------------------------------- |
| Promise\<void\> | Promise used to return the result.|
**Example**
```
let tcp = socket.constructTCPSocketInstance();
let promise = tcp.close();
promise.then(() => {
console.log('close success');
}).catch(err => {
console.log('close fail');
});
```
### getRemoteAddress
getRemoteAddress\(callback: AsyncCallback<NetAddress\>\): void
Obtains the remote address of a TCPSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>This API can be called only after [connect](#connect) is successfully called.
**Required permission**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------- | ---- | ---------- |
| callback | AsyncCallback<[NetAddress](#netaddress)> | Yes | Callback used to return the result.|
**Example**
```
let tcp = socket.constructTCPSocketInstance();
let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000});
promise.then(() => {
console.log('connect success');
tcp.getRemoteAddress((err, data) => {
if (err) {
console.log('getRemoteAddressfail');
return;
}
console.log('getRemoteAddresssuccess:' + JSON.stringify(data));
})
}).catch(err => {
console.log('connect fail');
});
```
### getRemoteAddress
getRemoteAddress\(\): Promise<NetAddress\>
Obtains the remote address of a TCPSocket connection. This API uses a promise to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>This API can be called only after [connect](#connect) is successfully called.
**Required permission**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Return Value**
| Type | Description |
| :------------------------------------------ | :------------------------------------------ |
| Promise<[NetAddress](#netaddress)> | Promise used to return the result.|
**Example**
```
let tcp = socket.constructTCPSocketInstance();
let promise1 = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000});
promise1.then(() => {
console.log('connect success');
let promise2 = tcp.getRemoteAddress();
promise2.then(() => {
console.log('getRemoteAddress success:' + JSON.stringify(data));
}).catch(err => {
console.log('getRemoteAddressfail');
});
}).catch(err => {
console.log('connect fail');
});
```
### getState
getState\(callback: AsyncCallback<SocketStateBase\>\): void
Obtains the status of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called.
**Required permission**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------ | ---- | ---------- |
| callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | Yes | Callback used to return the result.|
**Example**
```
let tcp = socket.constructTCPSocketInstance();
let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000});
promise.then(() => {
console.log('connect success');
tcp.getState((err, data) => {
if (err) {
console.log('getState fail');
return;
}
console.log('getState success:' + JSON.stringify(data));
});
}).catch(err => {
console.log('connect fail');
});
```
### getState
getState\(\): Promise<SocketStateBase\>
Obtains the status of the TCPSocket connection. This API uses a promise to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called.
**Required permission**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Return Value**
| Type | Description |
| :----------------------------------------------- | :----------------------------------------- |
| Promise<[SocketStateBase](#socketstatebase)> | Promise used to return the result.|
**Example**
```
let tcp = socket.constructTCPSocketInstance();
let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000});
promise.then(() => {
console.log('connect success');
let promise1 = tcp.getState();
promise1.then(() => {
console.log('getState success:' + JSON.stringify(data));
}).catch(err => {
console.log('getState fail');
});
}).catch(err => {
console.log('connect fail');
});
```
### setExtraOptions
setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback<void\>\): void
Sets other properties of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called.
**Required permission**: ohos.permission.INTERNET
**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. |
**Example**
```
let tcp = socket.constructTCPSocketInstance();
let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000});
promise.then(() => {
console.log('connect success');
tcp.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');
});
}).catch(err => {
console.log('connect fail');
});
```
### setExtraOptions
setExtraOptions\(options: TCPExtraOptions\): Promise<void\>
Sets other properties of the TCPSocket connection. This API uses a promise to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called.
**Required permission**: ohos.permission.INTERNET
**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.|
**Example**
```
let tcp = socket.constructTCPSocketInstance();
let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000});
promise.then(() => {
console.log('connect success');
let promise1 = tcp.setExtraOptions({
keepAlive: true,
OOBInline: true,
TCPNoDelay: true,
socketLinger: { on:true, linger:10 },
receiveBufferSize: 1000,
sendBufferSize: 1000,
reuseAddress: true,
socketTimeout: 3000,
});
promise1.then(() => {
console.log('setExtraOptions success');
}).catch(err => {
console.log('setExtraOptions fail');
});
}).catch(err => {
console.log('connect fail');
});
```
### on\('message'\)
on\(type: 'message', callback: Callback<\{message: ArrayBuffer, remoteInfo: SocketRemoteInfo\}\>\): void
Enables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | Yes | Event type. <br />**message**: message receiving event|
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | Yes | Callback used to return the result. |
**Example**
```
let tcp = socket.constructTCPSocketInstance();
tcp.on('message', value => {
console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo)
});
```
### off\('message'\)
off\(type: 'message', callback?: Callback<\{message: ArrayBuffer, remoteInfo: SocketRemoteInfo\}\>\): void
Disables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | Yes | Event type. <br />**message**: message receiving event|
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No | Callback used to return the result. |
**Example**
```
let tcp = socket.constructTCPSocketInstance();
let callback = value =>{
console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
}
tcp.on('message', callback);
// You can pass the callback of the on function 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');
```
### on\('connect' | 'close'\)
on\(type: 'connect' | 'close', callback: Callback<void\>\): void
Enables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type.<br>- **connect**: connection event<br>- **close**: close event|
| callback | Callback\<void\> | Yes | Callback used to return the result. |
**Example**
```
let tcp = socket.constructTCPSocketInstance();
tcp.on('connect', () => {
console.log("on connect success")
});
tcp.on('close', data => {
console.log("on close success")
});
```
### off\('connect' | 'close'\)
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.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type.<br>- **connect**: connection event<br>- **close**: close event|
| callback | Callback\<void\> | No | Callback used to return the result. |
**Example**
```
let tcp = socket.constructTCPSocketInstance();
let callback1 = () =>{
console.log("on connect success");
}
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.
tcp.off('connect', callback1);
tcp.off('connect');
let callback2 = () =>{
console.log("on close success");
}
tcp.on('close', callback2);
// You can pass the callback of the on function 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');
```
### on\('error'\)
on\(type: 'error', callback: ErrorCallback\): void
Enables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------------ |
| type | string | Yes | Event type. <br />**error**: error event|
| callback | ErrorCallback | Yes | Callback used to return the result. |
**Example**
```
let tcp = socket.constructTCPSocketInstance();
tcp.on('error', err => {
console.log("on error, err:" + JSON.stringify(err))
});
```
### off\('error'\)
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.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------------ |
| type | string | Yes | Event type. <br />**error**: error event|
| callback | ErrorCallback | No | Callback used to return the result. |
**Example**
```
let tcp = socket.constructTCPSocketInstance();
let callback = err =>{
console.log("on error, err:" + JSON.stringify(err));
}
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.
tcp.off('error', callback);
tcp.off('error');
```
## TCPConnectOptions
Defines TCPSocket connection parameters.
**System capability**: SystemCapability.Communication.NetStack
| Name | Type | Mandatory| Description |
| ------- | ---------------------------------- | ---- | -------------------------- |
| address | [NetAddress](#netaddress) | Yes | Bound IP address and port number. |
| timeout | number | No | Timeout duration of the TCPSocket connection, in ms.|
## TCPSendOptions
Defines the parameters for sending data over the TCPSocket connection.
**System capability**: SystemCapability.Communication.NetStack
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ |
| data | string | 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**.|
## TCPExtraOptions
Defines other properties of the TCPSocket connection.
**System capability**: SystemCapability.Communication.NetStack
| Name | Type | Mandatory| Description |
| ----------------- | ------- | ---- | ------------------------------------------------------------ |
| keepAlive | boolean | No | Whether to keep the connection alive. The default value is **false**. |
| OOBInline | boolean | No | Whether to enable OOBInline. The default value is **false**. |
| TCPNoDelay | boolean | No | Whether to enable no-delay on the TCPSocket connection. The default value is **false**. |
| socketLinger | Object | Yes | Socket linger.<br>- **on**: whether to enable socket linger. The value true means to enable socket linger and false means the opposite.<br>- **linger**: linger time, in ms. The value ranges from **0** to **65535**.<br>Specify this parameter only when **on** is set to **true**.|
| receiveBufferSize | number | No | Size of the receive buffer, in bytes. |
| sendBufferSize | number | No | Size of the send buffer, in bytes. |
| reuseAddress | boolean | No | Whether to reuse addresses. The default value is **false**. |
| socketTimeout | number | No | Timeout duration of the TCPSocket connection, in ms. |
# WebSocket
>![](public_sys-resources/icon-note.gif) **NOTE:**
>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
>Newly added APIs are defined but not implemented in OpenHarmony 3.1 Release. They will be available for use in OpenHarmony 3.1 MR.
You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the [createWebSocket](#websocketcreatewebsocket) API to create a [WebSocket](#websocket) object and then use the [connect](#connect) API to connect to the server. If the connection is successful, the client will receive a callback of the [open](#onopen) event. Then, the client can communicate with the server using the [send](#send) API. When the server sends a message to the client, the client will receive a callback of the [message](#onmessage) event. If the client no longer needs this connection, it can call the [close](#close) API to disconnect from the server. Then, the client will receive a callback of the [close](#onclose) event.
If an error occurs in any of the preceding processes, the client will receive a callback of the [error](#onerror) event.
## Modules to Import
```
import webSocket from '@ohos.net.webSocket';
```
## Complete Example
```
import webSocket from '@ohos.net.webSocket';
var defaultIpAddress = "ws://";
let ws = webSocket.createWebSocket();
ws.on('open', (err, value) => {
console.log("on open, status:" + value.status + ", message:" + value.message);
// When receiving the on('open') event, the client can use the send() API to communicate with the server.
ws.send("Hello, server!", (err, value) => {
if (!err) {
console.log("send success");
} else {
console.log("send fail, err:" + JSON.stringify(err));
}
});
});
ws.on('message', (err, value) => {
console.log("on message, message:" + value);
// When receiving the bye message (the actual message name may differ) from the server, the client proactively disconnects from the server.
if (value === 'bye') {
ws.close((err, value) => {
if (!err) {
console.log("close success");
} else {
console.log("close fail, err is " + JSON.stringify(err));
}
});
}
});
ws.on('close', (err, value) => {
console.log("on close, code is " + value.code + ", reason is " + value.reason);
});
ws.on('error', (err) => {
console.log("on error, error:" + JSON.stringify(err));
});
ws.connect(defaultIpAddress, (err, value) => {
if (!err) {
console.log("connect success");
} else {
console.log("connect fail, err:" + JSON.stringify(err));
}
});
```
## webSocket.createWebSocket
createWebSocket\(\): WebSocket
Creates a WebSocket connection. You can use this API to create or close a WebSocket connection, send data over it, or enable or disable listening for the **open**, **close**, **message**, and **error** events.
**System capability**: SystemCapability.Communication.NetStack
**Return Value**
| Type | Description |
| :---------------------------------- | :----------------------------------------------------------- |
| [WebSocket](#websocket) | A **WebSocket** object, which contains the **connect**, **send**, **close**, **on**, or **off** method.|
**Example**
```
let ws = webSocket.createWebSocket();
```
## WebSocket
Defines a **WebSocket** object. Before invoking WebSocket APIs, you need to call [webSocket.createWebSocket](#webSocketcreatewebsocket) to create a **WebSocket** object.
### connect
connect\(url: string, callback: AsyncCallback<boolean\>\): void
Initiates a WebSocket request to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------ | ---- | ---------------------------- |
| url | string | Yes | URL for establishing a WebSocket connection.|
| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result. |
**Example**
```
let ws = webSocket.createWebSocket();
let url = "ws://"
ws.connect(url, (err, value) => {
if (!err) {
console.log("connect success");
} else {
console.log("connect fail, err:" + JSON.stringify(err))
}
});
```
### connect
connect\(url: string, options: WebSocketRequestOptions, callback: AsyncCallback<boolean\>\): void
Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------ | ---- | ------------------------------------------------------- |
| url | string | Yes | URL for establishing a WebSocket connection. |
| options | WebSocketRequestOptions | Yes | Request options. For details, see [WebSocketRequestOptions](#websocketrequestoptions).|
| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result. |
**Example**
```
let ws = webSocket.createWebSocket();
let url = "ws://"
ws.connect(url, {
header: {
"key": "value",
"key2": "value2"
}
}, (err, value) => {
if (!err) {
console.log("connect success");
} else {
console.log("connect fail, err:" + JSON.stringify(err))
}
});
```
### connect
connect\(url: string, options?: WebSocketRequestOptions\): Promise<boolean\>
Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses a promise to return the result.
**Required permission**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ----------------------- | ---- | ------------------------------------------------------- |
| url | string | Yes | URL for establishing a WebSocket connection. |
| options | WebSocketRequestOptions | No | Request options. For details, see [WebSocketRequestOptions](#websocketrequestoptions).|
**Return Value**
| Type | Description |
| :----------------- | :-------------------------------- |
| Promise\<boolean\> | Promise used to return the result.|
**Example**
```
let ws = webSocket.createWebSocket();
let url = "ws://"
let promise = ws.connect(url);
promise.then((value) => {
console.log("connect success")
}).catch((err) => {
console.log("connect fail, error:" + JSON.stringify(err))
});
```
### send
send\(data: string | ArrayBuffer, callback: AsyncCallback<boolean\>\): void
Sends data through a WebSocket connection. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------ | ---- | ------------ |
| data | string \| ArrayBuffer <sup>8+</sup> | Yes | Data to send.|
| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result. |
**Example**
```
let ws = webSocket.createWebSocket();
let url = "ws://"
ws.connect(url, (err, value) => {
ws.send("Hello, server!", (err, value) => {
if (!err) {
console.log("send success");
} else {
console.log("send fail, err:" + JSON.stringify(err))
}
});
});
```
### send
send\(data: string | ArrayBuffer\): Promise<boolean\>
Sends data through a WebSocket connection. This API uses a promise to return the result.
**Required permission**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------ |
| data | string \| ArrayBuffer <sup>8+</sup> | Yes | Data to send.|
**Return Value**
| Type | Description |
| :----------------- | :-------------------------------- |
| Promise\<boolean\> | Promise used to return the result.|
**Example**
```
let ws = webSocket.createWebSocket();
let url = "ws://"
ws.connect(url, (err, value) => {
let promise = ws.send("Hello, server!");
promise.then((value) => {
console.log("send success")
}).catch((err) => {
console.log("send fail, error:" + JSON.stringify(err))
});
});
```
### close
close\(callback: AsyncCallback<boolean\>\): void
Closes a WebSocket connection. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------ | ---- | ---------- |
| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result.|
**Example**
```
let ws = webSocket.createWebSocket();
let url = "ws://"
ws.close((err, value) => {
if (!err) {
console.log("close success")
} else {
console.log("close fail, err is " + JSON.stringify(err))
}
});
```
### close
close\(options: WebSocketCloseOptions, callback: AsyncCallback<boolean\>\): void
Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------ | ---- | ----------------------------------------------------- |
| options | WebSocketCloseOptions | Yes | Request options. For details, see [WebSocketCloseOptions](#websocketcloseoptions).|
| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result. |
**Example**
```
let ws = webSocket.createWebSocket();
let url = "ws://"
ws.close({
code: 1000,
reason: "your reason"
}, (err, value) => {
if (!err) {
console.log("close success")
} else {
console.log("close fail, err is " + JSON.stringify(err))
}
});
```
### close
close\(options?: WebSocketCloseOptions\): Promise<boolean\>
Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses a promise to return the result.
**Required permission**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | --------------------- | ---- | ----------------------------------------------------- |
| options | WebSocketCloseOptions | No | Request options. For details, see [WebSocketCloseOptions](#websocketcloseoptions).|
**Return Value**
| Type | Description |
| :----------------- | :-------------------------------- |
| Promise\<boolean\> | Promise used to return the result.|
**Example**
```
let ws = webSocket.createWebSocket();
let url = "ws://"
let promise = ws.close({
code: 1000,
reason: "your reason"
});
promise.then((value) => {
console.log("close success")
}).catch((err) => {
console.log("close fail, err is " + JSON.stringify(err))
});
```
### on\('open'\)
on\(type: 'open', callback: AsyncCallback<Object\>\): void
Enables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | ----------------------------- |
| type | string | Yes | Event type. <br />**open**: event indicating that a WebSocket connection has been opened.|
| callback | AsyncCallback\<Object\> | Yes | Callback used to return the result. |
**Example**
```
let ws = webSocket.createWebSocket();
ws.on('open', (err, value) => {
console.log("on open, status:" + value.status + ", message:" + value.message);
});
```
### off\('open'\)
off\(type: 'open', callback?: AsyncCallback<Object\>\): void
Disables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | ----------------------------- |
| type | string | Yes | Event type. <br />**open**: event indicating that a WebSocket connection has been opened.|
| callback | AsyncCallback\<Object\> | No | Callback used to return the result. |
**Example**
```
let ws = webSocket.createWebSocket();
let callback1 = (err, value) => {
console.log("on open, status:" + value.status + ", message:" + value.message);
}
ws.on('open', callback1);
// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
ws.off('open', callback1);
```
### on\('message'\)
on\(type: 'message', callback: AsyncCallback<string | ArrayBuffer\>\): void
Enables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\).
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------------- |
| type | string | Yes | Event type.<br />**message**: event indicating that a message has been received from the server.|
| callback | AsyncCallback\<string \| ArrayBuffer <sup>8+</sup>\> | Yes | Callback used to return the result. |
**Example**
```
let ws = webSocket.createWebSocket();
ws.on('message', (err, value) => {
console.log("on message, message:" + value);
});
```
### off\('message'\)
off\(type: 'message', callback?: AsyncCallback<string | ArrayBuffer\>\): void
Disables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\).
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------------------- | ---- | -------------------------------------------- |
| type | string | Yes | Event type.<br />**message**: event indicating that a message has been received from the server.|
| callback | AsyncCallback\<string \|ArrayBuffer <sup>8+</sup>\> | No | Callback used to return the result. |
**Example**
```
let ws = webSocket.createWebSocket();
ws.off('message');
```
### on\('close'\)
on\(type: 'close', callback: AsyncCallback<\{ code: number, reason: string \}\>\): void
Enables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------- | ---- | ------------------------------ |
| type | string | Yes | Event type. <br />**close**: event indicating that a WebSocket connection has been closed.|
| callback | AsyncCallback<{ code: number, reason: string }> | Yes | Callback used to return the result. |
**Example**
```
let ws = webSocket.createWebSocket();
ws.on('close', (err, value) => {
console.log("on close, code is " + value.code + ", reason is " + value.reason);
});
```
### off\('close'\)
off\(type: 'close', callback?: AsyncCallback<\{ code: number, reason: string \}\>\): void
Disables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------- | ---- | ------------------------------ |
| type | string | Yes | Event type. <br />**close**: event indicating that a WebSocket connection has been closed.|
| callback | AsyncCallback<{ code: number, reason: string }> | No | Callback used to return the result. |
**Example**
```
let ws = webSocket.createWebSocket();
ws.off('close');
```
### on\('error'\)
on\(type: 'error', callback: ErrorCallback\): void
Enables listening for the **error** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------- |
| type | string | Yes | Event type.<br />**error**: event indicating the WebSocket connection has encountered an error.|
| callback | ErrorCallback | Yes | Callback used to return the result. |
**Example**
```
let ws = webSocket.createWebSocket();
ws.on('error', (err) => {
console.log("on error, error:" + JSON.stringify(err))
});
```
### off\('error'\)
off\(type: 'error', callback?: ErrorCallback\): void
Disables listening for the **error** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------- |
| type | string | Yes | Event type.<br />**error**: event indicating the WebSocket connection has encountered an error.|
| callback | ErrorCallback | No | Callback used to return the result. |
**Example**
```
let ws = webSocket.createWebSocket();
ws.off('error');
```
## WebSocketRequestOptions
Defines the optional parameters carried in the request for establishing a WebSocket connection.
**System capability**: SystemCapability.Communication.NetStack
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| header | Object | No | Header carrying optional parameters in the request for establishing a WebSocket connection. You can customize the parameter or leave it unspecified.|
## WebSocketCloseOptions
Defines the optional parameters carried in the request for closing a WebSocket connection.
**System capability**: SystemCapability.Communication.NetStack
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| code | number | No | Error code. Set this parameter based on the actual situation. The default value is **1000**.|
| reason | string | No | Error cause. Set this parameter based on the actual situation. The default value is an empty string ("").|
## Result Codes for Closing a WebSocket Connection
You can customize the result codes sent to the server. The result codes in the following table are for reference only.
**System capability**: SystemCapability.Communication.NetStack
| Value | Description |
| :-------- | :----------------- |
| 1000 | Normally closed |
| 1001 | Connection closed by the server |
| 1002 | Incorrect protocol |
| 1003 | Data unable to be processed|
| 1004~1015 | Reserved |
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册