提交 3cbd24d2 编写于 作者: Y Yangys

Update ErrorCode

Signed-off-by: NYangys <yangyousheng@huawei.com>
上级 4e104f11
# @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
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册