“5fafbed13f1be78f7b2768b40783a26ed33449ff”上不存在“git@gitcode.net:openanolis/dragonwell8_jdk.git”
提交 4e104f11 编写于 作者: Y Yangys

Update ErrroCode

Signed-off-by: NYangys <yangyousheng@huawei.com>
上级 84076318
# @ohos.net.http (数据请求)
本模块提供HTTP数据请求能力。应用可以通过HTTP发起一个数据请求,支持常见的GET、POST、OPTIONS、HEAD、PUT、DELETE、TRACE、CONNECT方法。
>**说明:**
>
>本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
>
## 导入模块
```js
import http from '@ohos.net.http';
```
## 完整示例
```js
import http from '@ohos.net.http';
// 每一个httpRequest对应一个HTTP请求任务,不可复用
let httpRequest = http.createHttp();
// 用于订阅HTTP响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息
// 从API 8开始,使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+
httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header));
});
httpRequest.request(
// 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定
"EXAMPLE_URL",
{
method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET
// 开发者根据自身业务需要添加header字段
header: {
'Content-Type': 'application/json'
},
// 当使用POST请求时此字段用于传递内容
extraData: {
"data": "data to send",
},
expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型
usingCache: true, // 可选,默认为true
priority: 1, // 可选,默认为1
connectTimeout: 60000, // 可选,默认为60000ms
readTimeout: 60000, // 可选,默认为60000ms
usingProtocol: http.HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定
}, (err, data) => {
if (!err) {
// data.result为HTTP响应内容,可根据业务需要进行解析
console.info('Result:' + data.result);
console.info('code:' + data.responseCode);
// data.header为HTTP响应头,可根据业务需要进行解析
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + data.cookies); // 8+
} else {
console.info('error:' + JSON.stringify(err));
// 当该请求使用完毕时,调用destroy方法主动销毁。
httpRequest.destroy();
}
}
);
```
## http.createHttp
createHttp\(\): HttpRequest
创建一个HTTP请求,里面包括发起请求、中断请求、订阅/取消订阅HTTP Response Header事件。每一个HttpRequest对象对应一个HTTP请求。如需发起多个HTTP请求,须为每个HTTP请求创建对应HttpRequest对象。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :---------- | :----------------------------------------------------------- |
| HttpRequest | 返回一个HttpRequest对象,里面包括request、destroy、on和off方法。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2100002 | System internal error. |
| 2300999 | Unknown Other Error |
以上错误码的详细介绍参见[HTTP错误码](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/errorcodes/errorcode-http.md)
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
import http from '@ohos.net.http';
let httpRequest = http.createHttp();
```
## HttpRequest
HTTP请求任务。在调用HttpRequest的方法前,需要先通过[createHttp\(\)](#httpcreatehttp)创建一个任务。
### request
request\(url: string, callback: AsyncCallback\<HttpResponse\>\):void
根据URL地址,发起HTTP网络请求,使用callback方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------------- | ---- | ----------------------- |
| url | string | 是 | 发起网络请求的URL地址。 |
| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300003 | URL using bad/illegal format or missing URL |
| 2300005 | Couldn't resolve proxy name |
| 2300006 | Couldn't resolve host name |
| 2300007 | Couldn't connect to server |
| 2300052 | Server returned nothing (no headers, no data) |
| 2300999 | Unknown Other Error |
以上错误码的详细介绍参见[HTTP错误码](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/errorcodes/errorcode-http.md)
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
httpRequest.request("EXAMPLE_URL", (err, data) => {
if (!err) {
console.info('Result:' + data.result);
console.info('code:' + data.responseCode);
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + data.cookies); // 8+
} else {
console.info('error:' + JSON.stringify(err));
}
});
```
### request
request\(url: string, options: HttpRequestOptions, callback: AsyncCallback<HttpResponse\>\):void
根据URL地址和相关配置项,发起HTTP网络请求,使用callback方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- |
| url | string | 是 | 发起网络请求的URL地址。 |
| options | HttpRequestOptions | 是 | 参考[HttpRequestOptions](#httprequestoptions)。 |
| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300003 | URL using bad/illegal format or missing URL |
| 2300005 | Couldn't resolve proxy name |
| 2300006 | Couldn't resolve host name |
| 2300007 | Couldn't connect to server |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300999 | Unknown Other Error |
以上错误码的详细介绍参见[HTTP错误码](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/errorcodes/errorcode-http.md)
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
httpRequest.request("EXAMPLE_URL",
{
method: http.RequestMethod.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:' + JSON.stringify(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']);
} else {
console.info('error:' + JSON.stringify(err));
}
});
```
### request
request\(url: string, options? : HttpRequestOptions\): Promise<HttpResponse\>
根据URL地址,发起HTTP网络请求,使用Promise方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------------------ | ---- | ----------------------------------------------- |
| url | string | 是 | 发起网络请求的URL地址。 |
| options | HttpRequestOptions | 否 | 参考[HttpRequestOptions](#httprequestoptions)。 |
**返回值:**
| 类型 | 说明 |
| :------------------------------------- | :-------------------------------- |
| Promise<[HttpResponse](#httpresponse)> | 以Promise形式返回发起请求的结果。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300003 | URL using bad/illegal format or missing URL |
| 2300005 | Couldn't resolve proxy name |
| 2300006 | Couldn't resolve host name |
| 2300007 | Couldn't connect to server |
| 2300009 | Access denied to remote resource |
| 2300999 | Unknown Other Error |
以上错误码的详细介绍参见[HTTP错误码](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/errorcodes/errorcode-http.md)
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
let promise = httpRequest.request("EXAMPLE_URL", {
method: http.RequestMethod.GET,
connectTimeout: 60000,
readTimeout: 60000,
header: {
'Content-Type': 'application/json'
}
});
promise.then((data) => {
console.info('Result:' + data.result);
console.info('code:' + data.responseCode);
console.info('header:' + JSON.stringify(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']);
}).catch((err) => {
console.info('error:' + JSON.stringify(err));
});
```
### destroy
destroy\(\): void
中断请求任务。
**系统能力**:SystemCapability.Communication.NetStack
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300999 | Unknown Other Error |
以上错误码的详细介绍参见[HTTP错误码](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/errorcodes/errorcode-http.md)
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
httpRequest.destroy();
```
### on\('headerReceive'\)
on\(type: 'headerReceive', callback: AsyncCallback<Object\>\): void
订阅HTTP Response Header 事件。
>![](public_sys-resources/icon-note.gif) **说明:**
>此接口已废弃,建议使用[on\('headersReceive'\)<sup>8+</sup>](#onheadersreceive8)替代。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------- | ---- | --------------------------------- |
| type | string | 是 | 订阅的事件类型,'headerReceive'。 |
| callback | AsyncCallback\<Object\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300003 | URL using bad/illegal format or missing URL |
| 2300005 | Couldn't resolve proxy name |
| 2300006 | Couldn't resolve host name |
| 2300007 | Couldn't connect to server |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300023 | Failed writing received data to disk/application |
| 2300025 | Upload failed |
| 2300027 | Out of memory |
| 2300028 | Timeout was reached |
| 2300052 | Server returned nothing (no headers, no data) |
| 2300056 | Failure when receiving data from the peer |
| 2300058 | Problem with the local SSL certificate |
| 2300060 | SSL peer certificate or SSH remote key was not OK |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding |
| 2300063 | Maximum file size exceeded |
| 2300070 | Disk full or allocation exceeded |
| 2300077 | Problem with the SSL CA cert (path? access rights?) |
| 2300078 | Remote file not found |
| 2300999 | Unknown Other Error |
以上错误码的详细介绍参见[HTTP错误码](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/errorcodes/errorcode-http.md)
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
httpRequest.on('headerReceive', (err, data) => {
if (!err) {
console.info('header: ' + JSON.stringify(data));
} else {
console.info('error:' + JSON.stringify(err));
}
});
```
### off\('headerReceive'\)
off\(type: 'headerReceive', callback?: AsyncCallback<Object\>\): void
取消订阅HTTP Response Header 事件。
>![](public_sys-resources/icon-note.gif) **说明:**
>
>1. 此接口已废弃,建议使用[off\('headersReceive'\)<sup>8+</sup>](#offheadersreceive8)替代。
>
>2. 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------- | ---- | ------------------------------------- |
| type | string | 是 | 取消订阅的事件类型,'headerReceive'。 |
| callback | AsyncCallback\<Object\> | 否 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300003 | URL using bad/illegal format or missing URL |
| 2300005 | Couldn't resolve proxy name |
| 2300006 | Couldn't resolve host name |
| 2300007 | Couldn't connect to server |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300999 | Unknown Other Error |
以上错误码的详细介绍参见[HTTP错误码](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/errorcodes/errorcode-http.md)
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
httpRequest.off('headerReceive');
```
### on\('headersReceive'\)<sup>8+</sup>
on\(type: 'headersReceive', callback: Callback<Object\>\): void
订阅HTTP Response Header 事件。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------ | ---- | ---------------------------------- |
| type | string | 是 | 订阅的事件类型:'headersReceive'。 |
| callback | Callback\<Object\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300003 | URL using bad/illegal format or missing URL |
| 2300005 | Couldn't resolve proxy name |
| 2300006 | Couldn't resolve host name |
| 2300007 | Couldn't connect to server |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300023 | Failed writing received data to disk/application |
| 2300025 | Upload failed |
| 2300027 | Out of memory |
| 2300028 | Timeout was reached |
| 2300052 | Server returned nothing (no headers, no data) |
| 2300056 | Failure when receiving data from the peer |
| 2300058 | Problem with the local SSL certificate |
| 2300060 | SSL peer certificate or SSH remote key was not OK |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding |
| 2300063 | Maximum file size exceeded |
| 2300070 | Disk full or allocation exceeded |
| 2300077 | Problem with the SSL CA cert (path? access rights?) |
| 2300078 | Remote file not found |
| 2300999 | Unknown Other Error |
以上错误码的详细介绍参见[HTTP错误码](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/errorcodes/errorcode-http.md)
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header));
});
```
### off\('headersReceive'\)<sup>8+</sup>
off\(type: 'headersReceive', callback?: Callback<Object\>\): void
取消订阅HTTP Response Header 事件。
>![](public_sys-resources/icon-note.gif) **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------ | ---- | -------------------------------------- |
| type | string | 是 | 取消订阅的事件类型:'headersReceive'。 |
| callback | Callback\<Object\> | 否 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300003 | URL using bad/illegal format or missing URL |
| 2300005 | Couldn't resolve proxy name |
| 2300006 | Couldn't resolve host name |
| 2300007 | Couldn't connect to server |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300999 | Unknown Other Error |
以上错误码的详细介绍参见[HTTP错误码](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/errorcodes/errorcode-http.md)
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
httpRequest.off('headersReceive');
```
### once\('headersReceive'\)<sup>8+</sup>
once\(type: 'headersReceive', callback: Callback<Object\>\): void
订阅HTTP Response Header 事件,但是只触发一次。一旦触发之后,订阅器就会被移除。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------ | ---- | ---------------------------------- |
| type | string | 是 | 订阅的事件类型:'headersReceive'。 |
| callback | Callback\<Object\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300003 | URL using bad/illegal format or missing URL |
| 2300005 | Couldn't resolve proxy name |
| 2300006 | Couldn't resolve host name |
| 2300007 | Couldn't connect to server |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300023 | Failed writing received data to disk/application |
| 2300025 | Upload failed |
| 2300027 | Out of memory |
| 2300028 | Timeout was reached |
| 2300052 | Server returned nothing (no headers, no data) |
| 2300056 | Failure when receiving data from the peer |
| 2300058 | Problem with the local SSL certificate |
| 2300060 | SSL peer certificate or SSH remote key was not OK |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding |
| 2300063 | Maximum file size exceeded |
| 2300070 | Disk full or allocation exceeded |
| 2300077 | Problem with the SSL CA cert (path? access rights?) |
| 2300078 | Remote file not found |
| 2300999 | Unknown Other Error |
以上错误码的详细介绍参见[HTTP错误码](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/errorcodes/errorcode-http.md)
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
httpRequest.once('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header));
});
```
## HttpRequestOptions
发起请求可选参数的类型和取值范围。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
| method | [RequestMethod](#requestmethod) | 否 | 请求方式。 |
| extraData | string \| Object \| ArrayBuffer<sup>6+</sup> | 否 | 发送请求的额外数据。<br />- 当HTTP请求为POST、PUT等方法时,此字段为HTTP请求的content。<br />- 当HTTP请求为GET、OPTIONS、DELETE、TRACE、CONNECT等方法时,此字段为HTTP请求的参数补充,参数内容会拼接到URL中进行发送。<sup>6+</sup><br />- 开发者传入string对象,开发者需要自行编码,将编码后的string传入。<sup>6+</sup> |
| expectDataType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | 否 | 指定返回数据的类型。如果设置了此参数,系统将优先返回指定的类型。 |
| usingCache<sup>9+</sup> | boolean | 否 | 是否使用缓存,默认为true。 |
| priority<sup>9+</sup> | number | 否 | 优先级,范围\[1,1000],默认是1。 |
| header | Object | 否 | HTTP请求头字段。默认{'Content-Type': 'application/json'}。 |
| readTimeout | number | 否 | 读取超时时间。单位为毫秒(ms),默认为60000ms。 |
| connectTimeout | number | 否 | 连接超时时间。单位为毫秒(ms),默认为60000ms。 |
| usingProtocol<sup>9+</sup> | [HttpProtocol](#httpprotocol9) | 否 | 使用协议。默认值由系统自动指定。 |
## RequestMethod
HTTP 请求方法。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 值 | 说明 |
| :------ | ------- | :------------------ |
| OPTIONS | "OPTIONS" | HTTP 请求 OPTIONS。 |
| GET | "GET" | HTTP 请求 GET。 |
| HEAD | "HEAD" | HTTP 请求 HEAD。 |
| POST | "POST" | HTTP 请求 POST。 |
| PUT | "PUT" | HTTP 请求 PUT。 |
| DELETE | "DELETE" | HTTP 请求 DELETE。 |
| TRACE | "TRACE" | HTTP 请求 TRACE。 |
| CONNECT | "CONNECT" | HTTP 请求 CONNECT。 |
## ResponseCode
发起请求返回的响应码。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 值 | 说明 |
| ----------------- | ---- | ------------------------------------------------------------ |
| OK | 200 | 请求成功。一般用于GET与POST请求。 |
| CREATED | 201 | 已创建。成功请求并创建了新的资源。 |
| ACCEPTED | 202 | 已接受。已经接受请求,但未处理完成。 |
| NOT_AUTHORITATIVE | 203 | 非授权信息。请求成功。 |
| NO_CONTENT | 204 | 无内容。服务器成功处理,但未返回内容。 |
| RESET | 205 | 重置内容。 |
| PARTIAL | 206 | 部分内容。服务器成功处理了部分GET请求。 |
| MULT_CHOICE | 300 | 多种选择。 |
| MOVED_PERM | 301 | 永久移动。请求的资源已被永久的移动到新URI,返回信息会包括新的URI,浏览器会自动定向到新URI。 |
| MOVED_TEMP | 302 | 临时移动。 |
| SEE_OTHER | 303 | 查看其它地址。 |
| NOT_MODIFIED | 304 | 未修改。 |
| USE_PROXY | 305 | 使用代理。 |
| BAD_REQUEST | 400 | 客户端请求的语法错误,服务器无法理解。 |
| UNAUTHORIZED | 401 | 请求要求用户的身份认证。 |
| PAYMENT_REQUIRED | 402 | 保留,将来使用。 |
| FORBIDDEN | 403 | 服务器理解请求客户端的请求,但是拒绝执行此请求。 |
| NOT_FOUND | 404 | 服务器无法根据客户端的请求找到资源(网页)。 |
| BAD_METHOD | 405 | 客户端请求中的方法被禁止。 |
| NOT_ACCEPTABLE | 406 | 服务器无法根据客户端请求的内容特性完成请求。 |
| PROXY_AUTH | 407 | 请求要求代理的身份认证。 |
| CLIENT_TIMEOUT | 408 | 请求时间过长,超时。 |
| CONFLICT | 409 | 服务器完成客户端的PUT请求是可能返回此代码,服务器处理请求时发生了冲突。 |
| GONE | 410 | 客户端请求的资源已经不存在。 |
| LENGTH_REQUIRED | 411 | 服务器无法处理客户端发送的不带Content-Length的请求信息。 |
| PRECON_FAILED | 412 | 客户端请求信息的先决条件错误。 |
| ENTITY_TOO_LARGE | 413 | 由于请求的实体过大,服务器无法处理,因此拒绝请求。 |
| REQ_TOO_LONG | 414 | 请求的URI过长(URI通常为网址),服务器无法处理。 |
| UNSUPPORTED_TYPE | 415 | 服务器无法处理请求的格式。 |
| INTERNAL_ERROR | 500 | 服务器内部错误,无法完成请求。 |
| NOT_IMPLEMENTED | 501 | 服务器不支持请求的功能,无法完成请求。 |
| BAD_GATEWAY | 502 | 充当网关或代理的服务器,从远端服务器接收到了一个无效的请求。 |
| UNAVAILABLE | 503 | 由于超载或系统维护,服务器暂时的无法处理客户端的请求。 |
| GATEWAY_TIMEOUT | 504 | 充当网关或代理的服务器,未及时从远端服务器获取请求。 |
| VERSION | 505 | 服务器请求的HTTP协议的版本。 |
## HttpResponse
request方法回调函数的返回值类型。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
| result | string \| Object \| ArrayBuffer<sup>6+</sup> | 是 | HTTP请求根据响应头中Content-type类型返回对应的响应格式内容:<br />- application/json:返回JSON格式的字符串,如需HTTP响应具体内容,需开发者自行解析<br />- application/octet-stream:ArrayBuffer<br />- 其他:string |
| resultType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | 是 | 返回值类型。 |
| responseCode | [ResponseCode](#responsecode) \| number | 是 | 回调函数执行成功时,此字段为[ResponseCode](#responsecode)。若执行失败,错误码将会从AsyncCallback中的err字段返回。 |
| header | Object | 是 | 发起HTTP请求返回来的响应头。当前返回的是JSON格式字符串,如需具体字段内容,需开发者自行解析。常见字段及解析方式如下:<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\> | 是 | 服务器返回的 cookies。 |
## http.createHttpResponseCache<sup>9+</sup>
createHttpResponseCache(cacheSize?: number): HttpResponseCache
创建一个默认的对象来存储HTTP访问请求的响应。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| cacheSize | number | 否 | 缓存大小最大为10\*1024\*1024(10MB),默认最大。 |
**返回值:**
| 类型 | 说明 |
| :---------- | :----------------------------------------------------------- |
| [HttpResponseCache](#httpresponsecache9) | 返回一个存储HTTP访问请求响应的对象。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300016 | Error in the HTTP2 framing layer |
| 2300018 | Transferred a partial file |
| 2300023 | Failed writing received data to disk/application |
| 2300025 | Upload failed |
| 2300026 | Failed to open/read local data from file/application |
| 2300027 | Out of memory |
| 2300028 | Timeout was reached |
| 2300047 | Number of redirects hit maximum amount |
| 2300052 | Server returned nothing (no headers, no data) |
| 2300055 | Failed sending data to the peer |
| 2300056 | Failure when receiving data from the peer |
| 2300058 | Problem with the local SSL certificate |
| 2300059 | Couldn't use specified SSL cipher |
| 2300060 | SSL peer certificate or SSH remote key was not OK |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding |
| 2300063 | Maximum file size exceeded |
| 2300070 | Disk full or allocation exceeded |
| 2300073 | Remote file already exists |
| 2300077 | Problem with the SSL CA cert (path? access rights?) |
| 2300078 | Remote file not found |
| 2300094 | An authentication function returned an error |
| 2300999 | Unknown Other Error |
以上错误码的详细介绍参见[HTTP错误码](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/errorcodes/errorcode-http.md)
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
import http from '@ohos.net.http';
let httpResponseCache = http.createHttpResponseCache();
```
## HttpResponseCache<sup>9+</sup>
存储HTTP访问请求响应的对象。
### flush<sup>9+</sup>
flush(callback: AsyncCallback\<void>): void
将缓存中的数据写入文件系统,以便在下一个HTTP请求中访问所有缓存数据,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | 是 | 回调函数返回写入结果。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300016 | Error in the HTTP2 framing layer |
| 2300018 | Transferred a partial file |
| 2300023 | Failed writing received data to disk/application |
| 2300025 | Upload failed |
| 2300026 | Failed to open/read local data from file/application |
| 2300027 | Out of memory |
| 2300028 | Timeout was reached |
| 2300047 | Number of redirects hit maximum amount |
| 2300052 | Server returned nothing (no headers, no data) |
| 2300055 | Failed sending data to the peer |
| 2300056 | Failure when receiving data from the peer |
| 2300058 | Problem with the local SSL certificate |
| 2300059 | Couldn't use specified SSL cipher |
| 2300060 | SSL peer certificate or SSH remote key was not OK |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding |
| 2300063 | Maximum file size exceeded |
| 2300070 | Disk full or allocation exceeded |
| 2300073 | Remote file already exists |
| 2300077 | Problem with the SSL CA cert (path? access rights?) |
| 2300078 | Remote file not found |
| 2300094 | An authentication function returned an error |
| 2300999 | Unknown Other Error |
以上错误码的详细介绍参见[HTTP错误码](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/errorcodes/errorcode-http.md)
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
httpResponseCache.flush(err => {
if (err) {
console.log('flush fail');
return;
}
console.log('flush success');
});
```
### flush<sup>9+</sup>
flush(): Promise\<void>
将缓存中的数据写入文件系统,以便在下一个HTTP请求中访问所有缓存数据,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| --------------------------------- | ------------------------------------- |
| Promise\<void>> | 以Promise形式返回写入结果。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300016 | Error in the HTTP2 framing layer |
| 2300018 | Transferred a partial file |
| 2300023 | Failed writing received data to disk/application |
| 2300025 | Upload failed |
| 2300026 | Failed to open/read local data from file/application |
| 2300027 | Out of memory |
| 2300028 | Timeout was reached |
| 2300047 | Number of redirects hit maximum amount |
| 2300052 | Server returned nothing (no headers, no data) |
| 2300055 | Failed sending data to the peer |
| 2300056 | Failure when receiving data from the peer |
| 2300058 | Problem with the local SSL certificate |
| 2300059 | Couldn't use specified SSL cipher |
| 2300060 | SSL peer certificate or SSH remote key was not OK |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding |
| 2300063 | Maximum file size exceeded |
| 2300070 | Disk full or allocation exceeded |
| 2300073 | Remote file already exists |
| 2300077 | Problem with the SSL CA cert (path? access rights?) |
| 2300078 | Remote file not found |
| 2300094 | An authentication function returned an error |
| 2300999 | Unknown Other Error |
以上错误码的详细介绍参见[HTTP错误码](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/errorcodes/errorcode-http.md)
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
httpResponseCache.flush().then(() => {
console.log('flush success');
}).catch(err => {
console.log('flush fail');
});
```
### delete<sup>9+</sup>
delete(callback: AsyncCallback\<void>): void
禁用缓存并删除其中的数据,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | 是 | 回调函数返回删除结果。|
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300003 | URL using bad/illegal format or missing URL |
| 2300005 | Couldn't resolve proxy name |
| 2300006 | Couldn't resolve host name |
| 2300007 | Couldn't connect to server |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300999 | Unknown Other Error |
以上错误码的详细介绍参见[HTTP错误码](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/errorcodes/errorcode-http.md)
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
httpResponseCache.delete(err => {
if (err) {
console.log('delete fail');
return;
}
console.log('delete success');
});
```
### delete<sup>9+</sup>
delete(): Promise\<void>
禁用缓存并删除其中的数据,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | 以Promise形式返回删除结果。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300999 | Unknown Other Error |
以上错误码的详细介绍参见[HTTP错误码](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/errorcodes/errorcode-http.md)
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
httpResponseCache.delete().then(() => {
console.log('delete success');
}).catch(err => {
console.log('delete fail');
});
```
## HttpDataType<sup>9+</sup>
http的数据类型。
**系统能力**:SystemCapability.Communication.NetStack
| 名称 | 值 | 说明 |
| ------------------ | -- | ----------- |
| STRING | 0 | 字符串类型。 |
| OBJECT | 1 | 对象类型。 |
| ARRAY_BUFFER | 2 | 二进制数组类型。|
## HttpProtocol<sup>9+</sup>
http协议版本。
**系统能力**:SystemCapability.Communication.NetStack
| 名称 | 说明 |
| :-------- | :----------- |
| HTTP1_1 | 协议http1.1 |
| HTTP2 | 协议http2 |
# @ohos.net.http (数据请求)
本模块提供HTTP数据请求能力。应用可以通过HTTP发起一个数据请求,支持常见的GET、POST、OPTIONS、HEAD、PUT、DELETE、TRACE、CONNECT方法。
>**说明:**
>
>本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
>
## 导入模块
```js
import http from '@ohos.net.http';
```
## 完整示例
```js
import http from '@ohos.net.http';
// 每一个httpRequest对应一个HTTP请求任务,不可复用
let httpRequest = http.createHttp();
// 用于订阅HTTP响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息
// 从API 8开始,使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+
httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header));
});
httpRequest.request(
// 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定
"EXAMPLE_URL",
{
method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET
// 开发者根据自身业务需要添加header字段
header: {
'Content-Type': 'application/json'
},
// 当使用POST请求时此字段用于传递内容
extraData: {
"data": "data to send",
},
expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型
usingCache: true, // 可选,默认为true
priority: 1, // 可选,默认为1
connectTimeout: 60000, // 可选,默认为60000ms
readTimeout: 60000, // 可选,默认为60000ms
usingProtocol: http.HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定
}, (err, data) => {
if (!err) {
// data.result为HTTP响应内容,可根据业务需要进行解析
console.info('Result:' + data.result);
console.info('code:' + data.responseCode);
// data.header为HTTP响应头,可根据业务需要进行解析
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + data.cookies); // 8+
} else {
console.info('error:' + JSON.stringify(err));
// 当该请求使用完毕时,调用destroy方法主动销毁。
httpRequest.destroy();
}
}
);
```
## http.createHttp
createHttp\(\): HttpRequest
创建一个HTTP请求,里面包括发起请求、中断请求、订阅/取消订阅HTTP Response Header事件。每一个HttpRequest对象对应一个HTTP请求。如需发起多个HTTP请求,须为每个HTTP请求创建对应HttpRequest对象。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :---------- | :----------------------------------------------------------- |
| HttpRequest | 返回一个HttpRequest对象,里面包括request、destroy、on和off方法。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2100002 | System internal error. |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
import http from '@ohos.net.http';
let httpRequest = http.createHttp();
```
## HttpRequest
HTTP请求任务。在调用HttpRequest的方法前,需要先通过[createHttp\(\)](#httpcreatehttp)创建一个任务。
### request
request\(url: string, callback: AsyncCallback\<HttpResponse\>\):void
根据URL地址,发起HTTP网络请求,使用callback方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------------- | ---- | ----------------------- |
| url | string | 是 | 发起网络请求的URL地址。 |
| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300003 | URL using bad/illegal format or missing URL |
| 2300005 | Couldn't resolve proxy name |
| 2300006 | Couldn't resolve host name |
| 2300007 | Couldn't connect to server |
| 2300052 | Server returned nothing (no headers, no data) |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
httpRequest.request("EXAMPLE_URL", (err, data) => {
if (!err) {
console.info('Result:' + data.result);
console.info('code:' + data.responseCode);
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + data.cookies); // 8+
} else {
console.info('error:' + JSON.stringify(err));
}
});
```
### request
request\(url: string, options: HttpRequestOptions, callback: AsyncCallback<HttpResponse\>\):void
根据URL地址和相关配置项,发起HTTP网络请求,使用callback方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- |
| url | string | 是 | 发起网络请求的URL地址。 |
| options | HttpRequestOptions | 是 | 参考[HttpRequestOptions](#httprequestoptions)。 |
| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300003 | URL using bad/illegal format or missing URL |
| 2300005 | Couldn't resolve proxy name |
| 2300006 | Couldn't resolve host name |
| 2300007 | Couldn't connect to server |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
httpRequest.request("EXAMPLE_URL",
{
method: http.RequestMethod.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:' + JSON.stringify(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']);
} else {
console.info('error:' + JSON.stringify(err));
}
});
```
### request
request\(url: string, options? : HttpRequestOptions\): Promise<HttpResponse\>
根据URL地址,发起HTTP网络请求,使用Promise方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------------------ | ---- | ----------------------------------------------- |
| url | string | 是 | 发起网络请求的URL地址。 |
| options | HttpRequestOptions | 否 | 参考[HttpRequestOptions](#httprequestoptions)。 |
**返回值:**
| 类型 | 说明 |
| :------------------------------------- | :-------------------------------- |
| Promise<[HttpResponse](#httpresponse)> | 以Promise形式返回发起请求的结果。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300003 | URL using bad/illegal format or missing URL |
| 2300005 | Couldn't resolve proxy name |
| 2300006 | Couldn't resolve host name |
| 2300007 | Couldn't connect to server |
| 2300009 | Access denied to remote resource |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
let promise = httpRequest.request("EXAMPLE_URL", {
method: http.RequestMethod.GET,
connectTimeout: 60000,
readTimeout: 60000,
header: {
'Content-Type': 'application/json'
}
});
promise.then((data) => {
console.info('Result:' + data.result);
console.info('code:' + data.responseCode);
console.info('header:' + JSON.stringify(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']);
}).catch((err) => {
console.info('error:' + JSON.stringify(err));
});
```
### destroy
destroy\(\): void
中断请求任务。
**系统能力**:SystemCapability.Communication.NetStack
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
httpRequest.destroy();
```
### on\('headerReceive'\)
on\(type: 'headerReceive', callback: AsyncCallback<Object\>\): void
订阅HTTP Response Header 事件。
>![](public_sys-resources/icon-note.gif) **说明:**
>此接口已废弃,建议使用[on\('headersReceive'\)<sup>8+</sup>](#onheadersreceive8)替代。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------- | ---- | --------------------------------- |
| type | string | 是 | 订阅的事件类型,'headerReceive'。 |
| callback | AsyncCallback\<Object\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300003 | URL using bad/illegal format or missing URL |
| 2300005 | Couldn't resolve proxy name |
| 2300006 | Couldn't resolve host name |
| 2300007 | Couldn't connect to server |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300023 | Failed writing received data to disk/application |
| 2300025 | Upload failed |
| 2300027 | Out of memory |
| 2300028 | Timeout was reached |
| 2300052 | Server returned nothing (no headers, no data) |
| 2300056 | Failure when receiving data from the peer |
| 2300058 | Problem with the local SSL certificate |
| 2300060 | SSL peer certificate or SSH remote key was not OK |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding |
| 2300063 | Maximum file size exceeded |
| 2300070 | Disk full or allocation exceeded |
| 2300077 | Problem with the SSL CA cert (path? access rights?) |
| 2300078 | Remote file not found |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
httpRequest.on('headerReceive', (err, data) => {
if (!err) {
console.info('header: ' + JSON.stringify(data));
} else {
console.info('error:' + JSON.stringify(err));
}
});
```
### off\('headerReceive'\)
off\(type: 'headerReceive', callback?: AsyncCallback<Object\>\): void
取消订阅HTTP Response Header 事件。
>![](public_sys-resources/icon-note.gif) **说明:**
>
>1. 此接口已废弃,建议使用[off\('headersReceive'\)<sup>8+</sup>](#offheadersreceive8)替代。
>
>2. 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------- | ---- | ------------------------------------- |
| type | string | 是 | 取消订阅的事件类型,'headerReceive'。 |
| callback | AsyncCallback\<Object\> | 否 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300003 | URL using bad/illegal format or missing URL |
| 2300005 | Couldn't resolve proxy name |
| 2300006 | Couldn't resolve host name |
| 2300007 | Couldn't connect to server |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
httpRequest.off('headerReceive');
```
### on\('headersReceive'\)<sup>8+</sup>
on\(type: 'headersReceive', callback: Callback<Object\>\): void
订阅HTTP Response Header 事件。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------ | ---- | ---------------------------------- |
| type | string | 是 | 订阅的事件类型:'headersReceive'。 |
| callback | Callback\<Object\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300003 | URL using bad/illegal format or missing URL |
| 2300005 | Couldn't resolve proxy name |
| 2300006 | Couldn't resolve host name |
| 2300007 | Couldn't connect to server |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300023 | Failed writing received data to disk/application |
| 2300025 | Upload failed |
| 2300027 | Out of memory |
| 2300028 | Timeout was reached |
| 2300052 | Server returned nothing (no headers, no data) |
| 2300056 | Failure when receiving data from the peer |
| 2300058 | Problem with the local SSL certificate |
| 2300060 | SSL peer certificate or SSH remote key was not OK |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding |
| 2300063 | Maximum file size exceeded |
| 2300070 | Disk full or allocation exceeded |
| 2300077 | Problem with the SSL CA cert (path? access rights?) |
| 2300078 | Remote file not found |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header));
});
```
### off\('headersReceive'\)<sup>8+</sup>
off\(type: 'headersReceive', callback?: Callback<Object\>\): void
取消订阅HTTP Response Header 事件。
>![](public_sys-resources/icon-note.gif) **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------ | ---- | -------------------------------------- |
| type | string | 是 | 取消订阅的事件类型:'headersReceive'。 |
| callback | Callback\<Object\> | 否 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300003 | URL using bad/illegal format or missing URL |
| 2300005 | Couldn't resolve proxy name |
| 2300006 | Couldn't resolve host name |
| 2300007 | Couldn't connect to server |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
httpRequest.off('headersReceive');
```
### once\('headersReceive'\)<sup>8+</sup>
once\(type: 'headersReceive', callback: Callback<Object\>\): void
订阅HTTP Response Header 事件,但是只触发一次。一旦触发之后,订阅器就会被移除。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------ | ---- | ---------------------------------- |
| type | string | 是 | 订阅的事件类型:'headersReceive'。 |
| callback | Callback\<Object\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300003 | URL using bad/illegal format or missing URL |
| 2300005 | Couldn't resolve proxy name |
| 2300006 | Couldn't resolve host name |
| 2300007 | Couldn't connect to server |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300023 | Failed writing received data to disk/application |
| 2300025 | Upload failed |
| 2300027 | Out of memory |
| 2300028 | Timeout was reached |
| 2300052 | Server returned nothing (no headers, no data) |
| 2300056 | Failure when receiving data from the peer |
| 2300058 | Problem with the local SSL certificate |
| 2300060 | SSL peer certificate or SSH remote key was not OK |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding |
| 2300063 | Maximum file size exceeded |
| 2300070 | Disk full or allocation exceeded |
| 2300077 | Problem with the SSL CA cert (path? access rights?) |
| 2300078 | Remote file not found |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
httpRequest.once('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header));
});
```
## HttpRequestOptions
发起请求可选参数的类型和取值范围。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
| method | [RequestMethod](#requestmethod) | 否 | 请求方式。 |
| extraData | string \| Object \| ArrayBuffer<sup>6+</sup> | 否 | 发送请求的额外数据。<br />- 当HTTP请求为POST、PUT等方法时,此字段为HTTP请求的content。<br />- 当HTTP请求为GET、OPTIONS、DELETE、TRACE、CONNECT等方法时,此字段为HTTP请求的参数补充,参数内容会拼接到URL中进行发送。<sup>6+</sup><br />- 开发者传入string对象,开发者需要自行编码,将编码后的string传入。<sup>6+</sup> |
| expectDataType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | 否 | 指定返回数据的类型。如果设置了此参数,系统将优先返回指定的类型。 |
| usingCache<sup>9+</sup> | boolean | 否 | 是否使用缓存,默认为true。 |
| priority<sup>9+</sup> | number | 否 | 优先级,范围\[1,1000],默认是1。 |
| header | Object | 否 | HTTP请求头字段。默认{'Content-Type': 'application/json'}。 |
| readTimeout | number | 否 | 读取超时时间。单位为毫秒(ms),默认为60000ms。 |
| connectTimeout | number | 否 | 连接超时时间。单位为毫秒(ms),默认为60000ms。 |
| usingProtocol<sup>9+</sup> | [HttpProtocol](#httpprotocol9) | 否 | 使用协议。默认值由系统自动指定。 |
## RequestMethod
HTTP 请求方法。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 值 | 说明 |
| :------ | ------- | :------------------ |
| OPTIONS | "OPTIONS" | HTTP 请求 OPTIONS。 |
| GET | "GET" | HTTP 请求 GET。 |
| HEAD | "HEAD" | HTTP 请求 HEAD。 |
| POST | "POST" | HTTP 请求 POST。 |
| PUT | "PUT" | HTTP 请求 PUT。 |
| DELETE | "DELETE" | HTTP 请求 DELETE。 |
| TRACE | "TRACE" | HTTP 请求 TRACE。 |
| CONNECT | "CONNECT" | HTTP 请求 CONNECT。 |
## ResponseCode
发起请求返回的响应码。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 值 | 说明 |
| ----------------- | ---- | ------------------------------------------------------------ |
| OK | 200 | 请求成功。一般用于GET与POST请求。 |
| CREATED | 201 | 已创建。成功请求并创建了新的资源。 |
| ACCEPTED | 202 | 已接受。已经接受请求,但未处理完成。 |
| NOT_AUTHORITATIVE | 203 | 非授权信息。请求成功。 |
| NO_CONTENT | 204 | 无内容。服务器成功处理,但未返回内容。 |
| RESET | 205 | 重置内容。 |
| PARTIAL | 206 | 部分内容。服务器成功处理了部分GET请求。 |
| MULT_CHOICE | 300 | 多种选择。 |
| MOVED_PERM | 301 | 永久移动。请求的资源已被永久的移动到新URI,返回信息会包括新的URI,浏览器会自动定向到新URI。 |
| MOVED_TEMP | 302 | 临时移动。 |
| SEE_OTHER | 303 | 查看其它地址。 |
| NOT_MODIFIED | 304 | 未修改。 |
| USE_PROXY | 305 | 使用代理。 |
| BAD_REQUEST | 400 | 客户端请求的语法错误,服务器无法理解。 |
| UNAUTHORIZED | 401 | 请求要求用户的身份认证。 |
| PAYMENT_REQUIRED | 402 | 保留,将来使用。 |
| FORBIDDEN | 403 | 服务器理解请求客户端的请求,但是拒绝执行此请求。 |
| NOT_FOUND | 404 | 服务器无法根据客户端的请求找到资源(网页)。 |
| BAD_METHOD | 405 | 客户端请求中的方法被禁止。 |
| NOT_ACCEPTABLE | 406 | 服务器无法根据客户端请求的内容特性完成请求。 |
| PROXY_AUTH | 407 | 请求要求代理的身份认证。 |
| CLIENT_TIMEOUT | 408 | 请求时间过长,超时。 |
| CONFLICT | 409 | 服务器完成客户端的PUT请求是可能返回此代码,服务器处理请求时发生了冲突。 |
| GONE | 410 | 客户端请求的资源已经不存在。 |
| LENGTH_REQUIRED | 411 | 服务器无法处理客户端发送的不带Content-Length的请求信息。 |
| PRECON_FAILED | 412 | 客户端请求信息的先决条件错误。 |
| ENTITY_TOO_LARGE | 413 | 由于请求的实体过大,服务器无法处理,因此拒绝请求。 |
| REQ_TOO_LONG | 414 | 请求的URI过长(URI通常为网址),服务器无法处理。 |
| UNSUPPORTED_TYPE | 415 | 服务器无法处理请求的格式。 |
| INTERNAL_ERROR | 500 | 服务器内部错误,无法完成请求。 |
| NOT_IMPLEMENTED | 501 | 服务器不支持请求的功能,无法完成请求。 |
| BAD_GATEWAY | 502 | 充当网关或代理的服务器,从远端服务器接收到了一个无效的请求。 |
| UNAVAILABLE | 503 | 由于超载或系统维护,服务器暂时的无法处理客户端的请求。 |
| GATEWAY_TIMEOUT | 504 | 充当网关或代理的服务器,未及时从远端服务器获取请求。 |
| VERSION | 505 | 服务器请求的HTTP协议的版本。 |
## HttpResponse
request方法回调函数的返回值类型。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
| result | string \| Object \| ArrayBuffer<sup>6+</sup> | 是 | HTTP请求根据响应头中Content-type类型返回对应的响应格式内容:<br />- application/json:返回JSON格式的字符串,如需HTTP响应具体内容,需开发者自行解析<br />- application/octet-stream:ArrayBuffer<br />- 其他:string |
| resultType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | 是 | 返回值类型。 |
| responseCode | [ResponseCode](#responsecode) \| number | 是 | 回调函数执行成功时,此字段为[ResponseCode](#responsecode)。若执行失败,错误码将会从AsyncCallback中的err字段返回。 |
| header | Object | 是 | 发起HTTP请求返回来的响应头。当前返回的是JSON格式字符串,如需具体字段内容,需开发者自行解析。常见字段及解析方式如下:<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\> | 是 | 服务器返回的 cookies。 |
## http.createHttpResponseCache<sup>9+</sup>
createHttpResponseCache(cacheSize?: number): HttpResponseCache
创建一个默认的对象来存储HTTP访问请求的响应。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| cacheSize | number | 否 | 缓存大小最大为10\*1024\*1024(10MB),默认最大。 |
**返回值:**
| 类型 | 说明 |
| :---------- | :----------------------------------------------------------- |
| [HttpResponseCache](#httpresponsecache9) | 返回一个存储HTTP访问请求响应的对象。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300016 | Error in the HTTP2 framing layer |
| 2300018 | Transferred a partial file |
| 2300023 | Failed writing received data to disk/application |
| 2300025 | Upload failed |
| 2300026 | Failed to open/read local data from file/application |
| 2300027 | Out of memory |
| 2300028 | Timeout was reached |
| 2300047 | Number of redirects hit maximum amount |
| 2300052 | Server returned nothing (no headers, no data) |
| 2300055 | Failed sending data to the peer |
| 2300056 | Failure when receiving data from the peer |
| 2300058 | Problem with the local SSL certificate |
| 2300059 | Couldn't use specified SSL cipher |
| 2300060 | SSL peer certificate or SSH remote key was not OK |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding |
| 2300063 | Maximum file size exceeded |
| 2300070 | Disk full or allocation exceeded |
| 2300073 | Remote file already exists |
| 2300077 | Problem with the SSL CA cert (path? access rights?) |
| 2300078 | Remote file not found |
| 2300094 | An authentication function returned an error |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
import http from '@ohos.net.http';
let httpResponseCache = http.createHttpResponseCache();
```
## HttpResponseCache<sup>9+</sup>
存储HTTP访问请求响应的对象。
### flush<sup>9+</sup>
flush(callback: AsyncCallback\<void>): void
将缓存中的数据写入文件系统,以便在下一个HTTP请求中访问所有缓存数据,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | 是 | 回调函数返回写入结果。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300016 | Error in the HTTP2 framing layer |
| 2300018 | Transferred a partial file |
| 2300023 | Failed writing received data to disk/application |
| 2300025 | Upload failed |
| 2300026 | Failed to open/read local data from file/application |
| 2300027 | Out of memory |
| 2300028 | Timeout was reached |
| 2300047 | Number of redirects hit maximum amount |
| 2300052 | Server returned nothing (no headers, no data) |
| 2300055 | Failed sending data to the peer |
| 2300056 | Failure when receiving data from the peer |
| 2300058 | Problem with the local SSL certificate |
| 2300059 | Couldn't use specified SSL cipher |
| 2300060 | SSL peer certificate or SSH remote key was not OK |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding |
| 2300063 | Maximum file size exceeded |
| 2300070 | Disk full or allocation exceeded |
| 2300073 | Remote file already exists |
| 2300077 | Problem with the SSL CA cert (path? access rights?) |
| 2300078 | Remote file not found |
| 2300094 | An authentication function returned an error |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
httpResponseCache.flush(err => {
if (err) {
console.log('flush fail');
return;
}
console.log('flush success');
});
```
### flush<sup>9+</sup>
flush(): Promise\<void>
将缓存中的数据写入文件系统,以便在下一个HTTP请求中访问所有缓存数据,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| --------------------------------- | ------------------------------------- |
| Promise\<void>> | 以Promise形式返回写入结果。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300016 | Error in the HTTP2 framing layer |
| 2300018 | Transferred a partial file |
| 2300023 | Failed writing received data to disk/application |
| 2300025 | Upload failed |
| 2300026 | Failed to open/read local data from file/application |
| 2300027 | Out of memory |
| 2300028 | Timeout was reached |
| 2300047 | Number of redirects hit maximum amount |
| 2300052 | Server returned nothing (no headers, no data) |
| 2300055 | Failed sending data to the peer |
| 2300056 | Failure when receiving data from the peer |
| 2300058 | Problem with the local SSL certificate |
| 2300059 | Couldn't use specified SSL cipher |
| 2300060 | SSL peer certificate or SSH remote key was not OK |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding |
| 2300063 | Maximum file size exceeded |
| 2300070 | Disk full or allocation exceeded |
| 2300073 | Remote file already exists |
| 2300077 | Problem with the SSL CA cert (path? access rights?) |
| 2300078 | Remote file not found |
| 2300094 | An authentication function returned an error |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
httpResponseCache.flush().then(() => {
console.log('flush success');
}).catch(err => {
console.log('flush fail');
});
```
### delete<sup>9+</sup>
delete(callback: AsyncCallback\<void>): void
禁用缓存并删除其中的数据,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | 是 | 回调函数返回删除结果。|
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300003 | URL using bad/illegal format or missing URL |
| 2300005 | Couldn't resolve proxy name |
| 2300006 | Couldn't resolve host name |
| 2300007 | Couldn't connect to server |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
httpResponseCache.delete(err => {
if (err) {
console.log('delete fail');
return;
}
console.log('delete success');
});
```
### delete<sup>9+</sup>
delete(): Promise\<void>
禁用缓存并删除其中的数据,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | 以Promise形式返回删除结果。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:**
```js
httpResponseCache.delete().then(() => {
console.log('delete success');
}).catch(err => {
console.log('delete fail');
});
```
## HttpDataType<sup>9+</sup>
http的数据类型。
**系统能力**:SystemCapability.Communication.NetStack
| 名称 | 值 | 说明 |
| ------------------ | -- | ----------- |
| STRING | 0 | 字符串类型。 |
| OBJECT | 1 | 对象类型。 |
| ARRAY_BUFFER | 2 | 二进制数组类型。|
## HttpProtocol<sup>9+</sup>
http协议版本。
**系统能力**:SystemCapability.Communication.NetStack
| 名称 | 说明 |
| :-------- | :----------- |
| HTTP1_1 | 协议http1.1 |
| HTTP2 | 协议http2 |
# @ohos.net.socket (Socket连接)
> **说明:**
>
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```js
import socket from '@ohos.net.socket';
```
## socket.constructUDPSocketInstance
constructUDPSocketInstance\(\): UDPSocket
创建一个UDPSocket对象。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :--------------------------------- | :---------------------- |
| [UDPSocket](#udpsocket) | 返回一个UDPSocket对象。 |
**示例:**
```js
let udp = socket.constructUDPSocketInstance();
```
## UDPSocket
UDPSocket连接。在调用UDPSocket的方法前,需要先通过[socket.constructUDPSocketInstance](#socketconstructudpsocketinstance)创建UDPSocket对象。
### bind
bind\(address: NetAddress, callback: AsyncCallback<void\>\): void
绑定IP地址和端口,端口可以指定或由系统随机分配。使用callback方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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\>
绑定IP地址和端口,端口可以指定或由系统随机分配。使用Promise方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :----------------------------------------- |
| Promise\<void\> | 以Promise形式异步返回UDPSocket绑定的结果。 |
**示例:**
```js
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
通过UDPSocket连接发送数据。使用callback方式作为异步方法。
发送数据前,需要先调用[UDPSocket.bind()](#bind)绑定IP地址和端口。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [UDPSendOptions](#udpsendoptions) | 是 | UDPSocket发送参数,参考[UDPSendOptions](#udpsendoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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\>
通过UDPSocket连接发送数据。使用Promise方式作为异步方法。
发送数据前,需要先调用[UDPSocket.bind()](#bind)绑定IP地址和端口。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [UDPSendOptions](#udpsendoptions) | 是 | UDPSocket发送参数,参考[UDPSendOptions](#udpsendoptions)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :--------------------------------------------- |
| Promise\<void\> | 以Promise形式返回UDPSocket连接发送数据的结果。 |
**示例:**
```js
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
关闭UDPSocket连接。使用callback方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | ---------- |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
let udp = socket.constructUDPSocketInstance();
udp.close(err => {
if (err) {
console.log('close fail');
return;
}
console.log('close success');
})
```
### close
close\(\): Promise<void\>
关闭UDPSocket连接。使用Promise方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :-------------- | :----------------------------------------- |
| Promise\<void\> | 以Promise形式返回关闭UDPSocket连接的结果。 |
**示例:**
```js
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
获取UDPSocket状态。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------ | ---- | ---------- |
| callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | 是 | 回调函数。 |
**示例:**
```js
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\>
获取UDPSocket状态。使用Promise方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :----------------------------------------------- | :----------------------------------------- |
| Promise<[SocketStateBase](#socketstatebase)> | 以Promise形式返回获取UDPSocket状态的结果。 |
**示例:**
```js
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
设置UDPSocket连接的其他属性。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [UDPExtraOptions](#udpextraoptions) | 是 | UDPSocket连接的其他属性,参考[UDPExtraOptions](#udpextraoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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\>
设置UDPSocket连接的其他属性。使用Promise方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [UDPExtraOptions](#udpextraoptions) | 是 | UDPSocket连接的其他属性,参考[UDPExtraOptions](#udpextraoptions)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :--------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回设置UDPSocket连接的其他属性的结果。 |
**示例:**
```js
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
订阅UDPSocket连接的接收消息事件。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | 是 | 订阅的事件类型。'message':接收消息事件。 |
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | 是 | 回调函数。 |
**示例:**
```js
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
取消订阅UDPSocket连接的接收消息事件。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | 是 | 订阅的事件类型。'message':接收消息事件。 |
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | 否 | 回调函数。 |
**示例:**
```js
let udp = socket.constructUDPSocketInstance();
let callback = value =>{
console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
}
udp.on('message', callback);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
udp.off('message', callback);
udp.off('message');
```
### on\('listening' | 'close'\)
on\(type: 'listening' | 'close', callback: Callback<void\>\): void
订阅UDPSocket连接的数据包消息事件或关闭事件。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 订阅的事件类型。<br />- 'listening':数据包消息事件。<br />- 'close':关闭事件。 |
| callback | Callback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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
取消订阅UDPSocket连接的数据包消息事件或关闭事件。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 订阅事件类型。<br />- 'listening':数据包消息事件。<br />- 'close':关闭事件。 |
| callback | Callback\<void\> | 否 | 回调函数。 |
**示例:**
```js
let udp = socket.constructUDPSocketInstance();
let callback1 = () =>{
console.log("on listening, success");
}
udp.on('listening', callback1);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
udp.off('listening', callback1);
udp.off('listening');
let callback2 = () =>{
console.log("on close, success");
}
udp.on('close', callback2);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
udp.off('close', callback2);
udp.off('close');
```
### on\('error'\)
on\(type: 'error', callback: ErrorCallback\): void
订阅UDPSocket连接的error事件。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | ------------------------------------ |
| type | string | 是 | 订阅的事件类型。'error':error事件。 |
| callback | ErrorCallback | 是 | 回调函数。 |
**示例:**
```js
let udp = socket.constructUDPSocketInstance();
udp.on('error', err => {
console.log("on error, err:" + JSON.stringify(err))
});
```
### off\('error'\)
off\(type: 'error', callback?: ErrorCallback\): void
取消订阅UDPSocket连接的error事件。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | ------------------------------------ |
| type | string | 是 | 订阅的事件类型。'error':error事件。 |
| callback | ErrorCallback | 否 | 回调函数。 |
**示例:**
```js
let udp = socket.constructUDPSocketInstance();
let callback = err =>{
console.log("on error, err:" + JSON.stringify(err));
}
udp.on('error', callback);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
udp.off('error', callback);
udp.off('error');
```
## NetAddress
目标地址信息。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| ------- | ------ | ---- | ------------------------------------------------------------ |
| address | string | 是 | 本地绑定的ip地址。 |
| port | number | 否 | 端口号 ,范围0~65535。如果不指定系统随机分配端口。 |
| family | number | 否 | 网络协议类型,可选类型:<br />- 1:IPv4<br />- 2:IPv6<br />默认为1。 |
## UDPSendOptions
UDPSocket发送参数。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------- | ---- | -------------- |
| data | string \| ArrayBuffer<sup>7+</sup> | 是 | 发送的数据。 |
| address | [NetAddress](#netaddress) | 是 | 目标地址信息。 |
## UDPExtraOptions
UDPSocket连接的其他属性。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| ----------------- | ------- | ---- | -------------------------------- |
| broadcast | boolean | 否 | 是否可以发送广播。默认为false。 |
| receiveBufferSize | number | 否 | 接收缓冲区大小(单位:Byte)。 |
| sendBufferSize | number | 否 | 发送缓冲区大小(单位:Byte)。 |
| reuseAddress | boolean | 否 | 是否重用地址。默认为false。 |
| socketTimeout | number | 否 | 套接字超时时间,单位毫秒(ms)。 |
## SocketStateBase
Socket的状态信息。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| ----------- | ------- | ---- | ---------- |
| isBound | boolean | 是 | 是否绑定。 |
| isClose | boolean | 是 | 是否关闭。 |
| isConnected | boolean | 是 | 是否连接。 |
## SocketRemoteInfo
Socket的连接信息。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| ------- | ------ | ---- | ------------------------------------------------------------ |
| address | string | 是 | 本地绑定的ip地址。 |
| family | string | 是 | 网络协议类型,可选类型:<br />- IPv4<br />- IPv6<br />默认为IPv4。 |
| port | number | 是 | 端口号,范围0~65535。 |
| size | number | 是 | 服务器响应信息的字节长度。 |
## UDP 错误码说明
UDP 错误码映射形式为:2301000 + 内核错误码。
错误码的详细介绍参见[Socket错误码](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/errorcodes/errorcode-socket.md)
## socket.constructTCPSocketInstance
constructTCPSocketInstance\(\): TCPSocket
创建一个TCPSocket对象。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :--------------------------------- | :---------------------- |
| [TCPSocket](#tcpsocket) | 返回一个TCPSocket对象。 |
**示例:**
```js
let tcp = socket.constructTCPSocketInstance();
```
## TCPSocket
TCPSocket连接。在调用TCPSocket的方法前,需要先通过[socket.constructTCPSocketInstance](#socketconstructtcpsocketinstance)创建TCPSocket对象。
### bind
bind\(address: NetAddress, callback: AsyncCallback<void\>\): void
绑定IP地址和端口,端口可以指定或由系统随机分配。使用callback方法作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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\>
绑定IP地址和端口,端口可以指定或由系统随机分配。使用Promise方法作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :------------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回TCPSocket绑定本机的IP地址和端口的结果。 |
**示例:**
```js
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
连接到指定的IP地址和端口。使用callback方法作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPConnectOptions](#tcpconnectoptions) | 是 | TCPSocket连接的参数,参考[TCPConnectOptions](#tcpconnectoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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\>
连接到指定的IP地址和端口。使用promise方法作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPConnectOptions](#tcpconnectoptions) | 是 | TCPSocket连接的参数,参考[TCPConnectOptions](#tcpconnectoptions)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :--------------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回TCPSocket连接到指定的IP地址和端口的结果。 |
**示例:**
```js
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
通过TCPSocket连接发送数据。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPSendOptions](#tcpsendoptions) | 是 | TCPSocket发送请求的参数,参考[TCPSendOptions](#tcpsendoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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\>
通过TCPSocket连接发送数据。使用Promise方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPSendOptions](#tcpsendoptions) | 是 | TCPSocket发送请求的参数,参考[TCPSendOptions](#tcpsendoptions)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回通过TCPSocket连接发送数据的结果。 |
**示例:**
```js
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
关闭TCPSocket连接。使用callback方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | ---------- |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
let tcp = socket.constructTCPSocketInstance();
tcp.close(err => {
if (err) {
console.log('close fail');
return;
}
console.log('close success');
})
```
### close
close\(\): Promise<void\>
关闭TCPSocket连接。使用Promise方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :-------------- | :----------------------------------------- |
| Promise\<void\> | 以Promise形式返回关闭TCPSocket连接的结果。 |
**示例:**
```js
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
获取对端Socket地址。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------- | ---- | ---------- |
| callback | AsyncCallback<[NetAddress](#netaddress)> | 是 | 回调函数。 |
**示例:**
```js
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\>
获取对端Socket地址。使用Promise方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :------------------------------------------ | :------------------------------------------ |
| Promise<[NetAddress](#netaddress)> | 以Promise形式返回获取对端socket地址的结果。 |
**示例:**
```js
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');
}).catch(err => {
console.log('getRemoteAddressfail');
});
}).catch(err => {
console.log('connect fail');
});
```
### getState
getState\(callback: AsyncCallback<SocketStateBase\>\): void
获取TCPSocket状态。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)或[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------ | ---- | ---------- |
| callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | 是 | 回调函数。 |
**示例:**
```js
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\>
获取TCPSocket状态。使用Promise方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)或[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :----------------------------------------------- | :----------------------------------------- |
| Promise<[SocketStateBase](#socketstatebase)> | 以Promise形式返回获取TCPSocket状态的结果。 |
**示例:**
```js
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');
}).catch(err => {
console.log('getState fail');
});
}).catch(err => {
console.log('connect fail');
});
```
### setExtraOptions
setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback<void\>\): void
设置TCPSocket连接的其他属性。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)或[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPExtraOptions](#tcpextraoptions) | 是 | TCPSocket连接的其他属性,参考[TCPExtraOptions](#tcpextraoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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\>
设置TCPSocket连接的其他属性,使用Promise方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)或[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPExtraOptions](#tcpextraoptions) | 是 | TCPSocket连接的其他属性,参考[TCPExtraOptions](#tcpextraoptions)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :--------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回设置TCPSocket连接的其他属性的结果。 |
**示例:**
```js
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
订阅TCPSocket连接的接收消息事件。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | 是 | 订阅的事件类型。'message':接收消息事件。 |
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | 是 | 回调函数。 |
**示例:**
```js
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
取消订阅TCPSocket连接的接收消息事件。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | 是 | 订阅的事件类型。'message':接收消息事件。 |
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | 否 | 回调函数。 |
**示例:**
```js
let tcp = socket.constructTCPSocketInstance();
let callback = value =>{
console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
}
tcp.on('message', callback);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
tcp.off('message', callback);
tcp.off('message');
```
### on\('connect' | 'close'\)
on\(type: 'connect' | 'close', callback: Callback<void\>\): void
订阅TCPSocket的连接事件或关闭事件。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 订阅的事件类型。<br />- 'connect':连接事件。<br />- 'close':关闭事件。 |
| callback | Callback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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
取消订阅TCPSocket的连接事件或关闭事件。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 订阅的事件类型。<br />- 'connect':连接事件。<br />- 'close':关闭事件。 |
| callback | Callback\<void\> | 否 | 回调函数。 |
**示例:**
```js
let tcp = socket.constructTCPSocketInstance();
let callback1 = () =>{
console.log("on connect success");
}
tcp.on('connect', callback1);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
tcp.off('connect', callback1);
tcp.off('connect');
let callback2 = () =>{
console.log("on close success");
}
tcp.on('close', callback2);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
tcp.off('close', callback2);
tcp.off('close');
```
### on\('error'\)
on\(type: 'error', callback: ErrorCallback\): void
订阅TCPSocket连接的error事件。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | ------------------------------------ |
| type | string | 是 | 订阅的事件类型。'error':error事件。 |
| callback | ErrorCallback | 是 | 回调函数。 |
**示例:**
```js
let tcp = socket.constructTCPSocketInstance();
tcp.on('error', err => {
console.log("on error, err:" + JSON.stringify(err))
});
```
### off\('error'\)
off\(type: 'error', callback?: ErrorCallback\): void
取消订阅TCPSocket连接的error事件。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | ------------------------------------ |
| type | string | 是 | 订阅的事件类型。'error':error事件。 |
| callback | ErrorCallback | 否 | 回调函数。 |
**示例:**
```js
let tcp = socket.constructTCPSocketInstance();
let callback = err =>{
console.log("on error, err:" + JSON.stringify(err));
}
tcp.on('error', callback);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
tcp.off('error', callback);
tcp.off('error');
```
## TCPConnectOptions
TCPSocket连接的参数。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------- | ---- | -------------------------- |
| address | [NetAddress](#netaddress) | 是 | 绑定的地址以及端口。 |
| timeout | number | 否 | 超时时间,单位毫秒(ms)。 |
## TCPSendOptions
TCPSocket发送请求的参数。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| -------- | ------ | ---- | ------------------------------------------------------------ |
| data | string\| ArrayBuffer<sup>7+</sup> | 是 | 发送的数据。 |
| encoding | string | 否 | 字符编码(UTF-8,UTF-16BE,UTF-16LE,UTF-16,US-AECII,ISO-8859-1),默认为UTF-8。 |
## TCPExtraOptions
TCPSocket连接的其他属性。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| ----------------- | ------- | ---- | ------------------------------------------------------------ |
| keepAlive | boolean | 否 | 是否保持连接。默认为false。 |
| OOBInline | boolean | 否 | 是否为OOB内联。默认为false。 |
| TCPNoDelay | boolean | 否 | TCPSocket连接是否无时延。默认为false。 |
| socketLinger | Object | 是 | socket是否继续逗留。<br />- on:是否逗留(true:逗留;false:不逗留)。<br />- linger:逗留时长,单位毫秒(ms),取值范围为0~65535。<br />当入参on设置为true时,才需要设置。 |
| receiveBufferSize | number | 否 | 接收缓冲区大小(单位:Byte)。 |
| sendBufferSize | number | 否 | 发送缓冲区大小(单位:Byte)。 |
| reuseAddress | boolean | 否 | 是否重用地址。默认为false。 |
| socketTimeout | number | 否 | 套接字超时时间,单位毫秒(ms)。 |
## TCP 错误码说明
TCP 错误码映射形式为:2301000 + 内核错误码。
错误码的详细介绍参见[Socket错误码](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/errorcodes/errorcode-socket.md)
## socket.constructTLSSocketInstance<sup>9+</sup>
constructTLSSocketInstance(): TLSSocket
创建并返回一个TLSSocket对象。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :--------------------------------- | :---------------------- |
| [TLSSocket](#tlssocket9) | 返回一个TLSSocket对象。 |
**示例:**
```js
let tls = socket.constructTLSSocketInstance();
```
## TLSSocket<sup>9+</sup>
TLSSocket连接。在调用TLSSocket的方法前,需要先通过[socket.constructTLSSocketInstance](#socketconstructtlssocketinstance9)创建TLSSocket对象。
### bind<sup>9+</sup>
bind\(address: NetAddress, callback: AsyncCallback<void\>\): void
绑定IP地址和端口。使用callback方法作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。成功返回TLSSocket绑定本机的IP地址和端口的结果。 失败返回错误码,错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2303198 | Address already in use. |
| 2300002 | System internal error. |
**示例:**
```js
tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
```
### bind<sup>9+</sup>
bind\(address: NetAddress\): Promise<void\>
绑定IP地址和端口。使用Promise方法作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :------------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回TLSSocket绑定本机的IP地址和端口的结果。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2303198 | Address already in use. |
| 2300002 | System internal error. |
**示例:**
```js
let promise = tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1});
promise.then(() => {
console.log('bind success');
}).catch(err => {
console.log('bind fail');
});
```
### getState<sup>9+</sup>
getState\(callback: AsyncCallback<SocketStateBase\>\): void
在TLSSocket的bind成功之后,获取TLSSocket状态。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------ | ---- | ---------- |
| callback | AsyncCallback\<[SocketStateBase](#socketstatebase)> | 是 | 回调函数。成功返回TLSSocket状态,失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**示例:**
```js
let promise = tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
tls.getState((err, data) => {
if (err) {
console.log('getState fail');
return;
}
console.log('getState success:' + JSON.stringify(data));
});
```
### getState<sup>9+</sup>
getState\(\): Promise<SocketStateBase\>
在TLSSocket的bind成功之后,获取TLSSocket状态。使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :----------------------------------------------- | :----------------------------------------- |
| Promise\<[SocketStateBase](#socketstatebase)> | 以Promise形式返回获取TLSSocket状态的结果。失败返回错误码,错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**示例:**
```js
tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let promise = tls.getState();
promise.then(() => {
console.log('getState success');
}).catch(err => {
console.log('getState fail');
});
```
### setExtraOptions<sup>9+</sup>
setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback<void\>\): void
在TLSSocket的bind成功之后,设置TCPSocket连接的其他属性。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPExtraOptions](#tcpextraoptions) | 是 | TCPSocket连接的其他属性,参考[TCPExtraOptions](#tcpextraoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。成功返回设置TCPSocket连接的其他属性的结果,失败返回错误码,错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 401 | Parameter error. |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**示例:**
```js
tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
tls.setExtraOptions({
keepAlive: true,
OOBInline: true,
TCPNoDelay: true,
socketLinger: { on:true, linger:10 },
receiveBufferSize: 1000,
sendBufferSize: 1000,
reuseAddress: true,
socketTimeout: 3000,
},err => {
if (err) {
console.log('setExtraOptions fail');
return;
}
console.log('setExtraOptions success');
});
```
### setExtraOptions<sup>9+</sup>
setExtraOptions\(options: TCPExtraOptions\): Promise<void\>
在TLSSocket的bind成功之后,设置TCPSocket连接的其他属性,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPExtraOptions](#tcpextraoptions) | 是 | TCPSocket连接的其他属性,参考[TCPExtraOptions](#tcpextraoptions)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :--------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回设置TCPSocket连接的其他属性的结果。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 401 | Parameter error. |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**示例:**
```js
tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let promise = tls.setExtraOptions({
keepAlive: true,
OOBInline: true,
TCPNoDelay: true,
socketLinger: { on:true, linger:10 },
receiveBufferSize: 1000,
sendBufferSize: 1000,
reuseAddress: true,
socketTimeout: 3000,
});
promise.then(() => {
console.log('setExtraOptions success');
}).catch(err => {
console.log('setExtraOptions fail');
});
```
### connect<sup>9+</sup>
connect(options: TLSConnectOptions, callback: AsyncCallback\<void>): void
在TLSSocket上bind成功之后,进行通信连接,并创建和初始化TLS会话,实现建立连接过程,启动与服务器的TLS/SSL握手,实现数据传输功能,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------| ----| --------------- |
| options | [TLSConnectOptions](#tlsconnectoptions9) | 是 | TLSSocket连接所需要的参数。|
| callback | AsyncCallback\<void> | 是 | 回调函数,成功无返回,失败返回错误码,错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 401 | Parameter error. |
| 2303104 | Interrupted system call. |
| 2303109 | Bad file number. |
| 2303111 | Resource temporarily unavailable try again. |
| 2303113 | System permission denied. |
| 2303188 | Socket operation on non-socket. |
| 2303191 | Protocol wrong type for socket. |
| 2303198 | Address already in use. |
| 2303199 | Cannot assign requested address. |
| 2303210 | Connection timed out. |
| 2303501 | SSL is null. |
| 2303502 | Error in tls reading. |
| 2303503 | Error in tls writing |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**示例:**
```js
let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let options = {
ALPNProtocols: ["spdy/1", "http/1.1"],
address: {
address: "192.168.xx.xxx",
port: xxxx,
family: 1,
},
secureOptions: {
key: "xxxx",
cert: "xxxx",
ca: ["xxxx"],
passwd: "xxxx",
protocols: [socket.Protocol.TLSv12],
useRemoteCipherPrefer: true,
signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
cipherSuite: "AES256-SHA256",
},
};
tlsTwoWay.connect(options, (err, data) => {
console.error(err);
console.log(data);
});
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let oneWayOptions = {
address: {
address: "192.168.xxx.xxx",
port: xxxx,
family: 1,
},
secureOptions: {
ca: ["xxxx","xxxx"],
cipherSuite: "AES256-SHA256",
},
};
tlsOneWay.connect(oneWayOptions, (err, data) => {
console.error(err);
console.log(data);
});
```
### connect<sup>9+</sup>
connect(options: TLSConnectOptions): Promise\<void>
在TLSSocket上bind成功之后,进行通信连接,并创建和初始化TLS会话,实现建立连接过程,启动与服务器的TLS/SSL握手,实现数据传输功能,该连接包括两种认证方式,单向认证与双向认证,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------| ----| --------------- |
| options | [TLSConnectOptions](#tlsconnectoptions9) | 是 | 连接所需要的参数。|
**返回值:**
| 类型 | 说明 |
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | 以Promise形式返回,成功无返回,失败返回错误码,错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 401 | Parameter error. |
| 2303104 | Interrupted system call. |
| 2303109 | Bad file number. |
| 2303111 | Resource temporarily unavailable try again. |
| 2303113 | System permission denied. |
| 2303188 | Socket operation on non-socket. |
| 2303191 | Protocol wrong type for socket. |
| 2303198 | Address already in use. |
| 2303199 | Cannot assign requested address. |
| 2303210 | Connection timed out. |
| 2303501 | SSL is null. |
| 2303502 | Error in tls reading. |
| 2303503 | Error in tls writing |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**示例:**
```js
let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let options = {
ALPNProtocols: ["spdy/1", "http/1.1"],
address: {
address: "xxxx",
port: xxxx,
family: 1,
},
secureOptions: {
key: "xxxx",
cert: "xxxx",
ca: ["xxxx"],
passwd: "xxxx",
protocols: [socket.Protocol.TLSv12],
useRemoteCipherPrefer: true,
signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
cipherSuite: "AES256-SHA256",
},
};
tlsTwoWay.connect(options).then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let oneWayOptions = {
address: {
address: "192.168.xxx.xxx",
port: xxxx,
family: 1,
},
secureOptions: {
ca: ["xxxx","xxxx"],
cipherSuite: "AES256-SHA256",
},
};
tlsOneWay.connect(oneWayOptions).then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getRemoteAddress<sup>9+</sup>
getRemoteAddress\(callback: AsyncCallback<NetAddress\>\): void
在TLSSocket通信连接成功之后,获取对端Socket地址。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<[NetAddress](#netaddress)> | 是 | 回调函数。成功返回对端的socket地址,失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**示例:**
```js
tls.getRemoteAddress((err, data) => {
if (err) {
console.log('getRemoteAddress fail');
return;
}
console.log('getRemoteAddress success:' + JSON.stringify(data));
});
```
### getRemoteAddress<sup>9+</sup>
getRemoteAddress\(\): Promise\<NetAddress>
在TLSSocket通信连接成功之后,获取对端Socket地址。使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :------------------------------------------ | :------------------------------------------ |
| Promise\<[NetAddress](#netaddress)> | 以Promise形式返回获取对端socket地址的结果。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**示例:**
```js
let promise = tls.getRemoteAddress();
promise.then(() => {
console.log('getRemoteAddress success');
}).catch(err => {
console.log('getRemoteAddress fail');
});
```
### getCertificate<sup>9+</sup>
getCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)>): void
在TLSSocket通信连接成功之后,获取本地的数字证书,该接口只适用于双向认证时,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)> | 是 | 回调函数,成功返回本地的证书,失败返回错误码,错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303504 | Error looking up x509. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getCertificate((err, data) => {
if (err) {
console.log("getCertificate callback error = " + err);
} else {
console.log("getCertificate callback = " + data);
}
});
```
### getCertificate<sup>9+</sup>
getCertificate():Promise\<[X509CertRawData](#x509certrawdata9)>
在TLSSocket通信连接之后,获取本地的数字证书,该接口只适用于双向认证时,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| -------------- | -------------------- |
| Promise\<[X509CertRawData](#x509certrawdata9)> | 以Promise形式返回本地的数字证书的结果。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303504 | Error looking up x509. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getCertificate().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getRemoteCertificate<sup>9+</sup>
getRemoteCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)>): void
在TLSSocket通信连接成功之后,获取服务端的数字证书,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)> | 是 | 回调函数,返回服务端的证书。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getRemoteCertificate((err, data) => {
if (err) {
console.log("getRemoteCertificate callback error = " + err);
} else {
console.log("getRemoteCertificate callback = " + data);
}
});
```
### getRemoteCertificate<sup>9+</sup>
getRemoteCertificate():Promise\<[X509CertRawData](#x509certrawdata9)>
在TLSSocket通信连接成功之后,获取服务端的数字证书,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| -------------- | -------------------- |
| Promise\<[X509CertRawData](#x509certrawdata9)> | 以Promise形式返回服务端的数字证书的结果。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getRemoteCertificate().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getProtocol<sup>9+</sup>
getProtocol(callback: AsyncCallback\<string>): void
在TLSSocket通信连接成功之后,获取通信的协议版本,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<string> | 是 | 回调函数,返回通信的协议。失败返回错误码,错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 2303501 | SSL is null. |
| 2303505 | Error occurred in the tls system call. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getProtocol((err, data) => {
if (err) {
console.log("getProtocol callback error = " + err);
} else {
console.log("getProtocol callback = " + data);
}
});
```
### getProtocol<sup>9+</sup>
getProtocol():Promise\<string>
在TLSSocket通信连接成功之后,获取通信的协议版本,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| -------------- | -------------------- |
| Promise\<string> | 以Promise形式返回通信的协议。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303505 | Error occurred in the tls system call. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getProtocol().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getCipherSuite<sup>9+</sup>
getCipherSuite(callback: AsyncCallback\<Array\<string>>): void
在TLSSocket通信连接成功之后,获取通信双方协商后的加密套件,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<Array\<string>> | 是 | 回调函数,返回通信双方支持的加密套件。 失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303502 | Error in tls reading. |
| 2303505 | Error occurred in the tls system call. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getCipherSuite((err, data) => {
if (err) {
console.log("getCipherSuite callback error = " + err);
} else {
console.log("getCipherSuite callback = " + data);
}
});
```
### getCipherSuite<sup>9+</sup>
getCipherSuite(): Promise\<Array\<string>>
在TLSSocket通信连接成功之后,获取通信双方协商后的加密套件,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| ---------------------- | --------------------- |
| Promise\<Array\<string>> | 以Promise形式返回通信双方支持的加密套件。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303502 | Error in tls reading. |
| 2303505 | Error occurred in the tls system call. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getCipherSuite().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getSignatureAlgorithms<sup>9+</sup>
getSignatureAlgorithms(callback: AsyncCallback\<Array\<string>>): void
在TLSSocket通信连接成功之后,获取通信双方协商后签名算法,该接口只适配双向认证模式下,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<Array\<string>> | 是 | 回调函数,返回双方支持的签名算法。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getSignatureAlgorithms((err, data) => {
if (err) {
console.log("getSignatureAlgorithms callback error = " + err);
} else {
console.log("getSignatureAlgorithms callback = " + data);
}
});
```
### getSignatureAlgorithms<sup>9+</sup>
getSignatureAlgorithms(): Promise\<Array\<string>>
在TLSSocket通信连接成功之后,获取通信双方协商后的签名算法,该接口只适配双向认证模式下,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| ---------------------- | -------------------- |
| Promise\<Array\<string>> | 以Promise形式返回获取到的双方支持的签名算法。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getSignatureAlgorithms().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### send<sup>9+</sup>
send(data: string, callback: AsyncCallback\<void>): void
在TLSSocket通信连接成功之后,向服务端发送消息,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -----------------------------| ---- | ---------------|
| data | string | 是 | 发送的数据内容。 |
| callback | AsyncCallback\<void> | 是 | 回调函数,返回TLSSocket发送数据的结果。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 401 | Parameter error. |
| 2303501 | SSL is null. |
| 2303503 | Error in tls writing |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**示例:**
```js
tls.send("xxxx", (err) => {
if (err) {
console.log("send callback error = " + err);
} else {
console.log("send success");
}
});
```
### send<sup>9+</sup>
send(data: string): Promise\<void>
在TLSSocket通信连接成功之后,向服务端发送消息,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -----------------------------| ---- | ---------------|
| data | string | 是 | 发送的数据内容。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 401 | Parameter error. |
| 2303501 | SSL is null. |
| 2303503 | Error in tls writing |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**返回值:**
| 类型 | 说明 |
| -------------- | -------------------- |
| Promise\<void> | 以Promise形式返回,返回TLSSocket发送数据的结果。失败返回错误码,错误信息。 |
**示例:**
```js
tls.send("xxxx").then(() =>{
console.log("send success");
}).catch(err => {
console.error(err);
});
```
### close<sup>9+</sup>
close(callback: AsyncCallback\<void>): void
在TLSSocket通信连接成功之后,断开连接,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -----------------------------| ---- | ---------------|
| callback | AsyncCallback\<void> | 是 | 回调函数,成功返回TLSSocket关闭连接的结果。 失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 2303501 | SSL is null. |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**示例:**
```js
tls.close((err) => {
if (err) {
console.log("close callback error = " + err);
} else {
console.log("close success");
}
});
```
### close<sup>9+</sup>
close(): Promise\<void>
在TLSSocket通信连接成功之后,断开连接,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| -------------- | -------------------- |
| Promise\<void> | 以Promise形式返回,返回TLSSocket关闭连接的结果。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 2303501 | SSL is null. |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**示例:**
```js
tls.close().then(() =>{
console.log("close success");
}).catch(err => {
console.error(err);
});
```
## TLSConnectOptions<sup>9+</sup>
TLS连接的操作。
**系统能力**:SystemCapability.Communication.NetStack
| 名称 | 类型 | 必填 | 说明 |
| -------------- | ------------------------------------- | --- |-------------- |
| address | [NetAddress](#netaddress) | 是 | 网关地址。 |
| secureOptions | [TLSSecureOptions](#tlssecureoptions9) | 是 | TLS安全相关操作。|
| ALPNProtocols | Array\<string> | 否 | ALPN协议。 |
## TLSSecureOptions<sup>9+</sup>
TLS安全相关操作,其中ca证书为必选参数,其他参数为可选参数。当本地证书cert和私钥key不为空时,开启双向验证模式。cert和key其中一项为空时,开启单向验证模式。
**系统能力**:SystemCapability.Communication.NetStack
| 名称 | 类型 | 必填 | 说明 |
| --------------------- | ------------------------------------------------------ | --- |----------------------------------- |
| ca | string \| Array\<string> | 是 | 服务端的ca证书,用于认证校验服务端的数字证书。|
| cert | string | 否 | 本地客户端的数字证书。 |
| key | string | 否 | 本地数字证书的私钥。 |
| passwd | string | 否 | 读取私钥的密码。 |
| protocols | [Protocol](#protocol9) \|Array\<[Protocol](#protocol9)> | 否 | TLS的协议版本。 |
| useRemoteCipherPrefer | boolean | 否 | 优先使用对等方的密码套件。 |
| signatureAlgorithms | string | 否 | 通信过程中的签名算法。 |
| cipherSuite | string | 否 | 通信过程中的加密套件。 |
## Protocol<sup>9+</sup>
TLS通信的协议版本。
**系统能力**:SystemCapability.Communication.NetStack
| 名称 | 值 | 说明 |
| --------- | --------- |------------------ |
| TLSv12 | "TLSv1.2" | 使用TLSv1.2协议通信。 |
| TLSv13 | "TLSv1.3" | 使用TLSv1.3协议通信。 |
## X509CertRawData<sup>9+</sup>
存储证书的数据。
**系统能力**:SystemCapability.Communication.NetStack
| 类型 | 说明 |
| --------------------------------------------------------------------- | --------------------- |
|[cryptoFramework.EncodingBlob](js-apis-cryptoFramework.md#datablob) | 存储证书的数据和编码格式 |
\ No newline at end of file
# @ohos.net.socket (Socket连接)
> **说明:**
>
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```js
import socket from '@ohos.net.socket';
```
## socket.constructUDPSocketInstance
constructUDPSocketInstance\(\): UDPSocket
创建一个UDPSocket对象。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :--------------------------------- | :---------------------- |
| [UDPSocket](#udpsocket) | 返回一个UDPSocket对象。 |
**示例:**
```js
let udp = socket.constructUDPSocketInstance();
```
## UDPSocket
UDPSocket连接。在调用UDPSocket的方法前,需要先通过[socket.constructUDPSocketInstance](#socketconstructudpsocketinstance)创建UDPSocket对象。
### bind
bind\(address: NetAddress, callback: AsyncCallback<void\>\): void
绑定IP地址和端口,端口可以指定或由系统随机分配。使用callback方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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\>
绑定IP地址和端口,端口可以指定或由系统随机分配。使用Promise方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :----------------------------------------- |
| Promise\<void\> | 以Promise形式异步返回UDPSocket绑定的结果。 |
**示例:**
```js
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
通过UDPSocket连接发送数据。使用callback方式作为异步方法。
发送数据前,需要先调用[UDPSocket.bind()](#bind)绑定IP地址和端口。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [UDPSendOptions](#udpsendoptions) | 是 | UDPSocket发送参数,参考[UDPSendOptions](#udpsendoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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\>
通过UDPSocket连接发送数据。使用Promise方式作为异步方法。
发送数据前,需要先调用[UDPSocket.bind()](#bind)绑定IP地址和端口。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [UDPSendOptions](#udpsendoptions) | 是 | UDPSocket发送参数,参考[UDPSendOptions](#udpsendoptions)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :--------------------------------------------- |
| Promise\<void\> | 以Promise形式返回UDPSocket连接发送数据的结果。 |
**示例:**
```js
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
关闭UDPSocket连接。使用callback方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | ---------- |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
let udp = socket.constructUDPSocketInstance();
udp.close(err => {
if (err) {
console.log('close fail');
return;
}
console.log('close success');
})
```
### close
close\(\): Promise<void\>
关闭UDPSocket连接。使用Promise方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :-------------- | :----------------------------------------- |
| Promise\<void\> | 以Promise形式返回关闭UDPSocket连接的结果。 |
**示例:**
```js
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
获取UDPSocket状态。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------ | ---- | ---------- |
| callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | 是 | 回调函数。 |
**示例:**
```js
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\>
获取UDPSocket状态。使用Promise方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :----------------------------------------------- | :----------------------------------------- |
| Promise<[SocketStateBase](#socketstatebase)> | 以Promise形式返回获取UDPSocket状态的结果。 |
**示例:**
```js
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
设置UDPSocket连接的其他属性。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [UDPExtraOptions](#udpextraoptions) | 是 | UDPSocket连接的其他属性,参考[UDPExtraOptions](#udpextraoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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\>
设置UDPSocket连接的其他属性。使用Promise方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [UDPExtraOptions](#udpextraoptions) | 是 | UDPSocket连接的其他属性,参考[UDPExtraOptions](#udpextraoptions)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :--------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回设置UDPSocket连接的其他属性的结果。 |
**示例:**
```js
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
订阅UDPSocket连接的接收消息事件。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | 是 | 订阅的事件类型。'message':接收消息事件。 |
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | 是 | 回调函数。 |
**示例:**
```js
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
取消订阅UDPSocket连接的接收消息事件。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | 是 | 订阅的事件类型。'message':接收消息事件。 |
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | 否 | 回调函数。 |
**示例:**
```js
let udp = socket.constructUDPSocketInstance();
let callback = value =>{
console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
}
udp.on('message', callback);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
udp.off('message', callback);
udp.off('message');
```
### on\('listening' | 'close'\)
on\(type: 'listening' | 'close', callback: Callback<void\>\): void
订阅UDPSocket连接的数据包消息事件或关闭事件。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 订阅的事件类型。<br />- 'listening':数据包消息事件。<br />- 'close':关闭事件。 |
| callback | Callback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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
取消订阅UDPSocket连接的数据包消息事件或关闭事件。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 订阅事件类型。<br />- 'listening':数据包消息事件。<br />- 'close':关闭事件。 |
| callback | Callback\<void\> | 否 | 回调函数。 |
**示例:**
```js
let udp = socket.constructUDPSocketInstance();
let callback1 = () =>{
console.log("on listening, success");
}
udp.on('listening', callback1);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
udp.off('listening', callback1);
udp.off('listening');
let callback2 = () =>{
console.log("on close, success");
}
udp.on('close', callback2);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
udp.off('close', callback2);
udp.off('close');
```
### on\('error'\)
on\(type: 'error', callback: ErrorCallback\): void
订阅UDPSocket连接的error事件。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | ------------------------------------ |
| type | string | 是 | 订阅的事件类型。'error':error事件。 |
| callback | ErrorCallback | 是 | 回调函数。 |
**示例:**
```js
let udp = socket.constructUDPSocketInstance();
udp.on('error', err => {
console.log("on error, err:" + JSON.stringify(err))
});
```
### off\('error'\)
off\(type: 'error', callback?: ErrorCallback\): void
取消订阅UDPSocket连接的error事件。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | ------------------------------------ |
| type | string | 是 | 订阅的事件类型。'error':error事件。 |
| callback | ErrorCallback | 否 | 回调函数。 |
**示例:**
```js
let udp = socket.constructUDPSocketInstance();
let callback = err =>{
console.log("on error, err:" + JSON.stringify(err));
}
udp.on('error', callback);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
udp.off('error', callback);
udp.off('error');
```
## NetAddress
目标地址信息。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| ------- | ------ | ---- | ------------------------------------------------------------ |
| address | string | 是 | 本地绑定的ip地址。 |
| port | number | 否 | 端口号 ,范围0~65535。如果不指定系统随机分配端口。 |
| family | number | 否 | 网络协议类型,可选类型:<br />- 1:IPv4<br />- 2:IPv6<br />默认为1。 |
## UDPSendOptions
UDPSocket发送参数。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------- | ---- | -------------- |
| data | string \| ArrayBuffer<sup>7+</sup> | 是 | 发送的数据。 |
| address | [NetAddress](#netaddress) | 是 | 目标地址信息。 |
## UDPExtraOptions
UDPSocket连接的其他属性。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| ----------------- | ------- | ---- | -------------------------------- |
| broadcast | boolean | 否 | 是否可以发送广播。默认为false。 |
| receiveBufferSize | number | 否 | 接收缓冲区大小(单位:Byte)。 |
| sendBufferSize | number | 否 | 发送缓冲区大小(单位:Byte)。 |
| reuseAddress | boolean | 否 | 是否重用地址。默认为false。 |
| socketTimeout | number | 否 | 套接字超时时间,单位毫秒(ms)。 |
## SocketStateBase
Socket的状态信息。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| ----------- | ------- | ---- | ---------- |
| isBound | boolean | 是 | 是否绑定。 |
| isClose | boolean | 是 | 是否关闭。 |
| isConnected | boolean | 是 | 是否连接。 |
## SocketRemoteInfo
Socket的连接信息。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| ------- | ------ | ---- | ------------------------------------------------------------ |
| address | string | 是 | 本地绑定的ip地址。 |
| family | string | 是 | 网络协议类型,可选类型:<br />- IPv4<br />- IPv6<br />默认为IPv4。 |
| port | number | 是 | 端口号,范围0~65535。 |
| size | number | 是 | 服务器响应信息的字节长度。 |
## UDP 错误码说明
UDP 错误码映射形式为:2301000 + 内核错误码。
## socket.constructTCPSocketInstance
constructTCPSocketInstance\(\): TCPSocket
创建一个TCPSocket对象。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :--------------------------------- | :---------------------- |
| [TCPSocket](#tcpsocket) | 返回一个TCPSocket对象。 |
**示例:**
```js
let tcp = socket.constructTCPSocketInstance();
```
## TCPSocket
TCPSocket连接。在调用TCPSocket的方法前,需要先通过[socket.constructTCPSocketInstance](#socketconstructtcpsocketinstance)创建TCPSocket对象。
### bind
bind\(address: NetAddress, callback: AsyncCallback<void\>\): void
绑定IP地址和端口,端口可以指定或由系统随机分配。使用callback方法作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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\>
绑定IP地址和端口,端口可以指定或由系统随机分配。使用Promise方法作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :------------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回TCPSocket绑定本机的IP地址和端口的结果。 |
**示例:**
```js
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
连接到指定的IP地址和端口。使用callback方法作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPConnectOptions](#tcpconnectoptions) | 是 | TCPSocket连接的参数,参考[TCPConnectOptions](#tcpconnectoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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\>
连接到指定的IP地址和端口。使用promise方法作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPConnectOptions](#tcpconnectoptions) | 是 | TCPSocket连接的参数,参考[TCPConnectOptions](#tcpconnectoptions)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :--------------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回TCPSocket连接到指定的IP地址和端口的结果。 |
**示例:**
```js
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
通过TCPSocket连接发送数据。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPSendOptions](#tcpsendoptions) | 是 | TCPSocket发送请求的参数,参考[TCPSendOptions](#tcpsendoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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\>
通过TCPSocket连接发送数据。使用Promise方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPSendOptions](#tcpsendoptions) | 是 | TCPSocket发送请求的参数,参考[TCPSendOptions](#tcpsendoptions)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回通过TCPSocket连接发送数据的结果。 |
**示例:**
```js
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
关闭TCPSocket连接。使用callback方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | ---------- |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
let tcp = socket.constructTCPSocketInstance();
tcp.close(err => {
if (err) {
console.log('close fail');
return;
}
console.log('close success');
})
```
### close
close\(\): Promise<void\>
关闭TCPSocket连接。使用Promise方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :-------------- | :----------------------------------------- |
| Promise\<void\> | 以Promise形式返回关闭TCPSocket连接的结果。 |
**示例:**
```js
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
获取对端Socket地址。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------- | ---- | ---------- |
| callback | AsyncCallback<[NetAddress](#netaddress)> | 是 | 回调函数。 |
**示例:**
```js
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\>
获取对端Socket地址。使用Promise方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :------------------------------------------ | :------------------------------------------ |
| Promise<[NetAddress](#netaddress)> | 以Promise形式返回获取对端socket地址的结果。 |
**示例:**
```js
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');
}).catch(err => {
console.log('getRemoteAddressfail');
});
}).catch(err => {
console.log('connect fail');
});
```
### getState
getState\(callback: AsyncCallback<SocketStateBase\>\): void
获取TCPSocket状态。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)或[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------ | ---- | ---------- |
| callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | 是 | 回调函数。 |
**示例:**
```js
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\>
获取TCPSocket状态。使用Promise方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)或[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :----------------------------------------------- | :----------------------------------------- |
| Promise<[SocketStateBase](#socketstatebase)> | 以Promise形式返回获取TCPSocket状态的结果。 |
**示例:**
```js
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');
}).catch(err => {
console.log('getState fail');
});
}).catch(err => {
console.log('connect fail');
});
```
### setExtraOptions
setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback<void\>\): void
设置TCPSocket连接的其他属性。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)或[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPExtraOptions](#tcpextraoptions) | 是 | TCPSocket连接的其他属性,参考[TCPExtraOptions](#tcpextraoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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\>
设置TCPSocket连接的其他属性,使用Promise方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)或[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPExtraOptions](#tcpextraoptions) | 是 | TCPSocket连接的其他属性,参考[TCPExtraOptions](#tcpextraoptions)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :--------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回设置TCPSocket连接的其他属性的结果。 |
**示例:**
```js
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
订阅TCPSocket连接的接收消息事件。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | 是 | 订阅的事件类型。'message':接收消息事件。 |
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | 是 | 回调函数。 |
**示例:**
```js
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
取消订阅TCPSocket连接的接收消息事件。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | 是 | 订阅的事件类型。'message':接收消息事件。 |
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | 否 | 回调函数。 |
**示例:**
```js
let tcp = socket.constructTCPSocketInstance();
let callback = value =>{
console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
}
tcp.on('message', callback);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
tcp.off('message', callback);
tcp.off('message');
```
### on\('connect' | 'close'\)
on\(type: 'connect' | 'close', callback: Callback<void\>\): void
订阅TCPSocket的连接事件或关闭事件。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 订阅的事件类型。<br />- 'connect':连接事件。<br />- 'close':关闭事件。 |
| callback | Callback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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
取消订阅TCPSocket的连接事件或关闭事件。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 订阅的事件类型。<br />- 'connect':连接事件。<br />- 'close':关闭事件。 |
| callback | Callback\<void\> | 否 | 回调函数。 |
**示例:**
```js
let tcp = socket.constructTCPSocketInstance();
let callback1 = () =>{
console.log("on connect success");
}
tcp.on('connect', callback1);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
tcp.off('connect', callback1);
tcp.off('connect');
let callback2 = () =>{
console.log("on close success");
}
tcp.on('close', callback2);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
tcp.off('close', callback2);
tcp.off('close');
```
### on\('error'\)
on\(type: 'error', callback: ErrorCallback\): void
订阅TCPSocket连接的error事件。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | ------------------------------------ |
| type | string | 是 | 订阅的事件类型。'error':error事件。 |
| callback | ErrorCallback | 是 | 回调函数。 |
**示例:**
```js
let tcp = socket.constructTCPSocketInstance();
tcp.on('error', err => {
console.log("on error, err:" + JSON.stringify(err))
});
```
### off\('error'\)
off\(type: 'error', callback?: ErrorCallback\): void
取消订阅TCPSocket连接的error事件。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | ------------------------------------ |
| type | string | 是 | 订阅的事件类型。'error':error事件。 |
| callback | ErrorCallback | 否 | 回调函数。 |
**示例:**
```js
let tcp = socket.constructTCPSocketInstance();
let callback = err =>{
console.log("on error, err:" + JSON.stringify(err));
}
tcp.on('error', callback);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
tcp.off('error', callback);
tcp.off('error');
```
## TCPConnectOptions
TCPSocket连接的参数。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------- | ---- | -------------------------- |
| address | [NetAddress](#netaddress) | 是 | 绑定的地址以及端口。 |
| timeout | number | 否 | 超时时间,单位毫秒(ms)。 |
## TCPSendOptions
TCPSocket发送请求的参数。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| -------- | ------ | ---- | ------------------------------------------------------------ |
| data | string\| ArrayBuffer<sup>7+</sup> | 是 | 发送的数据。 |
| encoding | string | 否 | 字符编码(UTF-8,UTF-16BE,UTF-16LE,UTF-16,US-AECII,ISO-8859-1),默认为UTF-8。 |
## TCPExtraOptions
TCPSocket连接的其他属性。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| ----------------- | ------- | ---- | ------------------------------------------------------------ |
| keepAlive | boolean | 否 | 是否保持连接。默认为false。 |
| OOBInline | boolean | 否 | 是否为OOB内联。默认为false。 |
| TCPNoDelay | boolean | 否 | TCPSocket连接是否无时延。默认为false。 |
| socketLinger | Object | 是 | socket是否继续逗留。<br />- on:是否逗留(true:逗留;false:不逗留)。<br />- linger:逗留时长,单位毫秒(ms),取值范围为0~65535。<br />当入参on设置为true时,才需要设置。 |
| receiveBufferSize | number | 否 | 接收缓冲区大小(单位:Byte)。 |
| sendBufferSize | number | 否 | 发送缓冲区大小(单位:Byte)。 |
| reuseAddress | boolean | 否 | 是否重用地址。默认为false。 |
| socketTimeout | number | 否 | 套接字超时时间,单位毫秒(ms)。 |
## TCP 错误码说明
TCP 错误码映射形式为:2301000 + 内核错误码。
错误码的详细介绍参见[Socket错误码](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/errorcodes/errorcode-socket.md)
## socket.constructTLSSocketInstance<sup>9+</sup>
constructTLSSocketInstance(): TLSSocket
创建并返回一个TLSSocket对象。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :--------------------------------- | :---------------------- |
| [TLSSocket](#tlssocket9) | 返回一个TLSSocket对象。 |
**示例:**
```js
let tls = socket.constructTLSSocketInstance();
```
## TLSSocket<sup>9+</sup>
TLSSocket连接。在调用TLSSocket的方法前,需要先通过[socket.constructTLSSocketInstance](#socketconstructtlssocketinstance9)创建TLSSocket对象。
### bind<sup>9+</sup>
bind\(address: NetAddress, callback: AsyncCallback<void\>\): void
绑定IP地址和端口。使用callback方法作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。成功返回TLSSocket绑定本机的IP地址和端口的结果。 失败返回错误码,错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2303198 | Address already in use. |
| 2300002 | System internal error. |
**示例:**
```js
tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
```
### bind<sup>9+</sup>
bind\(address: NetAddress\): Promise<void\>
绑定IP地址和端口。使用Promise方法作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :------------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回TLSSocket绑定本机的IP地址和端口的结果。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2303198 | Address already in use. |
| 2300002 | System internal error. |
**示例:**
```js
let promise = tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1});
promise.then(() => {
console.log('bind success');
}).catch(err => {
console.log('bind fail');
});
```
### getState<sup>9+</sup>
getState\(callback: AsyncCallback<SocketStateBase\>\): void
在TLSSocket的bind成功之后,获取TLSSocket状态。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------ | ---- | ---------- |
| callback | AsyncCallback\<[SocketStateBase](#socketstatebase)> | 是 | 回调函数。成功返回TLSSocket状态,失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**示例:**
```js
let promise = tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
tls.getState((err, data) => {
if (err) {
console.log('getState fail');
return;
}
console.log('getState success:' + JSON.stringify(data));
});
```
### getState<sup>9+</sup>
getState\(\): Promise<SocketStateBase\>
在TLSSocket的bind成功之后,获取TLSSocket状态。使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :----------------------------------------------- | :----------------------------------------- |
| Promise\<[SocketStateBase](#socketstatebase)> | 以Promise形式返回获取TLSSocket状态的结果。失败返回错误码,错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**示例:**
```js
tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let promise = tls.getState();
promise.then(() => {
console.log('getState success');
}).catch(err => {
console.log('getState fail');
});
```
### setExtraOptions<sup>9+</sup>
setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback<void\>\): void
在TLSSocket的bind成功之后,设置TCPSocket连接的其他属性。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPExtraOptions](#tcpextraoptions) | 是 | TCPSocket连接的其他属性,参考[TCPExtraOptions](#tcpextraoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。成功返回设置TCPSocket连接的其他属性的结果,失败返回错误码,错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 401 | Parameter error. |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**示例:**
```js
tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
tls.setExtraOptions({
keepAlive: true,
OOBInline: true,
TCPNoDelay: true,
socketLinger: { on:true, linger:10 },
receiveBufferSize: 1000,
sendBufferSize: 1000,
reuseAddress: true,
socketTimeout: 3000,
},err => {
if (err) {
console.log('setExtraOptions fail');
return;
}
console.log('setExtraOptions success');
});
```
### setExtraOptions<sup>9+</sup>
setExtraOptions\(options: TCPExtraOptions\): Promise<void\>
在TLSSocket的bind成功之后,设置TCPSocket连接的其他属性,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPExtraOptions](#tcpextraoptions) | 是 | TCPSocket连接的其他属性,参考[TCPExtraOptions](#tcpextraoptions)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :--------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回设置TCPSocket连接的其他属性的结果。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 401 | Parameter error. |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**示例:**
```js
tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let promise = tls.setExtraOptions({
keepAlive: true,
OOBInline: true,
TCPNoDelay: true,
socketLinger: { on:true, linger:10 },
receiveBufferSize: 1000,
sendBufferSize: 1000,
reuseAddress: true,
socketTimeout: 3000,
});
promise.then(() => {
console.log('setExtraOptions success');
}).catch(err => {
console.log('setExtraOptions fail');
});
```
### connect<sup>9+</sup>
connect(options: TLSConnectOptions, callback: AsyncCallback\<void>): void
在TLSSocket上bind成功之后,进行通信连接,并创建和初始化TLS会话,实现建立连接过程,启动与服务器的TLS/SSL握手,实现数据传输功能,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------| ----| --------------- |
| options | [TLSConnectOptions](#tlsconnectoptions9) | 是 | TLSSocket连接所需要的参数。|
| callback | AsyncCallback\<void> | 是 | 回调函数,成功无返回,失败返回错误码,错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 401 | Parameter error. |
| 2303104 | Interrupted system call. |
| 2303109 | Bad file number. |
| 2303111 | Resource temporarily unavailable try again. |
| 2303113 | System permission denied. |
| 2303188 | Socket operation on non-socket. |
| 2303191 | Protocol wrong type for socket. |
| 2303198 | Address already in use. |
| 2303199 | Cannot assign requested address. |
| 2303210 | Connection timed out. |
| 2303501 | SSL is null. |
| 2303502 | Error in tls reading. |
| 2303503 | Error in tls writing |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**示例:**
```js
let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let options = {
ALPNProtocols: ["spdy/1", "http/1.1"],
address: {
address: "192.168.xx.xxx",
port: xxxx,
family: 1,
},
secureOptions: {
key: "xxxx",
cert: "xxxx",
ca: ["xxxx"],
passwd: "xxxx",
protocols: [socket.Protocol.TLSv12],
useRemoteCipherPrefer: true,
signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
cipherSuite: "AES256-SHA256",
},
};
tlsTwoWay.connect(options, (err, data) => {
console.error(err);
console.log(data);
});
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let oneWayOptions = {
address: {
address: "192.168.xxx.xxx",
port: xxxx,
family: 1,
},
secureOptions: {
ca: ["xxxx","xxxx"],
cipherSuite: "AES256-SHA256",
},
};
tlsOneWay.connect(oneWayOptions, (err, data) => {
console.error(err);
console.log(data);
});
```
### connect<sup>9+</sup>
connect(options: TLSConnectOptions): Promise\<void>
在TLSSocket上bind成功之后,进行通信连接,并创建和初始化TLS会话,实现建立连接过程,启动与服务器的TLS/SSL握手,实现数据传输功能,该连接包括两种认证方式,单向认证与双向认证,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------| ----| --------------- |
| options | [TLSConnectOptions](#tlsconnectoptions9) | 是 | 连接所需要的参数。|
**返回值:**
| 类型 | 说明 |
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | 以Promise形式返回,成功无返回,失败返回错误码,错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 401 | Parameter error. |
| 2303104 | Interrupted system call. |
| 2303109 | Bad file number. |
| 2303111 | Resource temporarily unavailable try again. |
| 2303113 | System permission denied. |
| 2303188 | Socket operation on non-socket. |
| 2303191 | Protocol wrong type for socket. |
| 2303198 | Address already in use. |
| 2303199 | Cannot assign requested address. |
| 2303210 | Connection timed out. |
| 2303501 | SSL is null. |
| 2303502 | Error in tls reading. |
| 2303503 | Error in tls writing |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**示例:**
```js
let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let options = {
ALPNProtocols: ["spdy/1", "http/1.1"],
address: {
address: "xxxx",
port: xxxx,
family: 1,
},
secureOptions: {
key: "xxxx",
cert: "xxxx",
ca: ["xxxx"],
passwd: "xxxx",
protocols: [socket.Protocol.TLSv12],
useRemoteCipherPrefer: true,
signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
cipherSuite: "AES256-SHA256",
},
};
tlsTwoWay.connect(options).then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let oneWayOptions = {
address: {
address: "192.168.xxx.xxx",
port: xxxx,
family: 1,
},
secureOptions: {
ca: ["xxxx","xxxx"],
cipherSuite: "AES256-SHA256",
},
};
tlsOneWay.connect(oneWayOptions).then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getRemoteAddress<sup>9+</sup>
getRemoteAddress\(callback: AsyncCallback<NetAddress\>\): void
在TLSSocket通信连接成功之后,获取对端Socket地址。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<[NetAddress](#netaddress)> | 是 | 回调函数。成功返回对端的socket地址,失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**示例:**
```js
tls.getRemoteAddress((err, data) => {
if (err) {
console.log('getRemoteAddress fail');
return;
}
console.log('getRemoteAddress success:' + JSON.stringify(data));
});
```
### getRemoteAddress<sup>9+</sup>
getRemoteAddress\(\): Promise\<NetAddress>
在TLSSocket通信连接成功之后,获取对端Socket地址。使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :------------------------------------------ | :------------------------------------------ |
| Promise\<[NetAddress](#netaddress)> | 以Promise形式返回获取对端socket地址的结果。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**示例:**
```js
let promise = tls.getRemoteAddress();
promise.then(() => {
console.log('getRemoteAddress success');
}).catch(err => {
console.log('getRemoteAddress fail');
});
```
### getCertificate<sup>9+</sup>
getCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)>): void
在TLSSocket通信连接成功之后,获取本地的数字证书,该接口只适用于双向认证时,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)> | 是 | 回调函数,成功返回本地的证书,失败返回错误码,错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303504 | Error looking up x509. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getCertificate((err, data) => {
if (err) {
console.log("getCertificate callback error = " + err);
} else {
console.log("getCertificate callback = " + data);
}
});
```
### getCertificate<sup>9+</sup>
getCertificate():Promise\<[X509CertRawData](#x509certrawdata9)>
在TLSSocket通信连接之后,获取本地的数字证书,该接口只适用于双向认证时,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| -------------- | -------------------- |
| Promise\<[X509CertRawData](#x509certrawdata9)> | 以Promise形式返回本地的数字证书的结果。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303504 | Error looking up x509. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getCertificate().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getRemoteCertificate<sup>9+</sup>
getRemoteCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)>): void
在TLSSocket通信连接成功之后,获取服务端的数字证书,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)> | 是 | 回调函数,返回服务端的证书。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getRemoteCertificate((err, data) => {
if (err) {
console.log("getRemoteCertificate callback error = " + err);
} else {
console.log("getRemoteCertificate callback = " + data);
}
});
```
### getRemoteCertificate<sup>9+</sup>
getRemoteCertificate():Promise\<[X509CertRawData](#x509certrawdata9)>
在TLSSocket通信连接成功之后,获取服务端的数字证书,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| -------------- | -------------------- |
| Promise\<[X509CertRawData](#x509certrawdata9)> | 以Promise形式返回服务端的数字证书的结果。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getRemoteCertificate().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getProtocol<sup>9+</sup>
getProtocol(callback: AsyncCallback\<string>): void
在TLSSocket通信连接成功之后,获取通信的协议版本,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<string> | 是 | 回调函数,返回通信的协议。失败返回错误码,错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 2303501 | SSL is null. |
| 2303505 | Error occurred in the tls system call. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getProtocol((err, data) => {
if (err) {
console.log("getProtocol callback error = " + err);
} else {
console.log("getProtocol callback = " + data);
}
});
```
### getProtocol<sup>9+</sup>
getProtocol():Promise\<string>
在TLSSocket通信连接成功之后,获取通信的协议版本,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| -------------- | -------------------- |
| Promise\<string> | 以Promise形式返回通信的协议。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303505 | Error occurred in the tls system call. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getProtocol().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getCipherSuite<sup>9+</sup>
getCipherSuite(callback: AsyncCallback\<Array\<string>>): void
在TLSSocket通信连接成功之后,获取通信双方协商后的加密套件,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<Array\<string>> | 是 | 回调函数,返回通信双方支持的加密套件。 失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303502 | Error in tls reading. |
| 2303505 | Error occurred in the tls system call. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getCipherSuite((err, data) => {
if (err) {
console.log("getCipherSuite callback error = " + err);
} else {
console.log("getCipherSuite callback = " + data);
}
});
```
### getCipherSuite<sup>9+</sup>
getCipherSuite(): Promise\<Array\<string>>
在TLSSocket通信连接成功之后,获取通信双方协商后的加密套件,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| ---------------------- | --------------------- |
| Promise\<Array\<string>> | 以Promise形式返回通信双方支持的加密套件。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303502 | Error in tls reading. |
| 2303505 | Error occurred in the tls system call. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getCipherSuite().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getSignatureAlgorithms<sup>9+</sup>
getSignatureAlgorithms(callback: AsyncCallback\<Array\<string>>): void
在TLSSocket通信连接成功之后,获取通信双方协商后签名算法,该接口只适配双向认证模式下,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<Array\<string>> | 是 | 回调函数,返回双方支持的签名算法。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getSignatureAlgorithms((err, data) => {
if (err) {
console.log("getSignatureAlgorithms callback error = " + err);
} else {
console.log("getSignatureAlgorithms callback = " + data);
}
});
```
### getSignatureAlgorithms<sup>9+</sup>
getSignatureAlgorithms(): Promise\<Array\<string>>
在TLSSocket通信连接成功之后,获取通信双方协商后的签名算法,该接口只适配双向认证模式下,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| ---------------------- | -------------------- |
| Promise\<Array\<string>> | 以Promise形式返回获取到的双方支持的签名算法。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getSignatureAlgorithms().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### send<sup>9+</sup>
send(data: string, callback: AsyncCallback\<void>): void
在TLSSocket通信连接成功之后,向服务端发送消息,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -----------------------------| ---- | ---------------|
| data | string | 是 | 发送的数据内容。 |
| callback | AsyncCallback\<void> | 是 | 回调函数,返回TLSSocket发送数据的结果。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 401 | Parameter error. |
| 2303501 | SSL is null. |
| 2303503 | Error in tls writing |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**示例:**
```js
tls.send("xxxx", (err) => {
if (err) {
console.log("send callback error = " + err);
} else {
console.log("send success");
}
});
```
### send<sup>9+</sup>
send(data: string): Promise\<void>
在TLSSocket通信连接成功之后,向服务端发送消息,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -----------------------------| ---- | ---------------|
| data | string | 是 | 发送的数据内容。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 401 | Parameter error. |
| 2303501 | SSL is null. |
| 2303503 | Error in tls writing |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**返回值:**
| 类型 | 说明 |
| -------------- | -------------------- |
| Promise\<void> | 以Promise形式返回,返回TLSSocket发送数据的结果。失败返回错误码,错误信息。 |
**示例:**
```js
tls.send("xxxx").then(() =>{
console.log("send success");
}).catch(err => {
console.error(err);
});
```
### close<sup>9+</sup>
close(callback: AsyncCallback\<void>): void
在TLSSocket通信连接成功之后,断开连接,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -----------------------------| ---- | ---------------|
| callback | AsyncCallback\<void> | 是 | 回调函数,成功返回TLSSocket关闭连接的结果。 失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 2303501 | SSL is null. |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**示例:**
```js
tls.close((err) => {
if (err) {
console.log("close callback error = " + err);
} else {
console.log("close success");
}
});
```
### close<sup>9+</sup>
close(): Promise\<void>
在TLSSocket通信连接成功之后,断开连接,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| -------------- | -------------------- |
| Promise\<void> | 以Promise形式返回,返回TLSSocket关闭连接的结果。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 2303501 | SSL is null. |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**示例:**
```js
tls.close().then(() =>{
console.log("close success");
}).catch(err => {
console.error(err);
});
```
## TLSConnectOptions<sup>9+</sup>
TLS连接的操作。
**系统能力**:SystemCapability.Communication.NetStack
| 名称 | 类型 | 必填 | 说明 |
| -------------- | ------------------------------------- | --- |-------------- |
| address | [NetAddress](#netaddress) | 是 | 网关地址。 |
| secureOptions | [TLSSecureOptions](#tlssecureoptions9) | 是 | TLS安全相关操作。|
| ALPNProtocols | Array\<string> | 否 | ALPN协议。 |
## TLSSecureOptions<sup>9+</sup>
TLS安全相关操作,其中ca证书为必选参数,其他参数为可选参数。当本地证书cert和私钥key不为空时,开启双向验证模式。cert和key其中一项为空时,开启单向验证模式。
**系统能力**:SystemCapability.Communication.NetStack
| 名称 | 类型 | 必填 | 说明 |
| --------------------- | ------------------------------------------------------ | --- |----------------------------------- |
| ca | string \| Array\<string> | 是 | 服务端的ca证书,用于认证校验服务端的数字证书。|
| cert | string | 否 | 本地客户端的数字证书。 |
| key | string | 否 | 本地数字证书的私钥。 |
| passwd | string | 否 | 读取私钥的密码。 |
| protocols | [Protocol](#protocol9) \|Array\<[Protocol](#protocol9)> | 否 | TLS的协议版本。 |
| useRemoteCipherPrefer | boolean | 否 | 优先使用对等方的密码套件。 |
| signatureAlgorithms | string | 否 | 通信过程中的签名算法。 |
| cipherSuite | string | 否 | 通信过程中的加密套件。 |
## Protocol<sup>9+</sup>
TLS通信的协议版本。
**系统能力**:SystemCapability.Communication.NetStack
| 名称 | 值 | 说明 |
| --------- | --------- |------------------ |
| TLSv12 | "TLSv1.2" | 使用TLSv1.2协议通信。 |
| TLSv13 | "TLSv1.3" | 使用TLSv1.3协议通信。 |
## X509CertRawData<sup>9+</sup>
存储证书的数据。
**系统能力**:SystemCapability.Communication.NetStack
| 类型 | 说明 |
| --------------------------------------------------------------------- | --------------------- |
|[cryptoFramework.EncodingBlob](js-apis-cryptoFramework.md#datablob) | 存储证书的数据和编码格式 |
\ No newline at end of file
# @ohos.net.socket (Socket连接)
> **说明:**
>
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```js
import socket from '@ohos.net.socket';
```
## socket.constructUDPSocketInstance
constructUDPSocketInstance\(\): UDPSocket
创建一个UDPSocket对象。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :--------------------------------- | :---------------------- |
| [UDPSocket](#udpsocket) | 返回一个UDPSocket对象。 |
**示例:**
```js
let udp = socket.constructUDPSocketInstance();
```
## UDPSocket
UDPSocket连接。在调用UDPSocket的方法前,需要先通过[socket.constructUDPSocketInstance](#socketconstructudpsocketinstance)创建UDPSocket对象。
### bind
bind\(address: NetAddress, callback: AsyncCallback<void\>\): void
绑定IP地址和端口,端口可以指定或由系统随机分配。使用callback方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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\>
绑定IP地址和端口,端口可以指定或由系统随机分配。使用Promise方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :----------------------------------------- |
| Promise\<void\> | 以Promise形式异步返回UDPSocket绑定的结果。 |
**示例:**
```js
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
通过UDPSocket连接发送数据。使用callback方式作为异步方法。
发送数据前,需要先调用[UDPSocket.bind()](#bind)绑定IP地址和端口。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [UDPSendOptions](#udpsendoptions) | 是 | UDPSocket发送参数,参考[UDPSendOptions](#udpsendoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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\>
通过UDPSocket连接发送数据。使用Promise方式作为异步方法。
发送数据前,需要先调用[UDPSocket.bind()](#bind)绑定IP地址和端口。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [UDPSendOptions](#udpsendoptions) | 是 | UDPSocket发送参数,参考[UDPSendOptions](#udpsendoptions)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :--------------------------------------------- |
| Promise\<void\> | 以Promise形式返回UDPSocket连接发送数据的结果。 |
**示例:**
```js
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
关闭UDPSocket连接。使用callback方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | ---------- |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
let udp = socket.constructUDPSocketInstance();
udp.close(err => {
if (err) {
console.log('close fail');
return;
}
console.log('close success');
})
```
### close
close\(\): Promise<void\>
关闭UDPSocket连接。使用Promise方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :-------------- | :----------------------------------------- |
| Promise\<void\> | 以Promise形式返回关闭UDPSocket连接的结果。 |
**示例:**
```js
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
获取UDPSocket状态。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------ | ---- | ---------- |
| callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | 是 | 回调函数。 |
**示例:**
```js
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\>
获取UDPSocket状态。使用Promise方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :----------------------------------------------- | :----------------------------------------- |
| Promise<[SocketStateBase](#socketstatebase)> | 以Promise形式返回获取UDPSocket状态的结果。 |
**示例:**
```js
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
设置UDPSocket连接的其他属性。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [UDPExtraOptions](#udpextraoptions) | 是 | UDPSocket连接的其他属性,参考[UDPExtraOptions](#udpextraoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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\>
设置UDPSocket连接的其他属性。使用Promise方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [UDPExtraOptions](#udpextraoptions) | 是 | UDPSocket连接的其他属性,参考[UDPExtraOptions](#udpextraoptions)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :--------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回设置UDPSocket连接的其他属性的结果。 |
**示例:**
```js
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
订阅UDPSocket连接的接收消息事件。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | 是 | 订阅的事件类型。'message':接收消息事件。 |
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | 是 | 回调函数。 |
**示例:**
```js
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
取消订阅UDPSocket连接的接收消息事件。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | 是 | 订阅的事件类型。'message':接收消息事件。 |
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | 否 | 回调函数。 |
**示例:**
```js
let udp = socket.constructUDPSocketInstance();
let callback = value =>{
console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
}
udp.on('message', callback);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
udp.off('message', callback);
udp.off('message');
```
### on\('listening' | 'close'\)
on\(type: 'listening' | 'close', callback: Callback<void\>\): void
订阅UDPSocket连接的数据包消息事件或关闭事件。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 订阅的事件类型。<br />- 'listening':数据包消息事件。<br />- 'close':关闭事件。 |
| callback | Callback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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
取消订阅UDPSocket连接的数据包消息事件或关闭事件。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 订阅事件类型。<br />- 'listening':数据包消息事件。<br />- 'close':关闭事件。 |
| callback | Callback\<void\> | 否 | 回调函数。 |
**示例:**
```js
let udp = socket.constructUDPSocketInstance();
let callback1 = () =>{
console.log("on listening, success");
}
udp.on('listening', callback1);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
udp.off('listening', callback1);
udp.off('listening');
let callback2 = () =>{
console.log("on close, success");
}
udp.on('close', callback2);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
udp.off('close', callback2);
udp.off('close');
```
### on\('error'\)
on\(type: 'error', callback: ErrorCallback\): void
订阅UDPSocket连接的error事件。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | ------------------------------------ |
| type | string | 是 | 订阅的事件类型。'error':error事件。 |
| callback | ErrorCallback | 是 | 回调函数。 |
**示例:**
```js
let udp = socket.constructUDPSocketInstance();
udp.on('error', err => {
console.log("on error, err:" + JSON.stringify(err))
});
```
### off\('error'\)
off\(type: 'error', callback?: ErrorCallback\): void
取消订阅UDPSocket连接的error事件。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | ------------------------------------ |
| type | string | 是 | 订阅的事件类型。'error':error事件。 |
| callback | ErrorCallback | 否 | 回调函数。 |
**示例:**
```js
let udp = socket.constructUDPSocketInstance();
let callback = err =>{
console.log("on error, err:" + JSON.stringify(err));
}
udp.on('error', callback);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
udp.off('error', callback);
udp.off('error');
```
## NetAddress
目标地址信息。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| ------- | ------ | ---- | ------------------------------------------------------------ |
| address | string | 是 | 本地绑定的ip地址。 |
| port | number | 否 | 端口号 ,范围0~65535。如果不指定系统随机分配端口。 |
| family | number | 否 | 网络协议类型,可选类型:<br />- 1:IPv4<br />- 2:IPv6<br />默认为1。 |
## UDPSendOptions
UDPSocket发送参数。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------- | ---- | -------------- |
| data | string \| ArrayBuffer<sup>7+</sup> | 是 | 发送的数据。 |
| address | [NetAddress](#netaddress) | 是 | 目标地址信息。 |
## UDPExtraOptions
UDPSocket连接的其他属性。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| ----------------- | ------- | ---- | -------------------------------- |
| broadcast | boolean | 否 | 是否可以发送广播。默认为false。 |
| receiveBufferSize | number | 否 | 接收缓冲区大小(单位:Byte)。 |
| sendBufferSize | number | 否 | 发送缓冲区大小(单位:Byte)。 |
| reuseAddress | boolean | 否 | 是否重用地址。默认为false。 |
| socketTimeout | number | 否 | 套接字超时时间,单位毫秒(ms)。 |
## SocketStateBase
Socket的状态信息。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| ----------- | ------- | ---- | ---------- |
| isBound | boolean | 是 | 是否绑定。 |
| isClose | boolean | 是 | 是否关闭。 |
| isConnected | boolean | 是 | 是否连接。 |
## SocketRemoteInfo
Socket的连接信息。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| ------- | ------ | ---- | ------------------------------------------------------------ |
| address | string | 是 | 本地绑定的ip地址。 |
| family | string | 是 | 网络协议类型,可选类型:<br />- IPv4<br />- IPv6<br />默认为IPv4。 |
| port | number | 是 | 端口号,范围0~65535。 |
| size | number | 是 | 服务器响应信息的字节长度。 |
## UDP 错误码说明
UDP 错误码映射形式为:2301000 + 内核错误码。
## socket.constructTCPSocketInstance
constructTCPSocketInstance\(\): TCPSocket
创建一个TCPSocket对象。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :--------------------------------- | :---------------------- |
| [TCPSocket](#tcpsocket) | 返回一个TCPSocket对象。 |
**示例:**
```js
let tcp = socket.constructTCPSocketInstance();
```
## TCPSocket
TCPSocket连接。在调用TCPSocket的方法前,需要先通过[socket.constructTCPSocketInstance](#socketconstructtcpsocketinstance)创建TCPSocket对象。
### bind
bind\(address: NetAddress, callback: AsyncCallback<void\>\): void
绑定IP地址和端口,端口可以指定或由系统随机分配。使用callback方法作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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\>
绑定IP地址和端口,端口可以指定或由系统随机分配。使用Promise方法作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :------------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回TCPSocket绑定本机的IP地址和端口的结果。 |
**示例:**
```js
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
连接到指定的IP地址和端口。使用callback方法作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPConnectOptions](#tcpconnectoptions) | 是 | TCPSocket连接的参数,参考[TCPConnectOptions](#tcpconnectoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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\>
连接到指定的IP地址和端口。使用promise方法作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPConnectOptions](#tcpconnectoptions) | 是 | TCPSocket连接的参数,参考[TCPConnectOptions](#tcpconnectoptions)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :--------------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回TCPSocket连接到指定的IP地址和端口的结果。 |
**示例:**
```js
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
通过TCPSocket连接发送数据。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPSendOptions](#tcpsendoptions) | 是 | TCPSocket发送请求的参数,参考[TCPSendOptions](#tcpsendoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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\>
通过TCPSocket连接发送数据。使用Promise方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPSendOptions](#tcpsendoptions) | 是 | TCPSocket发送请求的参数,参考[TCPSendOptions](#tcpsendoptions)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回通过TCPSocket连接发送数据的结果。 |
**示例:**
```js
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
关闭TCPSocket连接。使用callback方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | ---------- |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
let tcp = socket.constructTCPSocketInstance();
tcp.close(err => {
if (err) {
console.log('close fail');
return;
}
console.log('close success');
})
```
### close
close\(\): Promise<void\>
关闭TCPSocket连接。使用Promise方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :-------------- | :----------------------------------------- |
| Promise\<void\> | 以Promise形式返回关闭TCPSocket连接的结果。 |
**示例:**
```js
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
获取对端Socket地址。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------- | ---- | ---------- |
| callback | AsyncCallback<[NetAddress](#netaddress)> | 是 | 回调函数。 |
**示例:**
```js
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\>
获取对端Socket地址。使用Promise方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :------------------------------------------ | :------------------------------------------ |
| Promise<[NetAddress](#netaddress)> | 以Promise形式返回获取对端socket地址的结果。 |
**示例:**
```js
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');
}).catch(err => {
console.log('getRemoteAddressfail');
});
}).catch(err => {
console.log('connect fail');
});
```
### getState
getState\(callback: AsyncCallback<SocketStateBase\>\): void
获取TCPSocket状态。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)或[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------ | ---- | ---------- |
| callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | 是 | 回调函数。 |
**示例:**
```js
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\>
获取TCPSocket状态。使用Promise方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)或[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :----------------------------------------------- | :----------------------------------------- |
| Promise<[SocketStateBase](#socketstatebase)> | 以Promise形式返回获取TCPSocket状态的结果。 |
**示例:**
```js
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');
}).catch(err => {
console.log('getState fail');
});
}).catch(err => {
console.log('connect fail');
});
```
### setExtraOptions
setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback<void\>\): void
设置TCPSocket连接的其他属性。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)或[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPExtraOptions](#tcpextraoptions) | 是 | TCPSocket连接的其他属性,参考[TCPExtraOptions](#tcpextraoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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\>
设置TCPSocket连接的其他属性,使用Promise方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)或[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPExtraOptions](#tcpextraoptions) | 是 | TCPSocket连接的其他属性,参考[TCPExtraOptions](#tcpextraoptions)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :--------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回设置TCPSocket连接的其他属性的结果。 |
**示例:**
```js
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
订阅TCPSocket连接的接收消息事件。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | 是 | 订阅的事件类型。'message':接收消息事件。 |
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | 是 | 回调函数。 |
**示例:**
```js
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
取消订阅TCPSocket连接的接收消息事件。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | 是 | 订阅的事件类型。'message':接收消息事件。 |
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | 否 | 回调函数。 |
**示例:**
```js
let tcp = socket.constructTCPSocketInstance();
let callback = value =>{
console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
}
tcp.on('message', callback);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
tcp.off('message', callback);
tcp.off('message');
```
### on\('connect' | 'close'\)
on\(type: 'connect' | 'close', callback: Callback<void\>\): void
订阅TCPSocket的连接事件或关闭事件。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 订阅的事件类型。<br />- 'connect':连接事件。<br />- 'close':关闭事件。 |
| callback | Callback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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
取消订阅TCPSocket的连接事件或关闭事件。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 订阅的事件类型。<br />- 'connect':连接事件。<br />- 'close':关闭事件。 |
| callback | Callback\<void\> | 否 | 回调函数。 |
**示例:**
```js
let tcp = socket.constructTCPSocketInstance();
let callback1 = () =>{
console.log("on connect success");
}
tcp.on('connect', callback1);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
tcp.off('connect', callback1);
tcp.off('connect');
let callback2 = () =>{
console.log("on close success");
}
tcp.on('close', callback2);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
tcp.off('close', callback2);
tcp.off('close');
```
### on\('error'\)
on\(type: 'error', callback: ErrorCallback\): void
订阅TCPSocket连接的error事件。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | ------------------------------------ |
| type | string | 是 | 订阅的事件类型。'error':error事件。 |
| callback | ErrorCallback | 是 | 回调函数。 |
**示例:**
```js
let tcp = socket.constructTCPSocketInstance();
tcp.on('error', err => {
console.log("on error, err:" + JSON.stringify(err))
});
```
### off\('error'\)
off\(type: 'error', callback?: ErrorCallback\): void
取消订阅TCPSocket连接的error事件。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | ------------------------------------ |
| type | string | 是 | 订阅的事件类型。'error':error事件。 |
| callback | ErrorCallback | 否 | 回调函数。 |
**示例:**
```js
let tcp = socket.constructTCPSocketInstance();
let callback = err =>{
console.log("on error, err:" + JSON.stringify(err));
}
tcp.on('error', callback);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
tcp.off('error', callback);
tcp.off('error');
```
## TCPConnectOptions
TCPSocket连接的参数。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------- | ---- | -------------------------- |
| address | [NetAddress](#netaddress) | 是 | 绑定的地址以及端口。 |
| timeout | number | 否 | 超时时间,单位毫秒(ms)。 |
## TCPSendOptions
TCPSocket发送请求的参数。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| -------- | ------ | ---- | ------------------------------------------------------------ |
| data | string\| ArrayBuffer<sup>7+</sup> | 是 | 发送的数据。 |
| encoding | string | 否 | 字符编码(UTF-8,UTF-16BE,UTF-16LE,UTF-16,US-AECII,ISO-8859-1),默认为UTF-8。 |
## TCPExtraOptions
TCPSocket连接的其他属性。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| ----------------- | ------- | ---- | ------------------------------------------------------------ |
| keepAlive | boolean | 否 | 是否保持连接。默认为false。 |
| OOBInline | boolean | 否 | 是否为OOB内联。默认为false。 |
| TCPNoDelay | boolean | 否 | TCPSocket连接是否无时延。默认为false。 |
| socketLinger | Object | 是 | socket是否继续逗留。<br />- on:是否逗留(true:逗留;false:不逗留)。<br />- linger:逗留时长,单位毫秒(ms),取值范围为0~65535。<br />当入参on设置为true时,才需要设置。 |
| receiveBufferSize | number | 否 | 接收缓冲区大小(单位:Byte)。 |
| sendBufferSize | number | 否 | 发送缓冲区大小(单位:Byte)。 |
| reuseAddress | boolean | 否 | 是否重用地址。默认为false。 |
| socketTimeout | number | 否 | 套接字超时时间,单位毫秒(ms)。 |
## TCP 错误码说明
TCP 错误码映射形式为:2301000 + 内核错误码。
## socket.constructTLSSocketInstance<sup>9+</sup>
constructTLSSocketInstance(): TLSSocket
创建并返回一个TLSSocket对象。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :--------------------------------- | :---------------------- |
| [TLSSocket](#tlssocket9) | 返回一个TLSSocket对象。 |
**示例:**
```js
let tls = socket.constructTLSSocketInstance();
```
## TLSSocket<sup>9+</sup>
TLSSocket连接。在调用TLSSocket的方法前,需要先通过[socket.constructTLSSocketInstance](#socketconstructtlssocketinstance9)创建TLSSocket对象。
### bind<sup>9+</sup>
bind\(address: NetAddress, callback: AsyncCallback<void\>\): void
绑定IP地址和端口。使用callback方法作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。成功返回TLSSocket绑定本机的IP地址和端口的结果。 失败返回错误码,错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2303198 | Address already in use. |
| 2300002 | System internal error. |
**示例:**
```js
tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
```
### bind<sup>9+</sup>
bind\(address: NetAddress\): Promise<void\>
绑定IP地址和端口。使用Promise方法作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :------------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回TLSSocket绑定本机的IP地址和端口的结果。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2303198 | Address already in use. |
| 2300002 | System internal error. |
**示例:**
```js
let promise = tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1});
promise.then(() => {
console.log('bind success');
}).catch(err => {
console.log('bind fail');
});
```
### getState<sup>9+</sup>
getState\(callback: AsyncCallback<SocketStateBase\>\): void
在TLSSocket的bind成功之后,获取TLSSocket状态。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------ | ---- | ---------- |
| callback | AsyncCallback\<[SocketStateBase](#socketstatebase)> | 是 | 回调函数。成功返回TLSSocket状态,失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**示例:**
```js
let promise = tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
tls.getState((err, data) => {
if (err) {
console.log('getState fail');
return;
}
console.log('getState success:' + JSON.stringify(data));
});
```
### getState<sup>9+</sup>
getState\(\): Promise<SocketStateBase\>
在TLSSocket的bind成功之后,获取TLSSocket状态。使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :----------------------------------------------- | :----------------------------------------- |
| Promise\<[SocketStateBase](#socketstatebase)> | 以Promise形式返回获取TLSSocket状态的结果。失败返回错误码,错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**示例:**
```js
tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let promise = tls.getState();
promise.then(() => {
console.log('getState success');
}).catch(err => {
console.log('getState fail');
});
```
### setExtraOptions<sup>9+</sup>
setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback<void\>\): void
在TLSSocket的bind成功之后,设置TCPSocket连接的其他属性。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPExtraOptions](#tcpextraoptions) | 是 | TCPSocket连接的其他属性,参考[TCPExtraOptions](#tcpextraoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。成功返回设置TCPSocket连接的其他属性的结果,失败返回错误码,错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 401 | Parameter error. |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**示例:**
```js
tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
tls.setExtraOptions({
keepAlive: true,
OOBInline: true,
TCPNoDelay: true,
socketLinger: { on:true, linger:10 },
receiveBufferSize: 1000,
sendBufferSize: 1000,
reuseAddress: true,
socketTimeout: 3000,
},err => {
if (err) {
console.log('setExtraOptions fail');
return;
}
console.log('setExtraOptions success');
});
```
### setExtraOptions<sup>9+</sup>
setExtraOptions\(options: TCPExtraOptions\): Promise<void\>
在TLSSocket的bind成功之后,设置TCPSocket连接的其他属性,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPExtraOptions](#tcpextraoptions) | 是 | TCPSocket连接的其他属性,参考[TCPExtraOptions](#tcpextraoptions)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :--------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回设置TCPSocket连接的其他属性的结果。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 401 | Parameter error. |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**示例:**
```js
tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let promise = tls.setExtraOptions({
keepAlive: true,
OOBInline: true,
TCPNoDelay: true,
socketLinger: { on:true, linger:10 },
receiveBufferSize: 1000,
sendBufferSize: 1000,
reuseAddress: true,
socketTimeout: 3000,
});
promise.then(() => {
console.log('setExtraOptions success');
}).catch(err => {
console.log('setExtraOptions fail');
});
```
### connect<sup>9+</sup>
connect(options: TLSConnectOptions, callback: AsyncCallback\<void>): void
在TLSSocket上bind成功之后,进行通信连接,并创建和初始化TLS会话,实现建立连接过程,启动与服务器的TLS/SSL握手,实现数据传输功能,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------| ----| --------------- |
| options | [TLSConnectOptions](#tlsconnectoptions9) | 是 | TLSSocket连接所需要的参数。|
| callback | AsyncCallback\<void> | 是 | 回调函数,成功无返回,失败返回错误码,错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 401 | Parameter error. |
| 2303104 | Interrupted system call. |
| 2303109 | Bad file number. |
| 2303111 | Resource temporarily unavailable try again. |
| 2303113 | System permission denied. |
| 2303188 | Socket operation on non-socket. |
| 2303191 | Protocol wrong type for socket. |
| 2303198 | Address already in use. |
| 2303199 | Cannot assign requested address. |
| 2303210 | Connection timed out. |
| 2303501 | SSL is null. |
| 2303502 | Error in tls reading. |
| 2303503 | Error in tls writing |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**示例:**
```js
let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let options = {
ALPNProtocols: ["spdy/1", "http/1.1"],
address: {
address: "192.168.xx.xxx",
port: xxxx,
family: 1,
},
secureOptions: {
key: "xxxx",
cert: "xxxx",
ca: ["xxxx"],
passwd: "xxxx",
protocols: [socket.Protocol.TLSv12],
useRemoteCipherPrefer: true,
signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
cipherSuite: "AES256-SHA256",
},
};
tlsTwoWay.connect(options, (err, data) => {
console.error(err);
console.log(data);
});
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let oneWayOptions = {
address: {
address: "192.168.xxx.xxx",
port: xxxx,
family: 1,
},
secureOptions: {
ca: ["xxxx","xxxx"],
cipherSuite: "AES256-SHA256",
},
};
tlsOneWay.connect(oneWayOptions, (err, data) => {
console.error(err);
console.log(data);
});
```
### connect<sup>9+</sup>
connect(options: TLSConnectOptions): Promise\<void>
在TLSSocket上bind成功之后,进行通信连接,并创建和初始化TLS会话,实现建立连接过程,启动与服务器的TLS/SSL握手,实现数据传输功能,该连接包括两种认证方式,单向认证与双向认证,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------| ----| --------------- |
| options | [TLSConnectOptions](#tlsconnectoptions9) | 是 | 连接所需要的参数。|
**返回值:**
| 类型 | 说明 |
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | 以Promise形式返回,成功无返回,失败返回错误码,错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 401 | Parameter error. |
| 2303104 | Interrupted system call. |
| 2303109 | Bad file number. |
| 2303111 | Resource temporarily unavailable try again. |
| 2303113 | System permission denied. |
| 2303188 | Socket operation on non-socket. |
| 2303191 | Protocol wrong type for socket. |
| 2303198 | Address already in use. |
| 2303199 | Cannot assign requested address. |
| 2303210 | Connection timed out. |
| 2303501 | SSL is null. |
| 2303502 | Error in tls reading. |
| 2303503 | Error in tls writing |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**示例:**
```js
let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let options = {
ALPNProtocols: ["spdy/1", "http/1.1"],
address: {
address: "xxxx",
port: xxxx,
family: 1,
},
secureOptions: {
key: "xxxx",
cert: "xxxx",
ca: ["xxxx"],
passwd: "xxxx",
protocols: [socket.Protocol.TLSv12],
useRemoteCipherPrefer: true,
signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
cipherSuite: "AES256-SHA256",
},
};
tlsTwoWay.connect(options).then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let oneWayOptions = {
address: {
address: "192.168.xxx.xxx",
port: xxxx,
family: 1,
},
secureOptions: {
ca: ["xxxx","xxxx"],
cipherSuite: "AES256-SHA256",
},
};
tlsOneWay.connect(oneWayOptions).then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getRemoteAddress<sup>9+</sup>
getRemoteAddress\(callback: AsyncCallback<NetAddress\>\): void
在TLSSocket通信连接成功之后,获取对端Socket地址。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<[NetAddress](#netaddress)> | 是 | 回调函数。成功返回对端的socket地址,失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**示例:**
```js
tls.getRemoteAddress((err, data) => {
if (err) {
console.log('getRemoteAddress fail');
return;
}
console.log('getRemoteAddress success:' + JSON.stringify(data));
});
```
### getRemoteAddress<sup>9+</sup>
getRemoteAddress\(\): Promise\<NetAddress>
在TLSSocket通信连接成功之后,获取对端Socket地址。使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :------------------------------------------ | :------------------------------------------ |
| Promise\<[NetAddress](#netaddress)> | 以Promise形式返回获取对端socket地址的结果。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**示例:**
```js
let promise = tls.getRemoteAddress();
promise.then(() => {
console.log('getRemoteAddress success');
}).catch(err => {
console.log('getRemoteAddress fail');
});
```
### getCertificate<sup>9+</sup>
getCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)>): void
在TLSSocket通信连接成功之后,获取本地的数字证书,该接口只适用于双向认证时,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)> | 是 | 回调函数,成功返回本地的证书,失败返回错误码,错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303504 | Error looking up x509. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getCertificate((err, data) => {
if (err) {
console.log("getCertificate callback error = " + err);
} else {
console.log("getCertificate callback = " + data);
}
});
```
### getCertificate<sup>9+</sup>
getCertificate():Promise\<[X509CertRawData](#x509certrawdata9)>
在TLSSocket通信连接之后,获取本地的数字证书,该接口只适用于双向认证时,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| -------------- | -------------------- |
| Promise\<[X509CertRawData](#x509certrawdata9)> | 以Promise形式返回本地的数字证书的结果。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303504 | Error looking up x509. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getCertificate().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getRemoteCertificate<sup>9+</sup>
getRemoteCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)>): void
在TLSSocket通信连接成功之后,获取服务端的数字证书,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)> | 是 | 回调函数,返回服务端的证书。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getRemoteCertificate((err, data) => {
if (err) {
console.log("getRemoteCertificate callback error = " + err);
} else {
console.log("getRemoteCertificate callback = " + data);
}
});
```
### getRemoteCertificate<sup>9+</sup>
getRemoteCertificate():Promise\<[X509CertRawData](#x509certrawdata9)>
在TLSSocket通信连接成功之后,获取服务端的数字证书,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| -------------- | -------------------- |
| Promise\<[X509CertRawData](#x509certrawdata9)> | 以Promise形式返回服务端的数字证书的结果。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getRemoteCertificate().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getProtocol<sup>9+</sup>
getProtocol(callback: AsyncCallback\<string>): void
在TLSSocket通信连接成功之后,获取通信的协议版本,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<string> | 是 | 回调函数,返回通信的协议。失败返回错误码,错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 2303501 | SSL is null. |
| 2303505 | Error occurred in the tls system call. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getProtocol((err, data) => {
if (err) {
console.log("getProtocol callback error = " + err);
} else {
console.log("getProtocol callback = " + data);
}
});
```
### getProtocol<sup>9+</sup>
getProtocol():Promise\<string>
在TLSSocket通信连接成功之后,获取通信的协议版本,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| -------------- | -------------------- |
| Promise\<string> | 以Promise形式返回通信的协议。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303505 | Error occurred in the tls system call. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getProtocol().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getCipherSuite<sup>9+</sup>
getCipherSuite(callback: AsyncCallback\<Array\<string>>): void
在TLSSocket通信连接成功之后,获取通信双方协商后的加密套件,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<Array\<string>> | 是 | 回调函数,返回通信双方支持的加密套件。 失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303502 | Error in tls reading. |
| 2303505 | Error occurred in the tls system call. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getCipherSuite((err, data) => {
if (err) {
console.log("getCipherSuite callback error = " + err);
} else {
console.log("getCipherSuite callback = " + data);
}
});
```
### getCipherSuite<sup>9+</sup>
getCipherSuite(): Promise\<Array\<string>>
在TLSSocket通信连接成功之后,获取通信双方协商后的加密套件,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| ---------------------- | --------------------- |
| Promise\<Array\<string>> | 以Promise形式返回通信双方支持的加密套件。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303502 | Error in tls reading. |
| 2303505 | Error occurred in the tls system call. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getCipherSuite().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getSignatureAlgorithms<sup>9+</sup>
getSignatureAlgorithms(callback: AsyncCallback\<Array\<string>>): void
在TLSSocket通信连接成功之后,获取通信双方协商后签名算法,该接口只适配双向认证模式下,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<Array\<string>> | 是 | 回调函数,返回双方支持的签名算法。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getSignatureAlgorithms((err, data) => {
if (err) {
console.log("getSignatureAlgorithms callback error = " + err);
} else {
console.log("getSignatureAlgorithms callback = " + data);
}
});
```
### getSignatureAlgorithms<sup>9+</sup>
getSignatureAlgorithms(): Promise\<Array\<string>>
在TLSSocket通信连接成功之后,获取通信双方协商后的签名算法,该接口只适配双向认证模式下,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| ---------------------- | -------------------- |
| Promise\<Array\<string>> | 以Promise形式返回获取到的双方支持的签名算法。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getSignatureAlgorithms().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### send<sup>9+</sup>
send(data: string, callback: AsyncCallback\<void>): void
在TLSSocket通信连接成功之后,向服务端发送消息,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -----------------------------| ---- | ---------------|
| data | string | 是 | 发送的数据内容。 |
| callback | AsyncCallback\<void> | 是 | 回调函数,返回TLSSocket发送数据的结果。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 401 | Parameter error. |
| 2303501 | SSL is null. |
| 2303503 | Error in tls writing |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**示例:**
```js
tls.send("xxxx", (err) => {
if (err) {
console.log("send callback error = " + err);
} else {
console.log("send success");
}
});
```
### send<sup>9+</sup>
send(data: string): Promise\<void>
在TLSSocket通信连接成功之后,向服务端发送消息,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -----------------------------| ---- | ---------------|
| data | string | 是 | 发送的数据内容。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 401 | Parameter error. |
| 2303501 | SSL is null. |
| 2303503 | Error in tls writing |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**返回值:**
| 类型 | 说明 |
| -------------- | -------------------- |
| Promise\<void> | 以Promise形式返回,返回TLSSocket发送数据的结果。失败返回错误码,错误信息。 |
**示例:**
```js
tls.send("xxxx").then(() =>{
console.log("send success");
}).catch(err => {
console.error(err);
});
```
### close<sup>9+</sup>
close(callback: AsyncCallback\<void>): void
在TLSSocket通信连接成功之后,断开连接,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -----------------------------| ---- | ---------------|
| callback | AsyncCallback\<void> | 是 | 回调函数,成功返回TLSSocket关闭连接的结果。 失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 2303501 | SSL is null. |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**示例:**
```js
tls.close((err) => {
if (err) {
console.log("close callback error = " + err);
} else {
console.log("close success");
}
});
```
### close<sup>9+</sup>
close(): Promise\<void>
在TLSSocket通信连接成功之后,断开连接,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| -------------- | -------------------- |
| Promise\<void> | 以Promise形式返回,返回TLSSocket关闭连接的结果。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 2303501 | SSL is null. |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**示例:**
```js
tls.close().then(() =>{
console.log("close success");
}).catch(err => {
console.error(err);
});
```
## TLSConnectOptions<sup>9+</sup>
TLS连接的操作。
**系统能力**:SystemCapability.Communication.NetStack
| 名称 | 类型 | 必填 | 说明 |
| -------------- | ------------------------------------- | --- |-------------- |
| address | [NetAddress](#netaddress) | 是 | 网关地址。 |
| secureOptions | [TLSSecureOptions](#tlssecureoptions9) | 是 | TLS安全相关操作。|
| ALPNProtocols | Array\<string> | 否 | ALPN协议。 |
## TLSSecureOptions<sup>9+</sup>
TLS安全相关操作,其中ca证书为必选参数,其他参数为可选参数。当本地证书cert和私钥key不为空时,开启双向验证模式。cert和key其中一项为空时,开启单向验证模式。
**系统能力**:SystemCapability.Communication.NetStack
| 名称 | 类型 | 必填 | 说明 |
| --------------------- | ------------------------------------------------------ | --- |----------------------------------- |
| ca | string \| Array\<string> | 是 | 服务端的ca证书,用于认证校验服务端的数字证书。|
| cert | string | 否 | 本地客户端的数字证书。 |
| key | string | 否 | 本地数字证书的私钥。 |
| passwd | string | 否 | 读取私钥的密码。 |
| protocols | [Protocol](#protocol9) \|Array\<[Protocol](#protocol9)> | 否 | TLS的协议版本。 |
| useRemoteCipherPrefer | boolean | 否 | 优先使用对等方的密码套件。 |
| signatureAlgorithms | string | 否 | 通信过程中的签名算法。 |
| cipherSuite | string | 否 | 通信过程中的加密套件。 |
## Protocol<sup>9+</sup>
TLS通信的协议版本。
**系统能力**:SystemCapability.Communication.NetStack
| 名称 | 值 | 说明 |
| --------- | --------- |------------------ |
| TLSv12 | "TLSv1.2" | 使用TLSv1.2协议通信。 |
| TLSv13 | "TLSv1.3" | 使用TLSv1.3协议通信。 |
## X509CertRawData<sup>9+</sup>
存储证书的数据。
**系统能力**:SystemCapability.Communication.NetStack
| 类型 | 说明 |
| --------------------------------------------------------------------- | --------------------- |
|[cryptoFramework.EncodingBlob](js-apis-cryptoFramework.md#datablob) | 存储证书的数据和编码格式 |
\ No newline at end of file
# @ohos.net.socket (Socket连接)
> **说明:**
>
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```js
import socket from '@ohos.net.socket';
```
## socket.constructUDPSocketInstance
constructUDPSocketInstance\(\): UDPSocket
创建一个UDPSocket对象。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :--------------------------------- | :---------------------- |
| [UDPSocket](#udpsocket) | 返回一个UDPSocket对象。 |
**示例:**
```js
let udp = socket.constructUDPSocketInstance();
```
## UDPSocket
UDPSocket连接。在调用UDPSocket的方法前,需要先通过[socket.constructUDPSocketInstance](#socketconstructudpsocketinstance)创建UDPSocket对象。
### bind
bind\(address: NetAddress, callback: AsyncCallback<void\>\): void
绑定IP地址和端口,端口可以指定或由系统随机分配。使用callback方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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\>
绑定IP地址和端口,端口可以指定或由系统随机分配。使用Promise方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :----------------------------------------- |
| Promise\<void\> | 以Promise形式异步返回UDPSocket绑定的结果。 |
**示例:**
```js
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
通过UDPSocket连接发送数据。使用callback方式作为异步方法。
发送数据前,需要先调用[UDPSocket.bind()](#bind)绑定IP地址和端口。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [UDPSendOptions](#udpsendoptions) | 是 | UDPSocket发送参数,参考[UDPSendOptions](#udpsendoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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\>
通过UDPSocket连接发送数据。使用Promise方式作为异步方法。
发送数据前,需要先调用[UDPSocket.bind()](#bind)绑定IP地址和端口。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [UDPSendOptions](#udpsendoptions) | 是 | UDPSocket发送参数,参考[UDPSendOptions](#udpsendoptions)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :--------------------------------------------- |
| Promise\<void\> | 以Promise形式返回UDPSocket连接发送数据的结果。 |
**示例:**
```js
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
关闭UDPSocket连接。使用callback方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | ---------- |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
let udp = socket.constructUDPSocketInstance();
udp.close(err => {
if (err) {
console.log('close fail');
return;
}
console.log('close success');
})
```
### close
close\(\): Promise<void\>
关闭UDPSocket连接。使用Promise方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :-------------- | :----------------------------------------- |
| Promise\<void\> | 以Promise形式返回关闭UDPSocket连接的结果。 |
**示例:**
```js
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
获取UDPSocket状态。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------ | ---- | ---------- |
| callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | 是 | 回调函数。 |
**示例:**
```js
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\>
获取UDPSocket状态。使用Promise方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :----------------------------------------------- | :----------------------------------------- |
| Promise<[SocketStateBase](#socketstatebase)> | 以Promise形式返回获取UDPSocket状态的结果。 |
**示例:**
```js
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
设置UDPSocket连接的其他属性。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [UDPExtraOptions](#udpextraoptions) | 是 | UDPSocket连接的其他属性,参考[UDPExtraOptions](#udpextraoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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\>
设置UDPSocket连接的其他属性。使用Promise方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [UDPExtraOptions](#udpextraoptions) | 是 | UDPSocket连接的其他属性,参考[UDPExtraOptions](#udpextraoptions)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :--------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回设置UDPSocket连接的其他属性的结果。 |
**示例:**
```js
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
订阅UDPSocket连接的接收消息事件。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | 是 | 订阅的事件类型。'message':接收消息事件。 |
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | 是 | 回调函数。 |
**示例:**
```js
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
取消订阅UDPSocket连接的接收消息事件。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | 是 | 订阅的事件类型。'message':接收消息事件。 |
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | 否 | 回调函数。 |
**示例:**
```js
let udp = socket.constructUDPSocketInstance();
let callback = value =>{
console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
}
udp.on('message', callback);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
udp.off('message', callback);
udp.off('message');
```
### on\('listening' | 'close'\)
on\(type: 'listening' | 'close', callback: Callback<void\>\): void
订阅UDPSocket连接的数据包消息事件或关闭事件。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 订阅的事件类型。<br />- 'listening':数据包消息事件。<br />- 'close':关闭事件。 |
| callback | Callback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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
取消订阅UDPSocket连接的数据包消息事件或关闭事件。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 订阅事件类型。<br />- 'listening':数据包消息事件。<br />- 'close':关闭事件。 |
| callback | Callback\<void\> | 否 | 回调函数。 |
**示例:**
```js
let udp = socket.constructUDPSocketInstance();
let callback1 = () =>{
console.log("on listening, success");
}
udp.on('listening', callback1);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
udp.off('listening', callback1);
udp.off('listening');
let callback2 = () =>{
console.log("on close, success");
}
udp.on('close', callback2);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
udp.off('close', callback2);
udp.off('close');
```
### on\('error'\)
on\(type: 'error', callback: ErrorCallback\): void
订阅UDPSocket连接的error事件。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | ------------------------------------ |
| type | string | 是 | 订阅的事件类型。'error':error事件。 |
| callback | ErrorCallback | 是 | 回调函数。 |
**示例:**
```js
let udp = socket.constructUDPSocketInstance();
udp.on('error', err => {
console.log("on error, err:" + JSON.stringify(err))
});
```
### off\('error'\)
off\(type: 'error', callback?: ErrorCallback\): void
取消订阅UDPSocket连接的error事件。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | ------------------------------------ |
| type | string | 是 | 订阅的事件类型。'error':error事件。 |
| callback | ErrorCallback | 否 | 回调函数。 |
**示例:**
```js
let udp = socket.constructUDPSocketInstance();
let callback = err =>{
console.log("on error, err:" + JSON.stringify(err));
}
udp.on('error', callback);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
udp.off('error', callback);
udp.off('error');
```
## NetAddress
目标地址信息。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| ------- | ------ | ---- | ------------------------------------------------------------ |
| address | string | 是 | 本地绑定的ip地址。 |
| port | number | 否 | 端口号 ,范围0~65535。如果不指定系统随机分配端口。 |
| family | number | 否 | 网络协议类型,可选类型:<br />- 1:IPv4<br />- 2:IPv6<br />默认为1。 |
## UDPSendOptions
UDPSocket发送参数。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------- | ---- | -------------- |
| data | string \| ArrayBuffer<sup>7+</sup> | 是 | 发送的数据。 |
| address | [NetAddress](#netaddress) | 是 | 目标地址信息。 |
## UDPExtraOptions
UDPSocket连接的其他属性。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| ----------------- | ------- | ---- | -------------------------------- |
| broadcast | boolean | 否 | 是否可以发送广播。默认为false。 |
| receiveBufferSize | number | 否 | 接收缓冲区大小(单位:Byte)。 |
| sendBufferSize | number | 否 | 发送缓冲区大小(单位:Byte)。 |
| reuseAddress | boolean | 否 | 是否重用地址。默认为false。 |
| socketTimeout | number | 否 | 套接字超时时间,单位毫秒(ms)。 |
## SocketStateBase
Socket的状态信息。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| ----------- | ------- | ---- | ---------- |
| isBound | boolean | 是 | 是否绑定。 |
| isClose | boolean | 是 | 是否关闭。 |
| isConnected | boolean | 是 | 是否连接。 |
## SocketRemoteInfo
Socket的连接信息。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| ------- | ------ | ---- | ------------------------------------------------------------ |
| address | string | 是 | 本地绑定的ip地址。 |
| family | string | 是 | 网络协议类型,可选类型:<br />- IPv4<br />- IPv6<br />默认为IPv4。 |
| port | number | 是 | 端口号,范围0~65535。 |
| size | number | 是 | 服务器响应信息的字节长度。 |
## UDP 错误码说明
UDP 错误码映射形式为:2301000 + 内核错误码。
## socket.constructTCPSocketInstance
constructTCPSocketInstance\(\): TCPSocket
创建一个TCPSocket对象。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :--------------------------------- | :---------------------- |
| [TCPSocket](#tcpsocket) | 返回一个TCPSocket对象。 |
**示例:**
```js
let tcp = socket.constructTCPSocketInstance();
```
## TCPSocket
TCPSocket连接。在调用TCPSocket的方法前,需要先通过[socket.constructTCPSocketInstance](#socketconstructtcpsocketinstance)创建TCPSocket对象。
### bind
bind\(address: NetAddress, callback: AsyncCallback<void\>\): void
绑定IP地址和端口,端口可以指定或由系统随机分配。使用callback方法作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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\>
绑定IP地址和端口,端口可以指定或由系统随机分配。使用Promise方法作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :------------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回TCPSocket绑定本机的IP地址和端口的结果。 |
**示例:**
```js
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
连接到指定的IP地址和端口。使用callback方法作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPConnectOptions](#tcpconnectoptions) | 是 | TCPSocket连接的参数,参考[TCPConnectOptions](#tcpconnectoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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\>
连接到指定的IP地址和端口。使用promise方法作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPConnectOptions](#tcpconnectoptions) | 是 | TCPSocket连接的参数,参考[TCPConnectOptions](#tcpconnectoptions)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :--------------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回TCPSocket连接到指定的IP地址和端口的结果。 |
**示例:**
```js
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
通过TCPSocket连接发送数据。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPSendOptions](#tcpsendoptions) | 是 | TCPSocket发送请求的参数,参考[TCPSendOptions](#tcpsendoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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\>
通过TCPSocket连接发送数据。使用Promise方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPSendOptions](#tcpsendoptions) | 是 | TCPSocket发送请求的参数,参考[TCPSendOptions](#tcpsendoptions)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回通过TCPSocket连接发送数据的结果。 |
**示例:**
```js
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
关闭TCPSocket连接。使用callback方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | ---------- |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
let tcp = socket.constructTCPSocketInstance();
tcp.close(err => {
if (err) {
console.log('close fail');
return;
}
console.log('close success');
})
```
### close
close\(\): Promise<void\>
关闭TCPSocket连接。使用Promise方式作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :-------------- | :----------------------------------------- |
| Promise\<void\> | 以Promise形式返回关闭TCPSocket连接的结果。 |
**示例:**
```js
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
获取对端Socket地址。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------- | ---- | ---------- |
| callback | AsyncCallback<[NetAddress](#netaddress)> | 是 | 回调函数。 |
**示例:**
```js
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\>
获取对端Socket地址。使用Promise方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :------------------------------------------ | :------------------------------------------ |
| Promise<[NetAddress](#netaddress)> | 以Promise形式返回获取对端socket地址的结果。 |
**示例:**
```js
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');
}).catch(err => {
console.log('getRemoteAddressfail');
});
}).catch(err => {
console.log('connect fail');
});
```
### getState
getState\(callback: AsyncCallback<SocketStateBase\>\): void
获取TCPSocket状态。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)或[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------ | ---- | ---------- |
| callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | 是 | 回调函数。 |
**示例:**
```js
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\>
获取TCPSocket状态。使用Promise方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)或[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :----------------------------------------------- | :----------------------------------------- |
| Promise<[SocketStateBase](#socketstatebase)> | 以Promise形式返回获取TCPSocket状态的结果。 |
**示例:**
```js
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');
}).catch(err => {
console.log('getState fail');
});
}).catch(err => {
console.log('connect fail');
});
```
### setExtraOptions
setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback<void\>\): void
设置TCPSocket连接的其他属性。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)或[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPExtraOptions](#tcpextraoptions) | 是 | TCPSocket连接的其他属性,参考[TCPExtraOptions](#tcpextraoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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\>
设置TCPSocket连接的其他属性,使用Promise方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>[bind](#bind)或[connect](#connect)方法调用成功后,才可调用此方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPExtraOptions](#tcpextraoptions) | 是 | TCPSocket连接的其他属性,参考[TCPExtraOptions](#tcpextraoptions)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :--------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回设置TCPSocket连接的其他属性的结果。 |
**示例:**
```js
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
订阅TCPSocket连接的接收消息事件。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | 是 | 订阅的事件类型。'message':接收消息事件。 |
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | 是 | 回调函数。 |
**示例:**
```js
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
取消订阅TCPSocket连接的接收消息事件。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | 是 | 订阅的事件类型。'message':接收消息事件。 |
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | 否 | 回调函数。 |
**示例:**
```js
let tcp = socket.constructTCPSocketInstance();
let callback = value =>{
console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
}
tcp.on('message', callback);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
tcp.off('message', callback);
tcp.off('message');
```
### on\('connect' | 'close'\)
on\(type: 'connect' | 'close', callback: Callback<void\>\): void
订阅TCPSocket的连接事件或关闭事件。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 订阅的事件类型。<br />- 'connect':连接事件。<br />- 'close':关闭事件。 |
| callback | Callback\<void\> | 是 | 回调函数。 |
**示例:**
```js
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
取消订阅TCPSocket的连接事件或关闭事件。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 订阅的事件类型。<br />- 'connect':连接事件。<br />- 'close':关闭事件。 |
| callback | Callback\<void\> | 否 | 回调函数。 |
**示例:**
```js
let tcp = socket.constructTCPSocketInstance();
let callback1 = () =>{
console.log("on connect success");
}
tcp.on('connect', callback1);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
tcp.off('connect', callback1);
tcp.off('connect');
let callback2 = () =>{
console.log("on close success");
}
tcp.on('close', callback2);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
tcp.off('close', callback2);
tcp.off('close');
```
### on\('error'\)
on\(type: 'error', callback: ErrorCallback\): void
订阅TCPSocket连接的error事件。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | ------------------------------------ |
| type | string | 是 | 订阅的事件类型。'error':error事件。 |
| callback | ErrorCallback | 是 | 回调函数。 |
**示例:**
```js
let tcp = socket.constructTCPSocketInstance();
tcp.on('error', err => {
console.log("on error, err:" + JSON.stringify(err))
});
```
### off\('error'\)
off\(type: 'error', callback?: ErrorCallback\): void
取消订阅TCPSocket连接的error事件。使用callback方式作为异步方法。
>![](public_sys-resources/icon-note.gif) **说明:**
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------- | ---- | ------------------------------------ |
| type | string | 是 | 订阅的事件类型。'error':error事件。 |
| callback | ErrorCallback | 否 | 回调函数。 |
**示例:**
```js
let tcp = socket.constructTCPSocketInstance();
let callback = err =>{
console.log("on error, err:" + JSON.stringify(err));
}
tcp.on('error', callback);
// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
tcp.off('error', callback);
tcp.off('error');
```
## TCPConnectOptions
TCPSocket连接的参数。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------- | ---- | -------------------------- |
| address | [NetAddress](#netaddress) | 是 | 绑定的地址以及端口。 |
| timeout | number | 否 | 超时时间,单位毫秒(ms)。 |
## TCPSendOptions
TCPSocket发送请求的参数。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| -------- | ------ | ---- | ------------------------------------------------------------ |
| data | string\| ArrayBuffer<sup>7+</sup> | 是 | 发送的数据。 |
| encoding | string | 否 | 字符编码(UTF-8,UTF-16BE,UTF-16LE,UTF-16,US-AECII,ISO-8859-1),默认为UTF-8。 |
## TCPExtraOptions
TCPSocket连接的其他属性。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 名称 | 类型 | 必填 | 说明 |
| ----------------- | ------- | ---- | ------------------------------------------------------------ |
| keepAlive | boolean | 否 | 是否保持连接。默认为false。 |
| OOBInline | boolean | 否 | 是否为OOB内联。默认为false。 |
| TCPNoDelay | boolean | 否 | TCPSocket连接是否无时延。默认为false。 |
| socketLinger | Object | 是 | socket是否继续逗留。<br />- on:是否逗留(true:逗留;false:不逗留)。<br />- linger:逗留时长,单位毫秒(ms),取值范围为0~65535。<br />当入参on设置为true时,才需要设置。 |
| receiveBufferSize | number | 否 | 接收缓冲区大小(单位:Byte)。 |
| sendBufferSize | number | 否 | 发送缓冲区大小(单位:Byte)。 |
| reuseAddress | boolean | 否 | 是否重用地址。默认为false。 |
| socketTimeout | number | 否 | 套接字超时时间,单位毫秒(ms)。 |
## TCP 错误码说明
TCP 错误码映射形式为:2301000 + 内核错误码。
## socket.constructTLSSocketInstance<sup>9+</sup>
constructTLSSocketInstance(): TLSSocket
创建并返回一个TLSSocket对象。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :--------------------------------- | :---------------------- |
| [TLSSocket](#tlssocket9) | 返回一个TLSSocket对象。 |
**示例:**
```js
let tls = socket.constructTLSSocketInstance();
```
## TLSSocket<sup>9+</sup>
TLSSocket连接。在调用TLSSocket的方法前,需要先通过[socket.constructTLSSocketInstance](#socketconstructtlssocketinstance9)创建TLSSocket对象。
### bind<sup>9+</sup>
bind\(address: NetAddress, callback: AsyncCallback<void\>\): void
绑定IP地址和端口。使用callback方法作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。成功返回TLSSocket绑定本机的IP地址和端口的结果。 失败返回错误码,错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2303198 | Address already in use. |
| 2300002 | System internal error. |
**示例:**
```js
tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
```
### bind<sup>9+</sup>
bind\(address: NetAddress\): Promise<void\>
绑定IP地址和端口。使用Promise方法作为异步方法。
**需要权限**:ohos.permission.INTERNET
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :------------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回TLSSocket绑定本机的IP地址和端口的结果。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2303198 | Address already in use. |
| 2300002 | System internal error. |
**示例:**
```js
let promise = tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1});
promise.then(() => {
console.log('bind success');
}).catch(err => {
console.log('bind fail');
});
```
### getState<sup>9+</sup>
getState\(callback: AsyncCallback<SocketStateBase\>\): void
在TLSSocket的bind成功之后,获取TLSSocket状态。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------ | ---- | ---------- |
| callback | AsyncCallback\<[SocketStateBase](#socketstatebase)> | 是 | 回调函数。成功返回TLSSocket状态,失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**示例:**
```js
let promise = tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
tls.getState((err, data) => {
if (err) {
console.log('getState fail');
return;
}
console.log('getState success:' + JSON.stringify(data));
});
```
### getState<sup>9+</sup>
getState\(\): Promise<SocketStateBase\>
在TLSSocket的bind成功之后,获取TLSSocket状态。使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :----------------------------------------------- | :----------------------------------------- |
| Promise\<[SocketStateBase](#socketstatebase)> | 以Promise形式返回获取TLSSocket状态的结果。失败返回错误码,错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**示例:**
```js
tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let promise = tls.getState();
promise.then(() => {
console.log('getState success');
}).catch(err => {
console.log('getState fail');
});
```
### setExtraOptions<sup>9+</sup>
setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback<void\>\): void
在TLSSocket的bind成功之后,设置TCPSocket连接的其他属性。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPExtraOptions](#tcpextraoptions) | 是 | TCPSocket连接的其他属性,参考[TCPExtraOptions](#tcpextraoptions)。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。成功返回设置TCPSocket连接的其他属性的结果,失败返回错误码,错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 401 | Parameter error. |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**示例:**
```js
tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
tls.setExtraOptions({
keepAlive: true,
OOBInline: true,
TCPNoDelay: true,
socketLinger: { on:true, linger:10 },
receiveBufferSize: 1000,
sendBufferSize: 1000,
reuseAddress: true,
socketTimeout: 3000,
},err => {
if (err) {
console.log('setExtraOptions fail');
return;
}
console.log('setExtraOptions success');
});
```
### setExtraOptions<sup>9+</sup>
setExtraOptions\(options: TCPExtraOptions\): Promise<void\>
在TLSSocket的bind成功之后,设置TCPSocket连接的其他属性,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPExtraOptions](#tcpextraoptions) | 是 | TCPSocket连接的其他属性,参考[TCPExtraOptions](#tcpextraoptions)。 |
**返回值:**
| 类型 | 说明 |
| :-------------- | :--------------------------------------------------- |
| Promise\<void\> | 以Promise形式返回设置TCPSocket连接的其他属性的结果。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 401 | Parameter error. |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**示例:**
```js
tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let promise = tls.setExtraOptions({
keepAlive: true,
OOBInline: true,
TCPNoDelay: true,
socketLinger: { on:true, linger:10 },
receiveBufferSize: 1000,
sendBufferSize: 1000,
reuseAddress: true,
socketTimeout: 3000,
});
promise.then(() => {
console.log('setExtraOptions success');
}).catch(err => {
console.log('setExtraOptions fail');
});
```
### connect<sup>9+</sup>
connect(options: TLSConnectOptions, callback: AsyncCallback\<void>): void
在TLSSocket上bind成功之后,进行通信连接,并创建和初始化TLS会话,实现建立连接过程,启动与服务器的TLS/SSL握手,实现数据传输功能,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------| ----| --------------- |
| options | [TLSConnectOptions](#tlsconnectoptions9) | 是 | TLSSocket连接所需要的参数。|
| callback | AsyncCallback\<void> | 是 | 回调函数,成功无返回,失败返回错误码,错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 401 | Parameter error. |
| 2303104 | Interrupted system call. |
| 2303109 | Bad file number. |
| 2303111 | Resource temporarily unavailable try again. |
| 2303113 | System permission denied. |
| 2303188 | Socket operation on non-socket. |
| 2303191 | Protocol wrong type for socket. |
| 2303198 | Address already in use. |
| 2303199 | Cannot assign requested address. |
| 2303210 | Connection timed out. |
| 2303501 | SSL is null. |
| 2303502 | Error in tls reading. |
| 2303503 | Error in tls writing |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**示例:**
```js
let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let options = {
ALPNProtocols: ["spdy/1", "http/1.1"],
address: {
address: "192.168.xx.xxx",
port: xxxx,
family: 1,
},
secureOptions: {
key: "xxxx",
cert: "xxxx",
ca: ["xxxx"],
passwd: "xxxx",
protocols: [socket.Protocol.TLSv12],
useRemoteCipherPrefer: true,
signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
cipherSuite: "AES256-SHA256",
},
};
tlsTwoWay.connect(options, (err, data) => {
console.error(err);
console.log(data);
});
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let oneWayOptions = {
address: {
address: "192.168.xxx.xxx",
port: xxxx,
family: 1,
},
secureOptions: {
ca: ["xxxx","xxxx"],
cipherSuite: "AES256-SHA256",
},
};
tlsOneWay.connect(oneWayOptions, (err, data) => {
console.error(err);
console.log(data);
});
```
### connect<sup>9+</sup>
connect(options: TLSConnectOptions): Promise\<void>
在TLSSocket上bind成功之后,进行通信连接,并创建和初始化TLS会话,实现建立连接过程,启动与服务器的TLS/SSL握手,实现数据传输功能,该连接包括两种认证方式,单向认证与双向认证,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------| ----| --------------- |
| options | [TLSConnectOptions](#tlsconnectoptions9) | 是 | 连接所需要的参数。|
**返回值:**
| 类型 | 说明 |
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | 以Promise形式返回,成功无返回,失败返回错误码,错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 401 | Parameter error. |
| 2303104 | Interrupted system call. |
| 2303109 | Bad file number. |
| 2303111 | Resource temporarily unavailable try again. |
| 2303113 | System permission denied. |
| 2303188 | Socket operation on non-socket. |
| 2303191 | Protocol wrong type for socket. |
| 2303198 | Address already in use. |
| 2303199 | Cannot assign requested address. |
| 2303210 | Connection timed out. |
| 2303501 | SSL is null. |
| 2303502 | Error in tls reading. |
| 2303503 | Error in tls writing |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**示例:**
```js
let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let options = {
ALPNProtocols: ["spdy/1", "http/1.1"],
address: {
address: "xxxx",
port: xxxx,
family: 1,
},
secureOptions: {
key: "xxxx",
cert: "xxxx",
ca: ["xxxx"],
passwd: "xxxx",
protocols: [socket.Protocol.TLSv12],
useRemoteCipherPrefer: true,
signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
cipherSuite: "AES256-SHA256",
},
};
tlsTwoWay.connect(options).then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
let oneWayOptions = {
address: {
address: "192.168.xxx.xxx",
port: xxxx,
family: 1,
},
secureOptions: {
ca: ["xxxx","xxxx"],
cipherSuite: "AES256-SHA256",
},
};
tlsOneWay.connect(oneWayOptions).then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getRemoteAddress<sup>9+</sup>
getRemoteAddress\(callback: AsyncCallback<NetAddress\>\): void
在TLSSocket通信连接成功之后,获取对端Socket地址。使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<[NetAddress](#netaddress)> | 是 | 回调函数。成功返回对端的socket地址,失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**示例:**
```js
tls.getRemoteAddress((err, data) => {
if (err) {
console.log('getRemoteAddress fail');
return;
}
console.log('getRemoteAddress success:' + JSON.stringify(data));
});
```
### getRemoteAddress<sup>9+</sup>
getRemoteAddress\(\): Promise\<NetAddress>
在TLSSocket通信连接成功之后,获取对端Socket地址。使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| :------------------------------------------ | :------------------------------------------ |
| Promise\<[NetAddress](#netaddress)> | 以Promise形式返回获取对端socket地址的结果。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error. |
**示例:**
```js
let promise = tls.getRemoteAddress();
promise.then(() => {
console.log('getRemoteAddress success');
}).catch(err => {
console.log('getRemoteAddress fail');
});
```
### getCertificate<sup>9+</sup>
getCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)>): void
在TLSSocket通信连接成功之后,获取本地的数字证书,该接口只适用于双向认证时,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)> | 是 | 回调函数,成功返回本地的证书,失败返回错误码,错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303504 | Error looking up x509. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getCertificate((err, data) => {
if (err) {
console.log("getCertificate callback error = " + err);
} else {
console.log("getCertificate callback = " + data);
}
});
```
### getCertificate<sup>9+</sup>
getCertificate():Promise\<[X509CertRawData](#x509certrawdata9)>
在TLSSocket通信连接之后,获取本地的数字证书,该接口只适用于双向认证时,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| -------------- | -------------------- |
| Promise\<[X509CertRawData](#x509certrawdata9)> | 以Promise形式返回本地的数字证书的结果。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303504 | Error looking up x509. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getCertificate().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getRemoteCertificate<sup>9+</sup>
getRemoteCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)>): void
在TLSSocket通信连接成功之后,获取服务端的数字证书,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)> | 是 | 回调函数,返回服务端的证书。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getRemoteCertificate((err, data) => {
if (err) {
console.log("getRemoteCertificate callback error = " + err);
} else {
console.log("getRemoteCertificate callback = " + data);
}
});
```
### getRemoteCertificate<sup>9+</sup>
getRemoteCertificate():Promise\<[X509CertRawData](#x509certrawdata9)>
在TLSSocket通信连接成功之后,获取服务端的数字证书,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| -------------- | -------------------- |
| Promise\<[X509CertRawData](#x509certrawdata9)> | 以Promise形式返回服务端的数字证书的结果。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getRemoteCertificate().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getProtocol<sup>9+</sup>
getProtocol(callback: AsyncCallback\<string>): void
在TLSSocket通信连接成功之后,获取通信的协议版本,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<string> | 是 | 回调函数,返回通信的协议。失败返回错误码,错误信息。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------- |
| 2303501 | SSL is null. |
| 2303505 | Error occurred in the tls system call. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getProtocol((err, data) => {
if (err) {
console.log("getProtocol callback error = " + err);
} else {
console.log("getProtocol callback = " + data);
}
});
```
### getProtocol<sup>9+</sup>
getProtocol():Promise\<string>
在TLSSocket通信连接成功之后,获取通信的协议版本,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| -------------- | -------------------- |
| Promise\<string> | 以Promise形式返回通信的协议。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303505 | Error occurred in the tls system call. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getProtocol().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getCipherSuite<sup>9+</sup>
getCipherSuite(callback: AsyncCallback\<Array\<string>>): void
在TLSSocket通信连接成功之后,获取通信双方协商后的加密套件,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<Array\<string>> | 是 | 回调函数,返回通信双方支持的加密套件。 失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303502 | Error in tls reading. |
| 2303505 | Error occurred in the tls system call. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getCipherSuite((err, data) => {
if (err) {
console.log("getCipherSuite callback error = " + err);
} else {
console.log("getCipherSuite callback = " + data);
}
});
```
### getCipherSuite<sup>9+</sup>
getCipherSuite(): Promise\<Array\<string>>
在TLSSocket通信连接成功之后,获取通信双方协商后的加密套件,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| ---------------------- | --------------------- |
| Promise\<Array\<string>> | 以Promise形式返回通信双方支持的加密套件。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2303502 | Error in tls reading. |
| 2303505 | Error occurred in the tls system call. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getCipherSuite().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### getSignatureAlgorithms<sup>9+</sup>
getSignatureAlgorithms(callback: AsyncCallback\<Array\<string>>): void
在TLSSocket通信连接成功之后,获取通信双方协商后签名算法,该接口只适配双向认证模式下,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------------------------| ---- | ---------------|
| callback | AsyncCallback\<Array\<string>> | 是 | 回调函数,返回双方支持的签名算法。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getSignatureAlgorithms((err, data) => {
if (err) {
console.log("getSignatureAlgorithms callback error = " + err);
} else {
console.log("getSignatureAlgorithms callback = " + data);
}
});
```
### getSignatureAlgorithms<sup>9+</sup>
getSignatureAlgorithms(): Promise\<Array\<string>>
在TLSSocket通信连接成功之后,获取通信双方协商后的签名算法,该接口只适配双向认证模式下,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| ---------------------- | -------------------- |
| Promise\<Array\<string>> | 以Promise形式返回获取到的双方支持的签名算法。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ------------------------------ |
| 2303501 | SSL is null. |
| 2300002 | System internal error. |
**示例:**
```js
tls.getSignatureAlgorithms().then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
```
### send<sup>9+</sup>
send(data: string, callback: AsyncCallback\<void>): void
在TLSSocket通信连接成功之后,向服务端发送消息,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -----------------------------| ---- | ---------------|
| data | string | 是 | 发送的数据内容。 |
| callback | AsyncCallback\<void> | 是 | 回调函数,返回TLSSocket发送数据的结果。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 401 | Parameter error. |
| 2303501 | SSL is null. |
| 2303503 | Error in tls writing |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**示例:**
```js
tls.send("xxxx", (err) => {
if (err) {
console.log("send callback error = " + err);
} else {
console.log("send success");
}
});
```
### send<sup>9+</sup>
send(data: string): Promise\<void>
在TLSSocket通信连接成功之后,向服务端发送消息,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -----------------------------| ---- | ---------------|
| data | string | 是 | 发送的数据内容。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 401 | Parameter error. |
| 2303501 | SSL is null. |
| 2303503 | Error in tls writing |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**返回值:**
| 类型 | 说明 |
| -------------- | -------------------- |
| Promise\<void> | 以Promise形式返回,返回TLSSocket发送数据的结果。失败返回错误码,错误信息。 |
**示例:**
```js
tls.send("xxxx").then(() =>{
console.log("send success");
}).catch(err => {
console.error(err);
});
```
### close<sup>9+</sup>
close(callback: AsyncCallback\<void>): void
在TLSSocket通信连接成功之后,断开连接,使用callback方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -----------------------------| ---- | ---------------|
| callback | AsyncCallback\<void> | 是 | 回调函数,成功返回TLSSocket关闭连接的结果。 失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 2303501 | SSL is null. |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**示例:**
```js
tls.close((err) => {
if (err) {
console.log("close callback error = " + err);
} else {
console.log("close success");
}
});
```
### close<sup>9+</sup>
close(): Promise\<void>
在TLSSocket通信连接成功之后,断开连接,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Communication.NetStack
**返回值:**
| 类型 | 说明 |
| -------------- | -------------------- |
| Promise\<void> | 以Promise形式返回,返回TLSSocket关闭连接的结果。失败返回错误码,错误信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 2303501 | SSL is null. |
| 2303505 | Error occurred in the tls system call. |
| 2303506 | Error clearing tls connection. |
| 2300002 | System internal error. |
**示例:**
```js
tls.close().then(() =>{
console.log("close success");
}).catch(err => {
console.error(err);
});
```
## TLSConnectOptions<sup>9+</sup>
TLS连接的操作。
**系统能力**:SystemCapability.Communication.NetStack
| 名称 | 类型 | 必填 | 说明 |
| -------------- | ------------------------------------- | --- |-------------- |
| address | [NetAddress](#netaddress) | 是 | 网关地址。 |
| secureOptions | [TLSSecureOptions](#tlssecureoptions9) | 是 | TLS安全相关操作。|
| ALPNProtocols | Array\<string> | 否 | ALPN协议。 |
## TLSSecureOptions<sup>9+</sup>
TLS安全相关操作,其中ca证书为必选参数,其他参数为可选参数。当本地证书cert和私钥key不为空时,开启双向验证模式。cert和key其中一项为空时,开启单向验证模式。
**系统能力**:SystemCapability.Communication.NetStack
| 名称 | 类型 | 必填 | 说明 |
| --------------------- | ------------------------------------------------------ | --- |----------------------------------- |
| ca | string \| Array\<string> | 是 | 服务端的ca证书,用于认证校验服务端的数字证书。|
| cert | string | 否 | 本地客户端的数字证书。 |
| key | string | 否 | 本地数字证书的私钥。 |
| passwd | string | 否 | 读取私钥的密码。 |
| protocols | [Protocol](#protocol9) \|Array\<[Protocol](#protocol9)> | 否 | TLS的协议版本。 |
| useRemoteCipherPrefer | boolean | 否 | 优先使用对等方的密码套件。 |
| signatureAlgorithms | string | 否 | 通信过程中的签名算法。 |
| cipherSuite | string | 否 | 通信过程中的加密套件。 |
## Protocol<sup>9+</sup>
TLS通信的协议版本。
**系统能力**:SystemCapability.Communication.NetStack
| 名称 | 值 | 说明 |
| --------- | --------- |------------------ |
| TLSv12 | "TLSv1.2" | 使用TLSv1.2协议通信。 |
| TLSv13 | "TLSv1.3" | 使用TLSv1.3协议通信。 |
## X509CertRawData<sup>9+</sup>
存储证书的数据。
**系统能力**:SystemCapability.Communication.NetStack
| 类型 | 说明 |
| --------------------------------------------------------------------- | --------------------- |
|[cryptoFramework.EncodingBlob](js-apis-cryptoFramework.md#datablob) | 存储证书的数据和编码格式 |
\ No newline at end of file
...@@ -75,6 +75,17 @@ createHttp\(\): HttpRequest ...@@ -75,6 +75,17 @@ createHttp\(\): HttpRequest
| :---------- | :----------------------------------------------------------- | | :---------- | :----------------------------------------------------------- |
| HttpRequest | 返回一个HttpRequest对象,里面包括request、destroy、on和off方法。 | | HttpRequest | 返回一个HttpRequest对象,里面包括request、destroy、on和off方法。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2100002 | System internal error. |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:** **示例:**
```js ```js
...@@ -103,6 +114,22 @@ request\(url: string, callback: AsyncCallback\<HttpResponse\>\):void ...@@ -103,6 +114,22 @@ request\(url: string, callback: AsyncCallback\<HttpResponse\>\):void
| url | string | 是 | 发起网络请求的URL地址。 | | url | string | 是 | 发起网络请求的URL地址。 |
| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | 是 | 回调函数。 | | callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300003 | URL using bad/illegal format or missing URL |
| 2300005 | Couldn't resolve proxy name |
| 2300006 | Couldn't resolve host name |
| 2300007 | Couldn't connect to server |
| 2300052 | Server returned nothing (no headers, no data) |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:** **示例:**
```js ```js
...@@ -136,6 +163,23 @@ request\(url: string, options: HttpRequestOptions, callback: AsyncCallback<HttpR ...@@ -136,6 +163,23 @@ request\(url: string, options: HttpRequestOptions, callback: AsyncCallback<HttpR
| options | HttpRequestOptions | 是 | 参考[HttpRequestOptions](#httprequestoptions)。 | | options | HttpRequestOptions | 是 | 参考[HttpRequestOptions](#httprequestoptions)。 |
| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | 是 | 回调函数。 | | callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300003 | URL using bad/illegal format or missing URL |
| 2300005 | Couldn't resolve proxy name |
| 2300006 | Couldn't resolve host name |
| 2300007 | Couldn't connect to server |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:** **示例:**
```js ```js
...@@ -184,6 +228,20 @@ request\(url: string, options? : HttpRequestOptions\): Promise<HttpResponse\> ...@@ -184,6 +228,20 @@ request\(url: string, options? : HttpRequestOptions\): Promise<HttpResponse\>
| :------------------------------------- | :-------------------------------- | | :------------------------------------- | :-------------------------------- |
| Promise<[HttpResponse](#httpresponse)> | 以Promise形式返回发起请求的结果。 | | Promise<[HttpResponse](#httpresponse)> | 以Promise形式返回发起请求的结果。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300003 | URL using bad/illegal format or missing URL |
| 2300005 | Couldn't resolve proxy name |
| 2300006 | Couldn't resolve host name |
| 2300007 | Couldn't connect to server |
| 2300009 | Access denied to remote resource |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:** **示例:**
...@@ -216,6 +274,15 @@ destroy\(\): void ...@@ -216,6 +274,15 @@ destroy\(\): void
**系统能力**:SystemCapability.Communication.NetStack **系统能力**:SystemCapability.Communication.NetStack
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:** **示例:**
```js ```js
...@@ -240,6 +307,35 @@ on\(type: 'headerReceive', callback: AsyncCallback<Object\>\): void ...@@ -240,6 +307,35 @@ on\(type: 'headerReceive', callback: AsyncCallback<Object\>\): void
| type | string | 是 | 订阅的事件类型,'headerReceive'。 | | type | string | 是 | 订阅的事件类型,'headerReceive'。 |
| callback | AsyncCallback\<Object\> | 是 | 回调函数。 | | callback | AsyncCallback\<Object\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300003 | URL using bad/illegal format or missing URL |
| 2300005 | Couldn't resolve proxy name |
| 2300006 | Couldn't resolve host name |
| 2300007 | Couldn't connect to server |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300023 | Failed writing received data to disk/application |
| 2300025 | Upload failed |
| 2300027 | Out of memory |
| 2300028 | Timeout was reached |
| 2300052 | Server returned nothing (no headers, no data) |
| 2300056 | Failure when receiving data from the peer |
| 2300058 | Problem with the local SSL certificate |
| 2300060 | SSL peer certificate or SSH remote key was not OK |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding |
| 2300063 | Maximum file size exceeded |
| 2300070 | Disk full or allocation exceeded |
| 2300077 | Problem with the SSL CA cert (path? access rights?) |
| 2300078 | Remote file not found |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:** **示例:**
```js ```js
...@@ -273,6 +369,22 @@ off\(type: 'headerReceive', callback?: AsyncCallback<Object\>\): void ...@@ -273,6 +369,22 @@ off\(type: 'headerReceive', callback?: AsyncCallback<Object\>\): void
| type | string | 是 | 取消订阅的事件类型,'headerReceive'。 | | type | string | 是 | 取消订阅的事件类型,'headerReceive'。 |
| callback | AsyncCallback\<Object\> | 否 | 回调函数。 | | callback | AsyncCallback\<Object\> | 否 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300003 | URL using bad/illegal format or missing URL |
| 2300005 | Couldn't resolve proxy name |
| 2300006 | Couldn't resolve host name |
| 2300007 | Couldn't connect to server |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:** **示例:**
```js ```js
...@@ -294,6 +406,35 @@ on\(type: 'headersReceive', callback: Callback<Object\>\): void ...@@ -294,6 +406,35 @@ on\(type: 'headersReceive', callback: Callback<Object\>\): void
| type | string | 是 | 订阅的事件类型:'headersReceive'。 | | type | string | 是 | 订阅的事件类型:'headersReceive'。 |
| callback | Callback\<Object\> | 是 | 回调函数。 | | callback | Callback\<Object\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300003 | URL using bad/illegal format or missing URL |
| 2300005 | Couldn't resolve proxy name |
| 2300006 | Couldn't resolve host name |
| 2300007 | Couldn't connect to server |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300023 | Failed writing received data to disk/application |
| 2300025 | Upload failed |
| 2300027 | Out of memory |
| 2300028 | Timeout was reached |
| 2300052 | Server returned nothing (no headers, no data) |
| 2300056 | Failure when receiving data from the peer |
| 2300058 | Problem with the local SSL certificate |
| 2300060 | SSL peer certificate or SSH remote key was not OK |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding |
| 2300063 | Maximum file size exceeded |
| 2300070 | Disk full or allocation exceeded |
| 2300077 | Problem with the SSL CA cert (path? access rights?) |
| 2300078 | Remote file not found |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:** **示例:**
```js ```js
...@@ -320,6 +461,22 @@ off\(type: 'headersReceive', callback?: Callback<Object\>\): void ...@@ -320,6 +461,22 @@ off\(type: 'headersReceive', callback?: Callback<Object\>\): void
| type | string | 是 | 取消订阅的事件类型:'headersReceive'。 | | type | string | 是 | 取消订阅的事件类型:'headersReceive'。 |
| callback | Callback\<Object\> | 否 | 回调函数。 | | callback | Callback\<Object\> | 否 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300003 | URL using bad/illegal format or missing URL |
| 2300005 | Couldn't resolve proxy name |
| 2300006 | Couldn't resolve host name |
| 2300007 | Couldn't connect to server |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:** **示例:**
```js ```js
...@@ -341,6 +498,35 @@ once\(type: 'headersReceive', callback: Callback<Object\>\): void ...@@ -341,6 +498,35 @@ once\(type: 'headersReceive', callback: Callback<Object\>\): void
| type | string | 是 | 订阅的事件类型:'headersReceive'。 | | type | string | 是 | 订阅的事件类型:'headersReceive'。 |
| callback | Callback\<Object\> | 是 | 回调函数。 | | callback | Callback\<Object\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300003 | URL using bad/illegal format or missing URL |
| 2300005 | Couldn't resolve proxy name |
| 2300006 | Couldn't resolve host name |
| 2300007 | Couldn't connect to server |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300023 | Failed writing received data to disk/application |
| 2300025 | Upload failed |
| 2300027 | Out of memory |
| 2300028 | Timeout was reached |
| 2300052 | Server returned nothing (no headers, no data) |
| 2300056 | Failure when receiving data from the peer |
| 2300058 | Problem with the local SSL certificate |
| 2300060 | SSL peer certificate or SSH remote key was not OK |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding |
| 2300063 | Maximum file size exceeded |
| 2300070 | Disk full or allocation exceeded |
| 2300077 | Problem with the SSL CA cert (path? access rights?) |
| 2300078 | Remote file not found |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:** **示例:**
```js ```js
...@@ -438,7 +624,7 @@ request方法回调函数的返回值类型。 ...@@ -438,7 +624,7 @@ request方法回调函数的返回值类型。
| -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | | -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
| result | string \| Object \| ArrayBuffer<sup>6+</sup> | 是 | HTTP请求根据响应头中Content-type类型返回对应的响应格式内容:<br />- application/json:返回JSON格式的字符串,如需HTTP响应具体内容,需开发者自行解析<br />- application/octet-stream:ArrayBuffer<br />- 其他:string | | result | string \| Object \| ArrayBuffer<sup>6+</sup> | 是 | HTTP请求根据响应头中Content-type类型返回对应的响应格式内容:<br />- application/json:返回JSON格式的字符串,如需HTTP响应具体内容,需开发者自行解析<br />- application/octet-stream:ArrayBuffer<br />- 其他:string |
| resultType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | 是 | 返回值类型。 | | resultType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | 是 | 返回值类型。 |
| responseCode | [ResponseCode](#responsecode) \| number | 是 | 回调函数执行成功时,此字段为[ResponseCode](#responsecode)。若执行失败,错误码将会从AsyncCallback中的err字段返回。错误码参考[Response错误码](#response常用错误码) | | responseCode | [ResponseCode](#responsecode) \| number | 是 | 回调函数执行成功时,此字段为[ResponseCode](#responsecode)。若执行失败,错误码将会从AsyncCallback中的err字段返回。 |
| header | Object | 是 | 发起HTTP请求返回来的响应头。当前返回的是JSON格式字符串,如需具体字段内容,需开发者自行解析。常见字段及解析方式如下:<br/>- Content-Type:header['Content-Type'];<br />- Status-Line:header['Status-Line'];<br />- Date:header.Date/header['Date'];<br />- Server:header.Server/header['Server']; | | header | Object | 是 | 发起HTTP请求返回来的响应头。当前返回的是JSON格式字符串,如需具体字段内容,需开发者自行解析。常见字段及解析方式如下:<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\> | 是 | 服务器返回的 cookies。 | | cookies<sup>8+</sup> | Array\<string\> | 是 | 服务器返回的 cookies。 |
...@@ -462,6 +648,38 @@ createHttpResponseCache(cacheSize?: number): HttpResponseCache ...@@ -462,6 +648,38 @@ createHttpResponseCache(cacheSize?: number): HttpResponseCache
| :---------- | :----------------------------------------------------------- | | :---------- | :----------------------------------------------------------- |
| [HttpResponseCache](#httpresponsecache9) | 返回一个存储HTTP访问请求响应的对象。 | | [HttpResponseCache](#httpresponsecache9) | 返回一个存储HTTP访问请求响应的对象。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300016 | Error in the HTTP2 framing layer |
| 2300018 | Transferred a partial file |
| 2300023 | Failed writing received data to disk/application |
| 2300025 | Upload failed |
| 2300026 | Failed to open/read local data from file/application |
| 2300027 | Out of memory |
| 2300028 | Timeout was reached |
| 2300047 | Number of redirects hit maximum amount |
| 2300052 | Server returned nothing (no headers, no data) |
| 2300055 | Failed sending data to the peer |
| 2300056 | Failure when receiving data from the peer |
| 2300058 | Problem with the local SSL certificate |
| 2300059 | Couldn't use specified SSL cipher |
| 2300060 | SSL peer certificate or SSH remote key was not OK |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding |
| 2300063 | Maximum file size exceeded |
| 2300070 | Disk full or allocation exceeded |
| 2300073 | Remote file already exists |
| 2300077 | Problem with the SSL CA cert (path? access rights?) |
| 2300078 | Remote file not found |
| 2300094 | An authentication function returned an error |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:** **示例:**
```js ```js
...@@ -487,6 +705,39 @@ flush(callback: AsyncCallback\<void>): void ...@@ -487,6 +705,39 @@ flush(callback: AsyncCallback\<void>): void
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | 是 | 回调函数返回写入结果。 | | callback | AsyncCallback\<void> | 是 | 回调函数返回写入结果。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300016 | Error in the HTTP2 framing layer |
| 2300018 | Transferred a partial file |
| 2300023 | Failed writing received data to disk/application |
| 2300025 | Upload failed |
| 2300026 | Failed to open/read local data from file/application |
| 2300027 | Out of memory |
| 2300028 | Timeout was reached |
| 2300047 | Number of redirects hit maximum amount |
| 2300052 | Server returned nothing (no headers, no data) |
| 2300055 | Failed sending data to the peer |
| 2300056 | Failure when receiving data from the peer |
| 2300058 | Problem with the local SSL certificate |
| 2300059 | Couldn't use specified SSL cipher |
| 2300060 | SSL peer certificate or SSH remote key was not OK |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding |
| 2300063 | Maximum file size exceeded |
| 2300070 | Disk full or allocation exceeded |
| 2300073 | Remote file already exists |
| 2300077 | Problem with the SSL CA cert (path? access rights?) |
| 2300078 | Remote file not found |
| 2300094 | An authentication function returned an error |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:** **示例:**
```js ```js
...@@ -513,6 +764,39 @@ flush(): Promise\<void> ...@@ -513,6 +764,39 @@ flush(): Promise\<void>
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<void>> | 以Promise形式返回写入结果。 | | Promise\<void>> | 以Promise形式返回写入结果。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300016 | Error in the HTTP2 framing layer |
| 2300018 | Transferred a partial file |
| 2300023 | Failed writing received data to disk/application |
| 2300025 | Upload failed |
| 2300026 | Failed to open/read local data from file/application |
| 2300027 | Out of memory |
| 2300028 | Timeout was reached |
| 2300047 | Number of redirects hit maximum amount |
| 2300052 | Server returned nothing (no headers, no data) |
| 2300055 | Failed sending data to the peer |
| 2300056 | Failure when receiving data from the peer |
| 2300058 | Problem with the local SSL certificate |
| 2300059 | Couldn't use specified SSL cipher |
| 2300060 | SSL peer certificate or SSH remote key was not OK |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding |
| 2300063 | Maximum file size exceeded |
| 2300070 | Disk full or allocation exceeded |
| 2300073 | Remote file already exists |
| 2300077 | Problem with the SSL CA cert (path? access rights?) |
| 2300078 | Remote file not found |
| 2300094 | An authentication function returned an error |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:** **示例:**
```js ```js
...@@ -537,6 +821,22 @@ delete(callback: AsyncCallback\<void>): void ...@@ -537,6 +821,22 @@ delete(callback: AsyncCallback\<void>): void
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | 是 | 回调函数返回删除结果。| | callback | AsyncCallback\<void> | 是 | 回调函数返回删除结果。|
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300001 | Unsupported protocol |
| 2300003 | URL using bad/illegal format or missing URL |
| 2300005 | Couldn't resolve proxy name |
| 2300006 | Couldn't resolve host name |
| 2300007 | Couldn't connect to server |
| 2300008 | Weird server reply |
| 2300009 | Access denied to remote resource |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:** **示例:**
```js ```js
...@@ -562,6 +862,16 @@ delete(): Promise\<void> ...@@ -562,6 +862,16 @@ delete(): Promise\<void>
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<void> | 以Promise形式返回删除结果。 | | Promise\<void> | 以Promise形式返回删除结果。 |
**错误码:**
| 错误码ID | 错误信息 |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 2300999 | Unknown Other Error |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
**示例:** **示例:**
```js ```js
...@@ -572,19 +882,6 @@ httpResponseCache.delete().then(() => { ...@@ -572,19 +882,6 @@ httpResponseCache.delete().then(() => {
}); });
``` ```
## Response常用错误码
| 错误码 | 说明 |
| ------ | ------------------------------------------------------------ |
| -1 | 参数错误。检查参数的个数与类型是否正确。 |
| 3 | URL格式错误。检查URL的格式与语法是否正确。 |
| 4 | 构建时无法找到内置的请求功能、协议或选项。一个功能或选项是不启用或明确禁用时,为了得到它的功能,你需要得到一个重建的libcurl。 |
| 5 | 无法解析代理,指定的代理服务器主机无法解析。建议排查:1、url地址是否正确。2、联网是否正常,网络是否可以和外部进行通信。3、是否有网络访问权限。 |
| 6 | 无法解析主机,指定的远程主机无法解析。建议排查:1、url地址是否正确。2、联网是否正常,网络是否可以和外部进行通信。3、是否有网络访问权限。 |
| 7 | 无法连接代理或主机。建议排查:1、端口号是否有问题。 2、查看本地是否开启http的代理影响的。 |
更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html)
## HttpDataType<sup>9+</sup> ## HttpDataType<sup>9+</sup>
http的数据类型。 http的数据类型。
......
...@@ -32,6 +32,19 @@ setIfaceConfig(iface: string, ic: InterfaceConfiguration, callback: AsyncCallbac ...@@ -32,6 +32,19 @@ setIfaceConfig(iface: string, ic: InterfaceConfiguration, callback: AsyncCallbac
| ic | [InterfaceConfiguration](#interfaceconfiguration) | 是 | 要设置的网络接口配置信息 | | ic | [InterfaceConfiguration](#interfaceconfiguration) | 是 | 要设置的网络接口配置信息 |
| callback | AsyncCallback\<void> | 是 | 回调函数,成功无返回,失败返回对应错误码。 | | callback | AsyncCallback\<void> | 是 | 回调函数,成功无返回,失败返回对应错误码。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------------------|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service.|
| 2200003 | System internal error. |
| 2201005 | The device information does not exist. |
| 2201006 | Device disconnected. |
| 2201007 | Failed to write the user configuration. |
**示例:** **示例:**
```js ```js
...@@ -71,6 +84,19 @@ setIfaceConfig(iface: string, ic: InterfaceConfiguration): Promise\<void> ...@@ -71,6 +84,19 @@ setIfaceConfig(iface: string, ic: InterfaceConfiguration): Promise\<void>
| ------------------- | ----------------------------------------------------------- | | ------------------- | ----------------------------------------------------------- |
| Promise\<void> | 以Promise形式返回执行结果。成功无返回,失败返回对应错误码。 | | Promise\<void> | 以Promise形式返回执行结果。成功无返回,失败返回对应错误码。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------------------|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service.|
| 2200003 | System internal error. |
| 2201005 | The device information does not exist. |
| 2201006 | Device disconnected. |
| 2201007 | Failed to write the user configuration. |
**示例:** **示例:**
```js ```js
...@@ -101,6 +127,17 @@ getIfaceConfig(iface: string, callback: AsyncCallback\<InterfaceConfiguration>): ...@@ -101,6 +127,17 @@ getIfaceConfig(iface: string, callback: AsyncCallback\<InterfaceConfiguration>):
| iface | string | 是 | 指定网络接口 | | iface | string | 是 | 指定网络接口 |
| callback | AsyncCallback\<[InterfaceConfiguration](#interfaceconfiguration)> | 是 | 回调函数,返回指定网络接口信息 | | callback | AsyncCallback\<[InterfaceConfiguration](#interfaceconfiguration)> | 是 | 回调函数,返回指定网络接口信息 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------------------|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service.|
| 2200003 | System internal error. |
| 2201005 | The device information does not exist. |
**示例:** **示例:**
```js ```js
...@@ -143,6 +180,17 @@ getIfaceConfig(iface: string): Promise\<InterfaceConfiguration> ...@@ -143,6 +180,17 @@ getIfaceConfig(iface: string): Promise\<InterfaceConfiguration>
| --------------------------------- | ---------------------------------- | | --------------------------------- | ---------------------------------- |
| Promise\<[InterfaceConfiguration](#interfaceconfiguration)> | 以Promise形式返回接口信息。 | | Promise\<[InterfaceConfiguration](#interfaceconfiguration)> | 以Promise形式返回接口信息。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------------------|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service.|
| 2200003 | System internal error. |
| 2201005 | The device information does not exist. |
**示例:** **示例:**
```js ```js
...@@ -178,6 +226,17 @@ isIfaceActive(iface: string, callback: AsyncCallback\<number>): void ...@@ -178,6 +226,17 @@ isIfaceActive(iface: string, callback: AsyncCallback\<number>): void
| iface | string | 是 | 接口名。为空时代表查询是否存在激活接口 | | iface | string | 是 | 接口名。为空时代表查询是否存在激活接口 |
| callback | AsyncCallback\<number> | 是 | 回调函数,已激活:1,未激活:0,其他为获取失败错误码。 | | callback | AsyncCallback\<number> | 是 | 回调函数,已激活:1,未激活:0,其他为获取失败错误码。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------------------|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service.|
| 2200003 | System internal error. |
| 2201005 | The device information does not exist. |
**示例:** **示例:**
```js ```js
...@@ -214,6 +273,17 @@ isIfaceActive(iface: string): Promise\<number> ...@@ -214,6 +273,17 @@ isIfaceActive(iface: string): Promise\<number>
| ----------------| ------------------------------------------------------------------ | | ----------------| ------------------------------------------------------------------ |
| Promise\<number> | 以Promise形式返回获取结果。已激活:1,未激活:0,其他为获取失败错误码。| | Promise\<number> | 以Promise形式返回获取结果。已激活:1,未激活:0,其他为获取失败错误码。|
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------------------|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service.|
| 2200003 | System internal error. |
| 2201005 | The device information does not exist. |
**示例:** **示例:**
```js ```js
...@@ -242,6 +312,14 @@ getAllActiveIfaces(callback: AsyncCallback\<Array\<string>>): void ...@@ -242,6 +312,14 @@ getAllActiveIfaces(callback: AsyncCallback\<Array\<string>>): void
| -------- | ------------------------------------ | ---- | ------------------------------ | | -------- | ------------------------------------ | ---- | ------------------------------ |
| callback | AsyncCallback\<Array\<string>> | 是 | 回调函数,返回值为对应接口名。 | | callback | AsyncCallback\<Array\<string>> | 是 | 回调函数,返回值为对应接口名。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------------------|
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service.|
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
...@@ -275,6 +353,14 @@ getAllActiveIfaces(): Promise\<Array\<string>> ...@@ -275,6 +353,14 @@ getAllActiveIfaces(): Promise\<Array\<string>>
| ------------------------------ | ----------------------------------------------- | | ------------------------------ | ----------------------------------------------- |
| Promise\<Array\<string>> | 以Promise形式返回获取结果。返回值为对应接口名。 | | Promise\<Array\<string>> | 以Promise形式返回获取结果。返回值为对应接口名。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | ----------------------------------------|
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service.|
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
......
...@@ -30,6 +30,15 @@ isSharingSupported(callback: AsyncCallback\<boolean>): void ...@@ -30,6 +30,15 @@ isSharingSupported(callback: AsyncCallback\<boolean>): void
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<boolean> | 是 | 回调函数,返回true代表支持网络共享。 | | callback | AsyncCallback\<boolean> | 是 | 回调函数,返回true代表支持网络共享。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
| 2202011 | Cannot get network sharing configuration. |
**示例:** **示例:**
```js ```js
...@@ -57,6 +66,15 @@ isSharingSupported(): Promise\<boolean> ...@@ -57,6 +66,15 @@ isSharingSupported(): Promise\<boolean>
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<boolean> | 以Promise形式返回是否支持共享结果。 | | Promise\<boolean> | 以Promise形式返回是否支持共享结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
| 2202011 | Cannot get network sharing configuration. |
**示例:** **示例:**
```js ```js
...@@ -85,6 +103,14 @@ isSharing(callback: AsyncCallback\<boolean>): void ...@@ -85,6 +103,14 @@ isSharing(callback: AsyncCallback\<boolean>): void
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<boolean> | 是 | 回调函数,返回true代表网络共享中。 | | callback | AsyncCallback\<boolean> | 是 | 回调函数,返回true代表网络共享中。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
...@@ -112,6 +138,14 @@ isSharing(): Promise\<boolean> ...@@ -112,6 +138,14 @@ isSharing(): Promise\<boolean>
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<boolean> | 以Promise形式返回网络共享状态结果,返回true代表网络共享中。 | | Promise\<boolean> | 以Promise形式返回网络共享状态结果,返回true代表网络共享中。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
...@@ -141,6 +175,21 @@ startSharing(type: SharingIfaceType, callback: AsyncCallback\<void>): void ...@@ -141,6 +175,21 @@ startSharing(type: SharingIfaceType, callback: AsyncCallback\<void>): void
| type | [SharingIfaceType](#sharingifacetype) | 是 | 共享类型,0:Wi-Fi 1:USB 2:BLUETOOTH。 | | type | [SharingIfaceType](#sharingifacetype) | 是 | 共享类型,0:Wi-Fi 1:USB 2:BLUETOOTH。 |
| callback | AsyncCallback\<void> | 是 | 回调函数,返回开启网络共享结果。 | | callback | AsyncCallback\<void> | 是 | 回调函数,返回开启网络共享结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
| 2202004 | Try to share an unavailable iface. |
| 2202005 | WiFi sharing failed. |
| 2202006 | Bluetooth sharing failed. |
| 2202009 | Network share enable forwarding error. |
| 2202011 | Cannot get network sharing configuration. |
**示例:** **示例:**
```js ```js
...@@ -174,6 +223,21 @@ startSharing(type: SharingIfaceType): Promise\<void> ...@@ -174,6 +223,21 @@ startSharing(type: SharingIfaceType): Promise\<void>
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<void> | 以Promise形式返回开启共享执行结果。 | | Promise\<void> | 以Promise形式返回开启共享执行结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
| 2202004 | Try to share an unavailable iface. |
| 2202005 | WiFi sharing failed. |
| 2202006 | Bluetooth sharing failed. |
| 2202009 | Network share enable forwarding error. |
| 2202011 | Cannot get network sharing configuration. |
**示例:** **示例:**
```js ```js
...@@ -204,6 +268,19 @@ stopSharing(type: SharingIfaceType, callback: AsyncCallback\<void>): void ...@@ -204,6 +268,19 @@ stopSharing(type: SharingIfaceType, callback: AsyncCallback\<void>): void
| type | [SharingIfaceType](#sharingifacetype) | 是 | 共享类型,0:Wi-Fi 1:USB 2:BLUETOOTH。 | | type | [SharingIfaceType](#sharingifacetype) | 是 | 共享类型,0:Wi-Fi 1:USB 2:BLUETOOTH。 |
| callback | AsyncCallback\<void> | 是 | 回调函数,返回停止网络共享结果。 | | callback | AsyncCallback\<void> | 是 | 回调函数,返回停止网络共享结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
| 2202005 | WiFi sharing failed. |
| 2202006 | Bluetooth sharing failed. |
| 2202011 | Cannot get network sharing configuration. |
**示例:** **示例:**
```js ```js
...@@ -237,6 +314,19 @@ stopSharing(type: SharingIfaceType): Promise\<void> ...@@ -237,6 +314,19 @@ stopSharing(type: SharingIfaceType): Promise\<void>
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<void> | 以Promise形式返回关闭共享执行结果。 | | Promise\<void> | 以Promise形式返回关闭共享执行结果。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
| 2202005 | WiFi sharing failed. |
| 2202006 | Bluetooth sharing failed. |
| 2202011 | Cannot get network sharing configuration. |
**示例:** **示例:**
```js ```js
...@@ -266,6 +356,14 @@ getStatsRxBytes(callback: AsyncCallback\<number>): void ...@@ -266,6 +356,14 @@ getStatsRxBytes(callback: AsyncCallback\<number>): void
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<number> | 是 | 回调函数,number代表数据量,单位:KB。 | | callback | AsyncCallback\<number> | 是 | 回调函数,number代表数据量,单位:KB。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
...@@ -293,6 +391,14 @@ getStatsRxBytes(): Promise\<number> ...@@ -293,6 +391,14 @@ getStatsRxBytes(): Promise\<number>
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<number> | 以Promise形式返回共享网络接收数据量,单位:KB。 | | Promise\<number> | 以Promise形式返回共享网络接收数据量,单位:KB。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
...@@ -321,6 +427,14 @@ getStatsTxBytes(callback: AsyncCallback\<number>): void ...@@ -321,6 +427,14 @@ getStatsTxBytes(callback: AsyncCallback\<number>): void
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<number> | 是 | 回调函数,number代表数据量,单位:KB。 | | callback | AsyncCallback\<number> | 是 | 回调函数,number代表数据量,单位:KB。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
...@@ -348,6 +462,14 @@ getStatsTxBytes(): Promise\<number> ...@@ -348,6 +462,14 @@ getStatsTxBytes(): Promise\<number>
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<number> | 以Promise形式返回共享网络发送数据量,单位:KB。 | | Promise\<number> | 以Promise形式返回共享网络发送数据量,单位:KB。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
...@@ -376,6 +498,14 @@ getStatsTotalBytes(callback: AsyncCallback\<number>): void ...@@ -376,6 +498,14 @@ getStatsTotalBytes(callback: AsyncCallback\<number>): void
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<number> | 是 | 回调函数,number代表数据量,单位:KB。 | | callback | AsyncCallback\<number> | 是 | 回调函数,number代表数据量,单位:KB。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
...@@ -403,6 +533,14 @@ getStatsTotalBytes(): Promise\<number> ...@@ -403,6 +533,14 @@ getStatsTotalBytes(): Promise\<number>
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<number> | 以Promise形式返回共享网络总数据量,单位:KB。 | | Promise\<number> | 以Promise形式返回共享网络总数据量,单位:KB。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
...@@ -432,6 +570,16 @@ getSharingIfaces(state: SharingIfaceState, callback: AsyncCallback\<Array\<strin ...@@ -432,6 +570,16 @@ getSharingIfaces(state: SharingIfaceState, callback: AsyncCallback\<Array\<strin
| state | [SharingIfaceState](#sharingifacestate) | 是 | 网络共享状态。 | | state | [SharingIfaceState](#sharingifacestate) | 是 | 网络共享状态。 |
| callback | AsyncCallback\<Array\<string>> | 是 | 回调函数,返回指定状态的网卡名称列表。 | | callback | AsyncCallback\<Array\<string>> | 是 | 回调函数,返回指定状态的网卡名称列表。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
...@@ -466,6 +614,16 @@ getSharingIfaces(state: SharingIfaceState): Promise\<Array\<string>> ...@@ -466,6 +614,16 @@ getSharingIfaces(state: SharingIfaceState): Promise\<Array\<string>>
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<Array\<string>> | 以Promise形式返回指定状态网卡名称列表。 | | Promise\<Array\<string>> | 以Promise形式返回指定状态网卡名称列表。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
...@@ -496,6 +654,16 @@ getSharingState(type: SharingIfaceType, callback: AsyncCallback\<SharingIfaceSta ...@@ -496,6 +654,16 @@ getSharingState(type: SharingIfaceType, callback: AsyncCallback\<SharingIfaceSta
| type | [SharingIfaceType](#sharingifacetype) | 是 | 共享类型,0:Wi-Fi 1:USB 2:BLUETOOTH。 | | type | [SharingIfaceType](#sharingifacetype) | 是 | 共享类型,0:Wi-Fi 1:USB 2:BLUETOOTH。 |
| callback | AsyncCallback\<[SharingIfaceState](#sharingifacestate)> | 是 | 回调函数,返回指定类型网络共享状态。 | | callback | AsyncCallback\<[SharingIfaceState](#sharingifacestate)> | 是 | 回调函数,返回指定类型网络共享状态。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
...@@ -524,6 +692,16 @@ getSharingState(type: SharingIfaceType): Promise\<SharingIfaceState> ...@@ -524,6 +692,16 @@ getSharingState(type: SharingIfaceType): Promise\<SharingIfaceState>
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| type | [SharingIfaceType](#sharingifacetype) | 是 | 共享类型,0:Wi-Fi 1:USB 2:BLUETOOTH。 | | type | [SharingIfaceType](#sharingifacetype) | 是 | 共享类型,0:Wi-Fi 1:USB 2:BLUETOOTH。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
...@@ -560,6 +738,16 @@ getSharableRegexes(type: SharingIfaceType, callback: AsyncCallback\<Array\<strin ...@@ -560,6 +738,16 @@ getSharableRegexes(type: SharingIfaceType, callback: AsyncCallback\<Array\<strin
| type | [SharingIfaceType](#sharingifacetype) | 是 | 共享类型,0:Wi-Fi 1:USB 2:BLUETOOTH。 | | type | [SharingIfaceType](#sharingifacetype) | 是 | 共享类型,0:Wi-Fi 1:USB 2:BLUETOOTH。 |
| callback | AsyncCallback\<Array\<string>> | 是 | 回调函数,返回指定类型网卡名称正则表达式列表。 | | callback | AsyncCallback\<Array\<string>> | 是 | 回调函数,返回指定类型网卡名称正则表达式列表。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
...@@ -594,6 +782,16 @@ getSharableRegexes(type: SharingIfaceType): Promise\<Array\<string>> ...@@ -594,6 +782,16 @@ getSharableRegexes(type: SharingIfaceType): Promise\<Array\<string>>
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<Array\<string>> | 以Promise形式返回正则表达式列表。 | | Promise\<Array\<string>> | 以Promise形式返回正则表达式列表。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**示例:** **示例:**
```js ```js
...@@ -624,6 +822,13 @@ on(type: 'sharingStateChange', callback: Callback\<boolean>): void ...@@ -624,6 +822,13 @@ on(type: 'sharingStateChange', callback: Callback\<boolean>): void
| type | string | 是 | 事件名称。 | | type | string | 是 | 事件名称。 |
| callback | AsyncCallback\<boolean> | 是 | 回调函数,返回网络共享状态。 | | callback | AsyncCallback\<boolean> | 是 | 回调函数,返回网络共享状态。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
**示例:** **示例:**
```js ```js
...@@ -652,6 +857,13 @@ off(type: 'sharingStateChange', callback?: Callback\<boolean>): void ...@@ -652,6 +857,13 @@ off(type: 'sharingStateChange', callback?: Callback\<boolean>): void
| type | string | 是 | 事件名称。 | | type | string | 是 | 事件名称。 |
| callback | AsyncCallback\<boolean> | 否 | 回调函数,返回网络共享状态。 | | callback | AsyncCallback\<boolean> | 否 | 回调函数,返回网络共享状态。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
**示例:** **示例:**
```js ```js
...@@ -680,6 +892,13 @@ on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIface ...@@ -680,6 +892,13 @@ on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIface
| type | string | 是 | 事件名称。 | | type | string | 是 | 事件名称。 |
| callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | 是 | 回调函数,指定网卡共享状态变化时调用。 | | callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | 是 | 回调函数,指定网卡共享状态变化时调用。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
**示例:** **示例:**
```js ```js
...@@ -708,6 +927,13 @@ off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfa ...@@ -708,6 +927,13 @@ off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfa
| type | string | 是 | 事件名称。 | | type | string | 是 | 事件名称。 |
| callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | 否 | 回调函数,注销指定网卡共享状态变化通知。 | | callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | 否 | 回调函数,注销指定网卡共享状态变化通知。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
**示例:** **示例:**
```js ```js
...@@ -736,6 +962,13 @@ on(type: 'sharingUpstreamChange', callback: Callback\<NetHandle>): void ...@@ -736,6 +962,13 @@ on(type: 'sharingUpstreamChange', callback: Callback\<NetHandle>): void
| type | string | 是 | 事件名称。 | | type | string | 是 | 事件名称。 |
| callback | AsyncCallback\<NetHandle> | 是 | 回调函数,上行网络变化时调用。 | | callback | AsyncCallback\<NetHandle> | 是 | 回调函数,上行网络变化时调用。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
**示例:** **示例:**
```js ```js
...@@ -764,6 +997,13 @@ off(type: 'sharingUpstreamChange', callback?: Callback\<NetHandle>): void ...@@ -764,6 +997,13 @@ off(type: 'sharingUpstreamChange', callback?: Callback\<NetHandle>): void
| type | string | 是 | 事件名称。 | | type | string | 是 | 事件名称。 |
| callback | AsyncCallback\<NetHandle> | 否 | 回调函数,注销上行网络变化事件。 | | callback | AsyncCallback\<NetHandle> | 否 | 回调函数,注销上行网络变化事件。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
**示例:** **示例:**
```js ```js
......
...@@ -667,6 +667,9 @@ Socket的连接信息。 ...@@ -667,6 +667,9 @@ Socket的连接信息。
| port | number | 是 | 端口号,范围0~65535。 | | port | number | 是 | 端口号,范围0~65535。 |
| size | number | 是 | 服务器响应信息的字节长度。 | | size | number | 是 | 服务器响应信息的字节长度。 |
## UDP 错误码说明
UDP 错误码映射形式为:2301000 + 内核错误码。
## socket.constructTCPSocketInstance ## socket.constructTCPSocketInstance
constructTCPSocketInstance\(\): TCPSocket constructTCPSocketInstance\(\): TCPSocket
...@@ -1453,6 +1456,9 @@ TCPSocket连接的其他属性。 ...@@ -1453,6 +1456,9 @@ TCPSocket连接的其他属性。
| reuseAddress | boolean | 否 | 是否重用地址。默认为false。 | | reuseAddress | boolean | 否 | 是否重用地址。默认为false。 |
| socketTimeout | number | 否 | 套接字超时时间,单位毫秒(ms)。 | | socketTimeout | number | 否 | 套接字超时时间,单位毫秒(ms)。 |
## TCP 错误码说明
TCP 错误码映射形式为:2301000 + 内核错误码。
## socket.constructTLSSocketInstance<sup>9+</sup> ## socket.constructTLSSocketInstance<sup>9+</sup>
constructTLSSocketInstance(): TLSSocket constructTLSSocketInstance(): TLSSocket
......
...@@ -104,6 +104,11 @@ connect\(url: string, callback: AsyncCallback<boolean\>\): void ...@@ -104,6 +104,11 @@ connect\(url: string, callback: AsyncCallback<boolean\>\): void
| url | string | 是 | 建立WebSocket连接的URL地址。 | | url | string | 是 | 建立WebSocket连接的URL地址。 |
| callback | AsyncCallback\<boolean\> | 是 | 回调函数。 | | callback | AsyncCallback\<boolean\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|-------|---------------------------|
| 401 | Parameter error. |
**示例:** **示例:**
...@@ -138,6 +143,11 @@ connect\(url: string, options: WebSocketRequestOptions, callback: AsyncCallback< ...@@ -138,6 +143,11 @@ connect\(url: string, options: WebSocketRequestOptions, callback: AsyncCallback<
| options | WebSocketRequestOptions | 是 | 参考[WebSocketRequestOptions](#websocketrequestoptions)。 | | options | WebSocketRequestOptions | 是 | 参考[WebSocketRequestOptions](#websocketrequestoptions)。 |
| callback | AsyncCallback\<boolean\> | 是 | 回调函数。 | | callback | AsyncCallback\<boolean\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|-------|---------------------------|
| 401 | Parameter error. |
**示例:** **示例:**
...@@ -182,6 +192,12 @@ connect\(url: string, options?: WebSocketRequestOptions\): Promise<boolean\> ...@@ -182,6 +192,12 @@ connect\(url: string, options?: WebSocketRequestOptions\): Promise<boolean\>
| :----------------- | :-------------------------------- | | :----------------- | :-------------------------------- |
| Promise\<boolean\> | 以Promise形式返回建立连接的结果。 | | Promise\<boolean\> | 以Promise形式返回建立连接的结果。 |
**错误码:**
| 错误码ID | 错误信息 |
|-------|---------------------------|
| 401 | Parameter error. |
**示例:** **示例:**
```js ```js
...@@ -213,6 +229,12 @@ send\(data: string | ArrayBuffer, callback: AsyncCallback<boolean\>\): void ...@@ -213,6 +229,12 @@ send\(data: string | ArrayBuffer, callback: AsyncCallback<boolean\>\): void
| data | string \| ArrayBuffer <sup>8+</sup> | 是 | 发送的数据。 | | data | string \| ArrayBuffer <sup>8+</sup> | 是 | 发送的数据。 |
| callback | AsyncCallback\<boolean\> | 是 | 回调函数。 | | callback | AsyncCallback\<boolean\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|-------|---------------------------|
| 401 | Parameter error. |
**示例:** **示例:**
```js ```js
...@@ -252,6 +274,12 @@ send\(data: string | ArrayBuffer\): Promise<boolean\> ...@@ -252,6 +274,12 @@ send\(data: string | ArrayBuffer\): Promise<boolean\>
| :----------------- | :-------------------------------- | | :----------------- | :-------------------------------- |
| Promise\<boolean\> | 以Promise形式返回发送数据的结果。 | | Promise\<boolean\> | 以Promise形式返回发送数据的结果。 |
**错误码:**
| 错误码ID | 错误信息 |
|--------|---------------------------|
| 401 | Parameter error. |
**示例:** **示例:**
```js ```js
...@@ -284,6 +312,12 @@ close\(callback: AsyncCallback<boolean\>\): void ...@@ -284,6 +312,12 @@ close\(callback: AsyncCallback<boolean\>\): void
| -------- | ------------------------ | ---- | ---------- | | -------- | ------------------------ | ---- | ---------- |
| callback | AsyncCallback\<boolean\> | 是 | 回调函数。 | | callback | AsyncCallback\<boolean\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|-------|---------------------------|
| 401 | Parameter error. |
**示例:** **示例:**
```js ```js
...@@ -316,6 +350,12 @@ close\(options: WebSocketCloseOptions, callback: AsyncCallback<boolean\>\): void ...@@ -316,6 +350,12 @@ close\(options: WebSocketCloseOptions, callback: AsyncCallback<boolean\>\): void
| options | WebSocketCloseOptions | 是 | 参考[WebSocketCloseOptions](#websocketcloseoptions)。 | | options | WebSocketCloseOptions | 是 | 参考[WebSocketCloseOptions](#websocketcloseoptions)。 |
| callback | AsyncCallback\<boolean\> | 是 | 回调函数。 | | callback | AsyncCallback\<boolean\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|--------|---------------------------|
| 401 | Parameter error. |
**示例:** **示例:**
```js ```js
...@@ -356,6 +396,12 @@ close\(options?: WebSocketCloseOptions\): Promise<boolean\> ...@@ -356,6 +396,12 @@ close\(options?: WebSocketCloseOptions\): Promise<boolean\>
| :----------------- | :-------------------------------- | | :----------------- | :-------------------------------- |
| Promise\<boolean\> | 以Promise形式返回关闭连接的结果。 | | Promise\<boolean\> | 以Promise形式返回关闭连接的结果。 |
**错误码:**
| 错误码ID | 错误信息 |
|--------|---------------------------|
| 401 | Parameter error. |
**示例:** **示例:**
```js ```js
...@@ -388,6 +434,11 @@ on\(type: 'open', callback: AsyncCallback<Object\>\): void ...@@ -388,6 +434,11 @@ on\(type: 'open', callback: AsyncCallback<Object\>\): void
| type | string | 是 | 'open':WebSocket的打开事件。 | | type | string | 是 | 'open':WebSocket的打开事件。 |
| callback | AsyncCallback\<Object\> | 是 | 回调函数。 | | callback | AsyncCallback\<Object\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|-------|---------------------------|
| 401 | Parameter error. |
**示例:** **示例:**
...@@ -417,6 +468,12 @@ off\(type: 'open', callback?: AsyncCallback<Object\>\): void ...@@ -417,6 +468,12 @@ off\(type: 'open', callback?: AsyncCallback<Object\>\): void
| type | string | 是 | 'open':WebSocket的打开事件。 | | type | string | 是 | 'open':WebSocket的打开事件。 |
| callback | AsyncCallback\<Object\> | 否 | 回调函数。 | | callback | AsyncCallback\<Object\> | 否 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|-------|---------------------------|
| 401 | Parameter error. |
**示例:** **示例:**
```js ```js
...@@ -448,6 +505,11 @@ on\(type: 'message', callback: AsyncCallback<string | ArrayBuffer\>\): void ...@@ -448,6 +505,11 @@ on\(type: 'message', callback: AsyncCallback<string | ArrayBuffer\>\): void
| type | string | 是 | 'message':WebSocket的接收到服务器消息事件。 | | type | string | 是 | 'message':WebSocket的接收到服务器消息事件。 |
| callback | AsyncCallback\<string \| ArrayBuffer <sup>8+</sup>\> | 是 | 回调函数。 | | callback | AsyncCallback\<string \| ArrayBuffer <sup>8+</sup>\> | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|--------|---------------------------|
| 401 | Parameter error. |
**示例:** **示例:**
...@@ -478,6 +540,12 @@ off\(type: 'message', callback?: AsyncCallback<string | ArrayBuffer\>\): void ...@@ -478,6 +540,12 @@ off\(type: 'message', callback?: AsyncCallback<string | ArrayBuffer\>\): void
| type | string | 是 | 'message':WebSocket的接收到服务器消息事件。 | | type | string | 是 | 'message':WebSocket的接收到服务器消息事件。 |
| callback | AsyncCallback\<string \|ArrayBuffer <sup>8+</sup>\> | 否 | 回调函数。 | | callback | AsyncCallback\<string \|ArrayBuffer <sup>8+</sup>\> | 否 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|-------|---------------------------|
| 401 | Parameter error. |
**示例:** **示例:**
```js ```js
...@@ -529,6 +597,11 @@ off\(type: 'close', callback?: AsyncCallback<\{ code: number, reason: string \}\ ...@@ -529,6 +597,11 @@ off\(type: 'close', callback?: AsyncCallback<\{ code: number, reason: string \}\
| type | string | 是 | 'close':WebSocket的关闭事件。 | | type | string | 是 | 'close':WebSocket的关闭事件。 |
| callback | AsyncCallback<{ code: number, reason: string }> | 否 | 回调函数。 | | callback | AsyncCallback<{ code: number, reason: string }> | 否 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|-------|---------------------------|
| 401 | Parameter error. |
**示例:** **示例:**
...@@ -553,6 +626,11 @@ on\(type: 'error', callback: ErrorCallback\): void ...@@ -553,6 +626,11 @@ on\(type: 'error', callback: ErrorCallback\): void
| type | string | 是 | 'error':WebSocket的Error事件。 | | type | string | 是 | 'error':WebSocket的Error事件。 |
| callback | ErrorCallback | 是 | 回调函数。 | | callback | ErrorCallback | 是 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|-------|---------------------------|
| 401 | Parameter error. |
**示例:** **示例:**
...@@ -582,6 +660,12 @@ off\(type: 'error', callback?: ErrorCallback\): void ...@@ -582,6 +660,12 @@ off\(type: 'error', callback?: ErrorCallback\): void
| type | string | 是 | 'error':WebSocket的Error事件。 | | type | string | 是 | 'error':WebSocket的Error事件。 |
| callback | ErrorCallback | 否 | 回调函数。 | | callback | ErrorCallback | 否 | 回调函数。 |
**错误码:**
| 错误码ID | 错误信息 |
|--------|---------------------------|
| 401 | Parameter error. |
**示例:** **示例:**
```js ```js
......
...@@ -47,6 +47,8 @@ ...@@ -47,6 +47,8 @@
- [文件管理子系统错误码](errorcode-filemanagement.md) - [文件管理子系统错误码](errorcode-filemanagement.md)
- 网络管理 - 网络管理
- [上传下载错误码](errorcode-request.md) - [上传下载错误码](errorcode-request.md)
- [HTTP错误码](errorcode-http.md)
- [Socket错误码](errorcode-socket.md)
- 通信与连接 - 通信与连接
- [NFC错误码](errorcode-nfc.md) - [NFC错误码](errorcode-nfc.md)
- [RPC错误码](errorcode-rpc.md) - [RPC错误码](errorcode-rpc.md)
......
# HTTP错误码
## 2300001 不支持的协议
**错误信息**
Unsupported protocol.
**错误描述**
协议版本服务器不支持。
**可能原因**
传入的协议版本,服务器不支持。
**处理步骤**
请检查传入的协议版本是否合理,排查服务器实现。
## 2300003 URL格式错误
**错误信息**
URL using bad/illegal format or missing URL.
**错误描述**
URL格式错误。
**可能原因**
可能传入的url格式不正确。
**处理步骤**
检查传入的url格式是否正确。
## 2300005 代理服务器域名解析失败
**错误信息**
Couldn't resolve proxy name.
**错误描述**
代理服务器的域名无法解析。
**可能原因**
服务器的URL不正确
**处理步骤**
排查代理服务器的URL是否正确。
## 2300006 域名解析失败
**错误信息**
Couldn't resolve host name.
**错误描述**
服务器的域名无法解析。
**可能原因**
传入的服务器的URL不正确。
**处理步骤**
请检查入的服务器的URL是否合理。
## 2300007 无法连接到服务器
**错误信息**
Couldn't connect to server.
**错误描述**
服务器无法连接。
**可能原因**
可能传入的url格式不正确。
**处理步骤**
检查传入的url格式是否正确。
## 2300008 服务器返回非法数据
**错误信息**
Weird server reply.
**错误描述**
服务器返回非法数据。
**可能原因**
服务器出错,返回了非HTTP格式的数据。
**处理步骤**
排查服务器实现。
## 2300009 拒绝对远程资源的访问
**错误信息**
Access denied to remote resource.
**错误描述**
拒绝对远程资源的访问。
**可能原因**
指定的内容被服务器拒绝访问。
**处理步骤**
排查请求内容。
## 2300016 HTT2帧层错误
**错误信息**
Error in the HTTP2 framing layer.
**错误描述**
HTTP2层级的错误。
**可能原因**
服务器不支持HTTP2。
**处理步骤**
抓包分析、排查服务器是否支持HTTP2。
## 2300018 服务器返回数据不完整
**错误信息**
Transferred a partial file.
**错误描述**
服务器返回的数据不完整。
**可能原因**
可能与服务器实现有关
**处理步骤**
排查服务器实现。
## 2300023 向磁盘/应用程序写入接收数据失败
**错误信息**
Failed writing received data to disk/application.
**错误描述**
向磁盘/应用程序写入接收数据失败。
**可能原因**
应用没有写文件权限。
**处理步骤**
排查应用权限。
## 2300025 上传失败
**错误信息**
Upload failed.
**错误描述**
上传失败。
**可能原因**
文件过大或者网络问题。对于FTP,服务器通常会拒绝STOR命令。错误缓冲区通常包含服务器的解释。
**处理步骤**
排查文件大小及网络状况。
## 2300026 从文件/应用程序中打开/读取本地数据失败
**错误信息**
Failed to open/read local data from file/application.
**错误描述**
从文件/应用程序中打开/读取本地数据失败。
**可能原因**
应用没有读文件权限
**处理步骤**
排查应用权限。
## 2300027 内存不足
**错误信息**
Out of memory.
**错误描述**
内存不足。
**可能原因**
内存不足。
**处理步骤**
排查系统内存。
## 2300028 操作超时
**错误信息**
Timeout was reached.
**错误描述**
操作超时。
**可能原因**
TCP连接超时或读写超时。
**处理步骤**
排查网络问题。
## 2300047 重定向次数达到最大值
**错误信息**
Number of redirects hit maximum amount.
**错误描述**
重定向次数达到最大值。
**可能原因**
重定向次数过多
**处理步骤**
排查服务器实现。
## 2300052 服务器没有返回内容
**错误信息**
Server returned nothing (no headers, no data).
**错误描述**
服务器没有返回内容。
**可能原因**
可能与服务器实现有关。
**处理步骤**
排查服务器实现。
## 2300055 发送网络数据失败
**错误信息**
Failed sending data to the peer.
**错误描述**
无法往对端发送数据,发送网络数据失败。
**可能原因**
网络问题。
**处理步骤**
排查网络。
## 2300056 接收网络数据失败
**错误信息**
Failure when receiving data from the peer.
**错误描述**
无法往从对端收到数据,接收网络数据失败。
**可能原因**
网络问题
**处理步骤**
排查网络问题。
## 2300058 本地SSL证书错误
**错误信息**
Problem with the local SSL certificate.
**错误描述**
本地SSL证书错误。
**可能原因**
SSL证书格式有错误。
**处理步骤**
检查SSL证书格式。
## 2300059 无法使用指定的密码
**错误信息**
Couldn't use specified SSL cipher.
**错误描述**
无法使用指定的密码。
**可能原因**
client和sever协商的加密算法系统不支持。
**处理步骤**
抓包分析协商的算法。
## 2300060 远程服务器SSL证书或SSH秘钥不正确
**错误信息**
SSL peer certificate or SSH remote key was not OK.
**错误描述**
远程服务器SSL证书或SSH秘钥不正确。
**可能原因**
无法校验服务器身份,有可能是证书过期了
**处理步骤**
检查证书有效性。
## 2300061 无法识别或错误的HTTP编码格式
**错误信息**
Unrecognized or bad HTTP Content or Transfer-Encoding.
**错误描述**
无法识别或错误的HTTP编码格式。
**可能原因**
HTTP编码格式不正确。
**处理步骤**
排查服务器实现,目前仅支持gzip编码。
## 2300063 超出最大文件大小
**错误信息**
Maximum file size exceeded.
**错误描述**
超出最大文件大小。
**可能原因**
下载的文件过大。
**处理步骤**
排查服务器实现。
## 2300070 服务器磁盘空间不足
**错误信息**
Remote disk full or allocation exceeded.
**错误描述**
服务器磁盘空间不足。
**可能原因**
服务器磁盘已满
**处理步骤**
检查服务器磁盘空间。
## 2300073 服务器返回文件已存在
**错误信息**
Remote file already exists.
**错误描述**
服务器返回文件已存在。
**可能原因**
上传文件的时候,服务器返回文件已经存在。
**处理步骤**
排查服务器。
## 2300077 SSL CA证书不存在或没有访问权限
**错误信息**
Problem with the SSL CA cert (path? access rights?).
**错误描述**
SSL CA证书不存在或没有访问权限。
**可能原因**
证书不存在或者没有访问权限。
**处理步骤**
检查证书是否存在或者有没有访问权限。
## 2300078 URL请求的文件不存在
**错误信息**
Remote file not found.
**错误描述**
URL请求的文件不存在。
**可能原因**
URL请求的文件不存在
**处理步骤**
检查URL请求的文件是否存在。
## 2300094 身份校验失败
**错误信息**
An authentication function returned an error.
**错误描述**
身份校验失败。
**可能原因**
传入的校验身份的字段与服务器不匹配。
**处理步骤**
排查传入的校验身份的字段是否与服务器匹配。
## 2300999 未知错误
**错误信息**
Unknown Other Error.
**错误描述**
未知错误。
**可能原因**
未知错误。
**处理步骤**
未知错误。
# TCP/UDP 错误码
## 2301001 操作不允许
**错误信息**
Operation not permitted.
**错误描述**
操作不允许。
**可能原因**
非法操作。
**处理步骤**
检查操作步骤。
## 2301002 文件不存在
**错误信息**
No such file or directory.
**错误描述**
文件不存在。
**可能原因**
文件不存在。
**处理步骤**
检查文件名或文件路径。
## 2301003 进程不存在
**错误信息**
No such process.
**错误描述**
进程不存在。
**可能原因**
进程不存在
**处理步骤**
排查进程信息。
## 2300004 Interrupted system call
**错误信息**
Couldn't resolve host name.
**错误描述**
系统调用中断。
**可能原因**
系统调用中断。
**处理步骤**
排查系统调用。
**TCP/UDP 错误码说明:**
> 其余错误码映射形式为:2301000 + 内核错误码,关键信息请参考内核错误码。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册