js-apis-socket.md 98.5 KB
Newer Older
S
shawn_he 已提交
1
# # @ohos.net.socket (Socket Connection) 
S
shawn_he 已提交
2

S
shawn_he 已提交
3 4
The **socket** module implements data transfer over TCPSocket, UDPSocket, WebSocket, and TLSSocket connections.

S
shawn_he 已提交
5 6
> **NOTE**
>
S
shawn_he 已提交
7
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
S
shawn_he 已提交
8 9 10

## Modules to Import

S
shawn_he 已提交
11
```js
S
shawn_he 已提交
12 13 14
import socket from '@ohos.net.socket';
```

S
shawn_he 已提交
15
## socket.constructUDPSocketInstance<sup>7+</sup>
S
shawn_he 已提交
16

S
shawn_he 已提交
17
constructUDPSocketInstance(): UDPSocket
S
shawn_he 已提交
18 19 20 21 22

Creates a **UDPSocket** object.

**System capability**: SystemCapability.Communication.NetStack

S
shawn_he 已提交
23
**Return value**
S
shawn_he 已提交
24 25

| Type                              | Description                   |
S
shawn_he 已提交
26
| :--------------------------------- | :---------------------- |
S
shawn_he 已提交
27 28 29 30
| [UDPSocket](#udpsocket) | **UDPSocket** object.|

**Example**

S
shawn_he 已提交
31
```js
S
shawn_he 已提交
32 33 34
let udp = socket.constructUDPSocketInstance();
```

S
shawn_he 已提交
35
## UDPSocket<sup>7+</sup>
S
shawn_he 已提交
36 37 38

Defines a **UDPSocket** connection. Before invoking UDPSocket APIs, you need to call [socket.constructUDPSocketInstance](#socketconstructudpsocketinstance) to create a **UDPSocket** object.

S
shawn_he 已提交
39
### bind<sup>7+</sup>
S
shawn_he 已提交
40

S
shawn_he 已提交
41
bind(address: NetAddress, callback: AsyncCallback\<void\>): void
S
shawn_he 已提交
42 43 44

Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result.

S
shawn_he 已提交
45
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
46 47 48 49 50 51 52 53 54 55

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                              | Mandatory| Description                                                  |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address  | [NetAddress](#netaddress) | Yes  | Destination address. For details, see [NetAddress](#netaddress).|
| callback | AsyncCallback\<void\>              | Yes  | Callback used to return the result.                                            |

S
shawn_he 已提交
56 57 58 59 60 61 62
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 401     | Parameter error.        |
| 201     | Permission denied.      |

S
shawn_he 已提交
63 64
**Example**

S
shawn_he 已提交
65
```js
S
shawn_he 已提交
66
let udp = socket.constructUDPSocketInstance();
S
shawn_he 已提交
67
udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
S
shawn_he 已提交
68
  if (err) {
S
shawn_he 已提交
69 70
    console.log('bind fail');
    return;
S
shawn_he 已提交
71 72 73 74 75
  }
  console.log('bind success');
})
```

S
shawn_he 已提交
76
### bind<sup>7+</sup>
S
shawn_he 已提交
77

S
shawn_he 已提交
78
bind(address: NetAddress): Promise\<void\>
S
shawn_he 已提交
79 80 81

Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result.

S
shawn_he 已提交
82
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
83 84 85 86 87 88 89 90 91

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name | Type                              | Mandatory| Description                                                  |
| ------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | Yes  | Destination address. For details, see [NetAddress](#netaddress).|

S
shawn_he 已提交
92 93 94 95 96 97
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 401     | Parameter error.        |
| 201     | Permission denied.      |
S
shawn_he 已提交
98

S
shawn_he 已提交
99
**Return value**
S
shawn_he 已提交
100 101

| Type           | Description                                      |
S
shawn_he 已提交
102
| :-------------- | :----------------------------------------- |
S
shawn_he 已提交
103 104 105 106
| Promise\<void\> | Promise used to return the result.|

**Example**

S
shawn_he 已提交
107
```js
S
shawn_he 已提交
108
let udp = socket.constructUDPSocketInstance();
S
shawn_he 已提交
109
let promise = udp.bind({ address: '192.168.xx.xxx', port: 8080, family: 1 });
S
shawn_he 已提交
110
promise.then(() => {
S
shawn_he 已提交
111 112 113 114 115 116
  console.log('bind success');
}).catch(err => {
  console.log('bind fail');
});
```

S
shawn_he 已提交
117
### send<sup>7+</sup>
S
shawn_he 已提交
118

S
shawn_he 已提交
119
send(options: UDPSendOptions, callback: AsyncCallback\<void\>): void
S
shawn_he 已提交
120 121 122

Sends data over a UDPSocket connection. This API uses an asynchronous callback to return the result.

S
shawn_he 已提交
123 124
Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and port.

S
shawn_he 已提交
125
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
126 127 128 129 130 131 132 133 134 135

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                    | Mandatory| Description                                                        |
| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options  | [UDPSendOptions](#udpsendoptions) | Yes  | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).|
| callback | AsyncCallback\<void\>                    | Yes  | Callback used to return the result.                                                  |

S
shawn_he 已提交
136 137 138 139 140 141 142
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 401     | Parameter error.        |
| 201     | Permission denied.      |

S
shawn_he 已提交
143 144
**Example**

S
shawn_he 已提交
145
```js
S
shawn_he 已提交
146 147
let udp = socket.constructUDPSocketInstance();
udp.send({
S
shawn_he 已提交
148
  data: 'Hello, server!',
S
shawn_he 已提交
149
  address: {
S
shawn_he 已提交
150 151 152
    address: '192.168.xx.xxx',
    port: xxxx,
    family: 1
S
shawn_he 已提交
153
  }
S
shawn_he 已提交
154 155 156 157 158 159
}, err => {
  if (err) {
    console.log('send fail');
    return;
  }
  console.log('send success');
S
shawn_he 已提交
160 161 162
})
```

S
shawn_he 已提交
163
### send<sup>7+</sup>
S
shawn_he 已提交
164

S
shawn_he 已提交
165
send(options: UDPSendOptions): Promise\<void\>
S
shawn_he 已提交
166 167 168

Sends data over a UDPSocket connection. This API uses a promise to return the result.

S
shawn_he 已提交
169 170
Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and port.

S
shawn_he 已提交
171
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
172 173 174 175 176 177 178 179 180

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name | Type                                    | Mandatory| Description                                                        |
| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [UDPSendOptions](#udpsendoptions) | Yes  | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).|

S
shawn_he 已提交
181 182 183 184 185 186 187
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 401     | Parameter error.        |
| 201     | Permission denied.      |

S
shawn_he 已提交
188
**Return value**
S
shawn_he 已提交
189 190

| Type           | Description                                          |
S
shawn_he 已提交
191
| :-------------- | :--------------------------------------------- |
S
shawn_he 已提交
192 193 194 195
| Promise\<void\> | Promise used to return the result.|

**Example**

S
shawn_he 已提交
196
```js
S
shawn_he 已提交
197 198
let udp = socket.constructUDPSocketInstance();
let promise = udp.send({
S
shawn_he 已提交
199
  data: 'Hello, server!',
S
shawn_he 已提交
200
  address: {
S
shawn_he 已提交
201 202 203
    address: '192.168.xx.xxx',
    port: xxxx,
    family: 1
S
shawn_he 已提交
204 205 206 207 208 209 210 211 212
  }
});
promise.then(() => {
  console.log('send success');
}).catch(err => {
  console.log('send fail');
});
```

S
shawn_he 已提交
213
### close<sup>7+</sup>
S
shawn_he 已提交
214

S
shawn_he 已提交
215
close(callback: AsyncCallback\<void\>): void
S
shawn_he 已提交
216 217 218

Closes a UDPSocket connection. This API uses an asynchronous callback to return the result.

S
shawn_he 已提交
219
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
220 221 222 223 224 225 226 227 228 229 230

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                 | Mandatory| Description      |
| -------- | --------------------- | ---- | ---------- |
| callback | AsyncCallback\<void\> | Yes  | Callback used to return the result.|

**Example**

S
shawn_he 已提交
231
```js
S
shawn_he 已提交
232 233 234
let udp = socket.constructUDPSocketInstance();
udp.close(err => {
  if (err) {
S
shawn_he 已提交
235 236
    console.log('close fail');
    return;
S
shawn_he 已提交
237 238 239 240 241
  }
  console.log('close success');
})
```

S
shawn_he 已提交
242
### close<sup>7+</sup>
S
shawn_he 已提交
243

S
shawn_he 已提交
244
close(): Promise\<void\>
S
shawn_he 已提交
245 246 247

Closes a UDPSocket connection. This API uses a promise to return the result.

S
shawn_he 已提交
248
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
249 250 251

**System capability**: SystemCapability.Communication.NetStack

S
shawn_he 已提交
252
**Return value**
S
shawn_he 已提交
253 254

| Type           | Description                                      |
S
shawn_he 已提交
255
| :-------------- | :----------------------------------------- |
S
shawn_he 已提交
256 257 258 259
| Promise\<void\> | Promise used to return the result.|

**Example**

S
shawn_he 已提交
260
```js
S
shawn_he 已提交
261 262 263 264 265 266 267 268 269
let udp = socket.constructUDPSocketInstance();
let promise = udp.close();
promise.then(() => {
  console.log('close success');
}).catch(err => {
  console.log('close fail');
});
```

S
shawn_he 已提交
270
### getState<sup>7+</sup>
S
shawn_he 已提交
271

S
shawn_he 已提交
272
getState(callback: AsyncCallback\<SocketStateBase\>): void
S
shawn_he 已提交
273 274 275

Obtains the status of the UDPSocket connection. This API uses an asynchronous callback to return the result.

S
shawn_he 已提交
276 277
> **NOTE**
> This API can be called only after **bind** is successfully called.
S
shawn_he 已提交
278

S
shawn_he 已提交
279
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
280 281 282 283 284 285 286 287 288

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                                  | Mandatory| Description      |
| -------- | ------------------------------------------------------ | ---- | ---------- |
| callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | Yes  | Callback used to return the result.|

S
shawn_he 已提交
289 290 291 292 293 294
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 201     | Permission denied.      |

S
shawn_he 已提交
295 296
**Example**

S
shawn_he 已提交
297
```js
S
shawn_he 已提交
298 299 300
let udp = socket.constructUDPSocketInstance();
udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
  if (err) {
S
shawn_he 已提交
301 302
    console.log('bind fail');
    return;
S
shawn_he 已提交
303 304 305
  }
  console.log('bind success');
  udp.getState((err, data) => {
S
shawn_he 已提交
306 307 308 309 310
    if (err) {
      console.log('getState fail');
      return;
    }
    console.log('getState success:' + JSON.stringify(data));
S
shawn_he 已提交
311 312 313 314
  })
})
```

S
shawn_he 已提交
315
### getState<sup>7+</sup>
S
shawn_he 已提交
316

S
shawn_he 已提交
317
getState(): Promise\<SocketStateBase\>
S
shawn_he 已提交
318 319 320

Obtains the status of the UDPSocket connection. This API uses a promise to return the result.

S
shawn_he 已提交
321 322
> **NOTE**
> This API can be called only after **bind** is successfully called.
S
shawn_he 已提交
323

S
shawn_he 已提交
324
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
325 326 327

**System capability**: SystemCapability.Communication.NetStack

S
shawn_he 已提交
328
**Return value**
S
shawn_he 已提交
329 330

| Type                                            | Description                                      |
S
shawn_he 已提交
331
| :----------------------------------------------- | :----------------------------------------- |
S
shawn_he 已提交
332
| Promise\<[SocketStateBase](#socketstatebase)\> | Promise used to return the result.|
S
shawn_he 已提交
333 334 335

**Example**

S
shawn_he 已提交
336
```js
S
shawn_he 已提交
337
let udp = socket.constructUDPSocketInstance();
S
shawn_he 已提交
338
let promise = udp.bind({ address: '192.168.xx.xxx', port: xxxx, family: 1 });
S
shawn_he 已提交
339
promise.then(err => {
S
shawn_he 已提交
340
  if (err) {
S
shawn_he 已提交
341 342
    console.log('bind fail');
    return;
S
shawn_he 已提交
343 344
  }
  console.log('bind success');
S
shawn_he 已提交
345
  let promise = udp.getState();
S
shawn_he 已提交
346
  promise.then(data => {
S
shawn_he 已提交
347
    console.log('getState success:' + JSON.stringify(data));
S
shawn_he 已提交
348
  }).catch(err => {
S
shawn_he 已提交
349
    console.log('getState fail');
S
shawn_he 已提交
350
  });
S
shawn_he 已提交
351
});
S
shawn_he 已提交
352 353
```

S
shawn_he 已提交
354
### setExtraOptions<sup>7+</sup>
S
shawn_he 已提交
355

S
shawn_he 已提交
356
setExtraOptions(options: UDPExtraOptions, callback: AsyncCallback\<void\>): void
S
shawn_he 已提交
357

S
shawn_he 已提交
358
Sets other attributes of the UDPSocket connection. This API uses an asynchronous callback to return the result.
S
shawn_he 已提交
359

S
shawn_he 已提交
360 361
> **NOTE**
> This API can be called only after **bind** is successfully called.
S
shawn_he 已提交
362

S
shawn_he 已提交
363
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
364 365 366 367 368 369 370 371 372 373

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                    | Mandatory| Description                                                        |
| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options  | [UDPExtraOptions](#udpextraoptions) | Yes  | Other properties of the UDPSocket connection. For details, see [UDPExtraOptions](#udpextraoptions).|
| callback | AsyncCallback\<void\>                    | Yes  | Callback used to return the result.                                                  |

S
shawn_he 已提交
374 375 376 377 378 379
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 401     | Parameter error.        |
| 201     | Permission denied.      |
S
shawn_he 已提交
380 381 382

**Example**

S
shawn_he 已提交
383
```js
S
shawn_he 已提交
384
let udp = socket.constructUDPSocketInstance();
S
shawn_he 已提交
385
udp.bind({ address: '192.168.xx.xxx', port: xxxx, family: 1 }, err => {
S
shawn_he 已提交
386
  if (err) {
S
shawn_he 已提交
387 388
    console.log('bind fail');
    return;
S
shawn_he 已提交
389 390 391
  }
  console.log('bind success');
  udp.setExtraOptions({
S
shawn_he 已提交
392 393 394 395 396 397 398 399 400 401 402
    receiveBufferSize: 1000,
    sendBufferSize: 1000,
    reuseAddress: false,
    socketTimeout: 6000,
    broadcast: true
  }, err => {
    if (err) {
      console.log('setExtraOptions fail');
      return;
    }
    console.log('setExtraOptions success');
S
shawn_he 已提交
403 404 405 406
  })
})
```

S
shawn_he 已提交
407
### setExtraOptions<sup>7+</sup>
S
shawn_he 已提交
408

S
shawn_he 已提交
409
setExtraOptions(options: UDPExtraOptions): Promise\<void\>
S
shawn_he 已提交
410

S
shawn_he 已提交
411
Sets other attributes of the UDPSocket connection. This API uses a promise to return the result.
S
shawn_he 已提交
412

S
shawn_he 已提交
413 414
> **NOTE**
> This API can be called only after **bind** is successfully called.
S
shawn_he 已提交
415

S
shawn_he 已提交
416
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
417 418 419 420 421 422 423 424 425

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name | Type                                    | Mandatory| Description                                                        |
| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [UDPExtraOptions](#udpextraoptions) | Yes  | Other properties of the UDPSocket connection. For details, see [UDPExtraOptions](#udpextraoptions).|

S
shawn_he 已提交
426
**Return value**
S
shawn_he 已提交
427 428

| Type           | Description                                                |
S
shawn_he 已提交
429
| :-------------- | :--------------------------------------------------- |
S
shawn_he 已提交
430 431
| Promise\<void\> | Promise used to return the result.|

S
shawn_he 已提交
432 433 434 435 436 437 438
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 401     | Parameter error.        |
| 201     | Permission denied.      |

S
shawn_he 已提交
439 440
**Example**

S
shawn_he 已提交
441
```js
S
shawn_he 已提交
442
let udp = socket.constructUDPSocketInstance();
S
shawn_he 已提交
443
let promise = udp.bind({ address: '192.168.xx.xxx', port: xxxx, family: 1 });
S
shawn_he 已提交
444 445 446
promise.then(() => {
  console.log('bind success');
  let promise1 = udp.setExtraOptions({
S
shawn_he 已提交
447 448 449 450 451
    receiveBufferSize: 1000,
    sendBufferSize: 1000,
    reuseAddress: false,
    socketTimeout: 6000,
    broadcast: true
S
shawn_he 已提交
452 453
  });
  promise1.then(() => {
S
shawn_he 已提交
454
    console.log('setExtraOptions success');
S
shawn_he 已提交
455
  }).catch(err => {
S
shawn_he 已提交
456
    console.log('setExtraOptions fail');
S
shawn_he 已提交
457 458 459 460 461 462
  });
}).catch(err => {
  console.log('bind fail');
});
```

S
shawn_he 已提交
463
### on('message')<sup>7+</sup>
S
shawn_he 已提交
464

S
shawn_he 已提交
465
on(type: 'message', callback: Callback\<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void
S
shawn_he 已提交
466 467 468 469 470 471 472 473 474

Enables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                                        | Mandatory| Description                                     |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
S
shawn_he 已提交
475
| type     | string                                                       | Yes  | Type of the event to subscribe to.<br /> **message**: message receiving event|
S
shawn_he 已提交
476
| callback | Callback\<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}\> | Yes  | Callback used to return the result.                               |
S
shawn_he 已提交
477 478 479

**Example**

S
shawn_he 已提交
480
```js
S
shawn_he 已提交
481
let udp = socket.constructUDPSocketInstance();
S
shawn_he 已提交
482
let messageView = '';
S
shawn_he 已提交
483
udp.on('message', value => {
S
shawn_he 已提交
484 485 486
  for (var i = 0; i < value.message.length; i++) {
    let messages = value.message[i]
    let message = String.fromCharCode(messages);
S
shawn_he 已提交
487
    messageView += message;
S
shawn_he 已提交
488 489 490
  }
  console.log('on message message: ' + JSON.stringify(messageView));
  console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo));
S
shawn_he 已提交
491 492 493
});
```

S
shawn_he 已提交
494
### off('message')<sup>7+</sup>
S
shawn_he 已提交
495

S
shawn_he 已提交
496
off(type: 'message', callback?: Callback\<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void
S
shawn_he 已提交
497 498 499

Disables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result.

S
shawn_he 已提交
500 501
> **NOTE**
> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
S
shawn_he 已提交
502 503 504 505 506 507 508

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                                        | Mandatory| Description                                     |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
S
shawn_he 已提交
509
| type     | string                                                       | Yes  | Type of the event to subscribe to.<br /> **message**: message receiving event|
S
shawn_he 已提交
510 511 512 513
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No  | Callback used to return the result.                               |

**Example**

S
shawn_he 已提交
514
```js
S
shawn_he 已提交
515
let udp = socket.constructUDPSocketInstance();
S
shawn_he 已提交
516
let messageView = '';
S
shawn_he 已提交
517
let callback = value => {
S
shawn_he 已提交
518 519 520
  for (var i = 0; i < value.message.length; i++) {
    let messages = value.message[i]
    let message = String.fromCharCode(messages);
S
shawn_he 已提交
521
    messageView += message;
S
shawn_he 已提交
522 523 524
  }
  console.log('on message message: ' + JSON.stringify(messageView));
  console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo));
S
shawn_he 已提交
525 526
}
udp.on('message', callback);
S
shawn_he 已提交
527
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
S
shawn_he 已提交
528 529 530 531
udp.off('message', callback);
udp.off('message');
```

S
shawn_he 已提交
532
### on('listening' | 'close')<sup>7+</sup>
S
shawn_he 已提交
533

S
shawn_he 已提交
534
on(type: 'listening' | 'close', callback: Callback\<void\>): void
S
shawn_he 已提交
535 536 537 538 539 540 541 542 543

Enables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type            | Mandatory| Description                                                        |
| -------- | ---------------- | ---- | ------------------------------------------------------------ |
S
shawn_he 已提交
544
| type     | string           | Yes  | Type of the event to subscribe to.<br /><br>- **listening**: data packet message event<br>- **close**: close event|
S
shawn_he 已提交
545 546 547 548
| callback | Callback\<void\> | Yes  | Callback used to return the result.                                                  |

**Example**

S
shawn_he 已提交
549
```js
S
shawn_he 已提交
550 551
let udp = socket.constructUDPSocketInstance();
udp.on('listening', () => {
S
shawn_he 已提交
552
  console.log("on listening success");
S
shawn_he 已提交
553 554
});
udp.on('close', () => {
S
shawn_he 已提交
555
  console.log("on close success");
S
shawn_he 已提交
556 557 558
});
```

S
shawn_he 已提交
559
### off('listening' | 'close')<sup>7+</sup>
S
shawn_he 已提交
560

S
shawn_he 已提交
561
off(type: 'listening' | 'close', callback?: Callback\<void\>): void
S
shawn_he 已提交
562 563 564

Disables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result.

S
shawn_he 已提交
565 566
> **NOTE**
> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
S
shawn_he 已提交
567 568 569 570 571 572 573

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type            | Mandatory| Description                                                        |
| -------- | ---------------- | ---- | ------------------------------------------------------------ |
S
shawn_he 已提交
574
| type     | string           | Yes  | Type of the event to subscribe to.<br>- **listening**: data packet message event<br>- **close**: close event|
S
shawn_he 已提交
575 576 577 578
| callback | Callback\<void\> | No  | Callback used to return the result.                                                  |

**Example**

S
shawn_he 已提交
579
```js
S
shawn_he 已提交
580
let udp = socket.constructUDPSocketInstance();
S
shawn_he 已提交
581 582
let callback1 = () => {
  console.log("on listening, success");
S
shawn_he 已提交
583 584
}
udp.on('listening', callback1);
S
shawn_he 已提交
585
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
S
shawn_he 已提交
586 587
udp.off('listening', callback1);
udp.off('listening');
S
shawn_he 已提交
588 589
let callback2 = () => {
  console.log("on close, success");
S
shawn_he 已提交
590 591
}
udp.on('close', callback2);
S
shawn_he 已提交
592
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
S
shawn_he 已提交
593 594 595 596
udp.off('close', callback2);
udp.off('close');
```

S
shawn_he 已提交
597
### on('error')<sup>7+</sup>
S
shawn_he 已提交
598

S
shawn_he 已提交
599
on(type: 'error', callback: ErrorCallback): void
S
shawn_he 已提交
600 601 602 603 604 605 606 607 608

Enables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type         | Mandatory| Description                                |
| -------- | ------------- | ---- | ------------------------------------ |
S
shawn_he 已提交
609
| type     | string        | Yes  | Type of the event to subscribe to.<br /> **error**: error event|
S
shawn_he 已提交
610 611 612 613
| callback | ErrorCallback | Yes  | Callback used to return the result.                          |

**Example**

S
shawn_he 已提交
614
```js
Z
zengyawen 已提交
615
let udp = socket.constructUDPSocketInstance();
S
shawn_he 已提交
616
udp.on('error', err => {
S
shawn_he 已提交
617
  console.log("on error, err:" + JSON.stringify(err))
S
shawn_he 已提交
618 619 620
});
```

S
shawn_he 已提交
621
### off('error')<sup>7+</sup>
S
shawn_he 已提交
622

S
shawn_he 已提交
623
off(type: 'error', callback?: ErrorCallback): void
S
shawn_he 已提交
624 625 626

Disables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result.

S
shawn_he 已提交
627 628
> **NOTE**
> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
S
shawn_he 已提交
629 630 631 632 633 634 635

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type         | Mandatory| Description                                |
| -------- | ------------- | ---- | ------------------------------------ |
S
shawn_he 已提交
636
| type     | string        | Yes  | Type of the event to subscribe to.<br /> **error**: error event|
S
shawn_he 已提交
637 638 639 640
| callback | ErrorCallback | No  | Callback used to return the result.                          |

**Example**

S
shawn_he 已提交
641
```js
Z
zengyawen 已提交
642
let udp = socket.constructUDPSocketInstance();
S
shawn_he 已提交
643 644
let callback = err => {
  console.log("on error, err:" + JSON.stringify(err));
S
shawn_he 已提交
645 646
}
udp.on('error', callback);
S
shawn_he 已提交
647
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
S
shawn_he 已提交
648 649 650 651
udp.off('error', callback);
udp.off('error');
```

S
shawn_he 已提交
652
## NetAddress<sup>7+</sup>
S
shawn_he 已提交
653 654 655 656 657 658 659 660 661 662 663

Defines the destination address.

**System capability**: SystemCapability.Communication.NetStack

| Name | Type  | Mandatory| Description                                                        |
| ------- | ------ | ---- | ------------------------------------------------------------ |
| address | string | Yes  | Bound IP address.                                          |
| port    | number | No  | Port number. The value ranges from **0** to **65535**. If this parameter is not specified, the system randomly allocates a port.          |
| family  | number | No  | Network protocol type.<br>- **1**: IPv4<br>- **2**: IPv6<br>The default value is **1**.|

S
shawn_he 已提交
664
## UDPSendOptions<sup>7+</sup>
S
shawn_he 已提交
665 666 667 668 669 670 671

Defines the parameters for sending data over the UDPSocket connection.

**System capability**: SystemCapability.Communication.NetStack

| Name | Type                              | Mandatory| Description          |
| ------- | ---------------------------------- | ---- | -------------- |
S
shawn_he 已提交
672
| data    | string \| ArrayBuffer<sup>7+</sup>                          | Yes  | Data to send.  |
S
shawn_he 已提交
673 674
| address | [NetAddress](#netaddress) | Yes  | Destination address.|

S
shawn_he 已提交
675
## UDPExtraOptions<sup>7+</sup>
S
shawn_he 已提交
676 677 678 679 680 681 682 683

Defines other properties of the UDPSocket connection.

**System capability**: SystemCapability.Communication.NetStack

| Name           | Type   | Mandatory| Description                            |
| ----------------- | ------- | ---- | -------------------------------- |
| broadcast         | boolean | No  | Whether to send broadcast messages. The default value is **false**. |
S
shawn_he 已提交
684 685
| receiveBufferSize | number  | No  | Size of the receive buffer, in bytes. The default value is **0**.  |
| sendBufferSize    | number  | No  | Size of the send buffer, in bytes. The default value is **0**.  |
S
shawn_he 已提交
686
| reuseAddress      | boolean | No  | Whether to reuse addresses. The default value is **false**.     |
S
shawn_he 已提交
687
| socketTimeout     | number  | No  | Timeout duration of the UDPSocket connection, in ms. The default value is **0**.|
S
shawn_he 已提交
688

S
shawn_he 已提交
689
## SocketStateBase<sup>7+</sup>
S
shawn_he 已提交
690

S
shawn_he 已提交
691
Defines the status of the socket connection.
S
shawn_he 已提交
692 693 694 695 696 697 698 699 700

**System capability**: SystemCapability.Communication.NetStack

| Name     | Type   | Mandatory| Description      |
| ----------- | ------- | ---- | ---------- |
| isBound     | boolean | Yes  | Whether the connection is in the bound state.|
| isClose     | boolean | Yes  | Whether the connection is in the closed state.|
| isConnected | boolean | Yes  | Whether the connection is in the connected state.|

S
shawn_he 已提交
701
## SocketRemoteInfo<sup>7+</sup>
S
shawn_he 已提交
702

S
shawn_he 已提交
703
Defines information about the socket connection.
S
shawn_he 已提交
704 705 706 707 708 709 710 711 712 713

**System capability**: SystemCapability.Communication.NetStack

| Name | Type  | Mandatory| Description                                                        |
| ------- | ------ | ---- | ------------------------------------------------------------ |
| address | string | Yes  | Bound IP address.                                          |
| family  | string | Yes  | Network protocol type.<br>- IPv4<br>- IPv6<br>The default value is **IPv4**.|
| port    | number | Yes  | Port number. The value ranges from **0** to **65535**.                                       |
| size    | number | Yes  | Length of the server response message, in bytes.                                  |

S
shawn_he 已提交
714 715 716 717 718 719
## Description of UDP Error Codes

The UDP error code mapping is in the format of 2301000 + Linux kernel error code.

For details about error codes, see [Socket Error Codes](../errorcodes/errorcode-net-socket.md).

S
shawn_he 已提交
720
## socket.constructTCPSocketInstance<sup>7+</sup>
S
shawn_he 已提交
721

S
shawn_he 已提交
722
constructTCPSocketInstance(): TCPSocket
S
shawn_he 已提交
723 724 725 726 727

Creates a **TCPSocket** object.

**System capability**: SystemCapability.Communication.NetStack

S
shawn_he 已提交
728
**Return value**
S
shawn_he 已提交
729

S
shawn_he 已提交
730
| Type                              | Description                   |
S
shawn_he 已提交
731
  | :--------------------------------- | :---------------------- |
S
shawn_he 已提交
732
| [TCPSocket](#tcpsocket) | **TCPSocket** object.|
S
shawn_he 已提交
733 734 735

**Example**

S
shawn_he 已提交
736
```js
S
shawn_he 已提交
737 738 739
let tcp = socket.constructTCPSocketInstance();
```

S
shawn_he 已提交
740
## TCPSocket<sup>7+</sup>
S
shawn_he 已提交
741 742 743

Defines a TCPSocket connection. Before invoking TCPSocket APIs, you need to call [socket.constructTCPSocketInstance](#socketconstructtcpsocketinstance) to create a **TCPSocket** object.

S
shawn_he 已提交
744
### bind<sup>7+</sup>
S
shawn_he 已提交
745

S
shawn_he 已提交
746
bind(address: NetAddress, callback: AsyncCallback\<void\>): void
S
shawn_he 已提交
747 748 749

Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result.

S
shawn_he 已提交
750
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
751 752 753 754 755 756 757 758 759 760

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                              | Mandatory| Description                                                  |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address  | [NetAddress](#netaddress) | Yes  | Destination address. For details, see [NetAddress](#netaddress).|
| callback | AsyncCallback\<void\>              | Yes  | Callback used to return the result.                                            |

S
shawn_he 已提交
761 762 763 764 765 766
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 401     | Parameter error.        |
| 201     | Permission denied.      |
S
shawn_he 已提交
767 768 769

**Example**

S
shawn_he 已提交
770
```js
S
shawn_he 已提交
771
let tcp = socket.constructTCPSocketInstance();
S
shawn_he 已提交
772
tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
S
shawn_he 已提交
773
  if (err) {
S
shawn_he 已提交
774 775
    console.log('bind fail');
    return;
S
shawn_he 已提交
776 777 778 779 780
  }
  console.log('bind success');
})
```

S
shawn_he 已提交
781
### bind<sup>7+</sup>
S
shawn_he 已提交
782

S
shawn_he 已提交
783
bind(address: NetAddress): Promise\<void\>
S
shawn_he 已提交
784 785 786

Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result.

S
shawn_he 已提交
787
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
788 789 790 791 792 793 794 795 796

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name | Type                              | Mandatory| Description                                                  |
| ------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress) | Yes  | Destination address. For details, see [NetAddress](#netaddress).|

S
shawn_he 已提交
797
**Return value**
S
shawn_he 已提交
798 799

| Type           | Description                                                    |
S
shawn_he 已提交
800
| :-------------- | :------------------------------------------------------- |
S
shawn_he 已提交
801 802
| Promise\<void\> | Promise used to return the result.|

S
shawn_he 已提交
803 804 805 806 807 808 809
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 401     | Parameter error.        |
| 201     | Permission denied.      |

S
shawn_he 已提交
810 811
**Example**

S
shawn_he 已提交
812
```js
S
shawn_he 已提交
813
let tcp = socket.constructTCPSocketInstance();
S
shawn_he 已提交
814
let promise = tcp.bind({ address: '192.168.xx.xxx', port: xxxx, family: 1 });
S
shawn_he 已提交
815 816 817 818 819 820 821
promise.then(() => {
  console.log('bind success');
}).catch(err => {
  console.log('bind fail');
});
```

S
shawn_he 已提交
822
### connect<sup>7+</sup>
S
shawn_he 已提交
823

S
shawn_he 已提交
824
connect(options: TCPConnectOptions, callback: AsyncCallback\<void\>): void
S
shawn_he 已提交
825 826 827

Sets up a connection to the specified IP address and port number. This API uses an asynchronous callback to return the result.

S
shawn_he 已提交
828 829
> **NOTE**
> This API can be called only after **bind** is successfully called.
S
shawn_he 已提交
830

S
shawn_he 已提交
831
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
832 833 834 835 836 837 838 839 840 841

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                    | Mandatory| Description                                                        |
| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options  | [TCPConnectOptions](#tcpconnectoptions) | Yes  | TCPSocket connection parameters. For details, see [TCPConnectOptions](#tcpconnectoptions).|
| callback | AsyncCallback\<void\>                    | Yes  | Callback used to return the result.                                                  |

S
shawn_he 已提交
842 843 844 845 846 847 848
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 401     | Parameter error.        |
| 201     | Permission denied.      |

S
shawn_he 已提交
849 850
**Example**

S
shawn_he 已提交
851
```js
S
shawn_he 已提交
852
let tcp = socket.constructTCPSocketInstance();
S
shawn_he 已提交
853
tcp.connect({ address: { address: '192.168.xx.xxx', port: xxxx, family: 1 }, timeout: 6000 }, err => {
S
shawn_he 已提交
854
  if (err) {
S
shawn_he 已提交
855 856
    console.log('connect fail');
    return;
S
shawn_he 已提交
857 858 859 860 861
  }
  console.log('connect success');
})
```

S
shawn_he 已提交
862
### connect<sup>7+</sup>
S
shawn_he 已提交
863

S
shawn_he 已提交
864
connect(options: TCPConnectOptions): Promise\<void\>
S
shawn_he 已提交
865 866 867

Sets up a connection to the specified IP address and port number. This API uses a promise to return the result.

S
shawn_he 已提交
868
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
869 870 871 872 873 874 875 876 877

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name | Type                                    | Mandatory| Description                                                        |
| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPConnectOptions](#tcpconnectoptions) | Yes  | TCPSocket connection parameters. For details, see [TCPConnectOptions](#tcpconnectoptions).|

S
shawn_he 已提交
878
**Return value**
S
shawn_he 已提交
879 880

| Type           | Description                                                      |
S
shawn_he 已提交
881
| :-------------- | :--------------------------------------------------------- |
S
shawn_he 已提交
882 883
| Promise\<void\> | Promise used to return the result.|

S
shawn_he 已提交
884 885 886 887 888 889 890
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 401     | Parameter error.        |
| 201     | Permission denied.      |

S
shawn_he 已提交
891 892
**Example**

S
shawn_he 已提交
893
```js
S
shawn_he 已提交
894
let tcp = socket.constructTCPSocketInstance();
S
shawn_he 已提交
895
let promise = tcp.connect({ address: { address: '192.168.xx.xxx', port: xxxx, family: 1 }, timeout: 6000 });
S
shawn_he 已提交
896 897 898 899 900 901 902
promise.then(() => {
  console.log('connect success')
}).catch(err => {
  console.log('connect fail');
});
```

S
shawn_he 已提交
903
### send<sup>7+</sup>
S
shawn_he 已提交
904

S
shawn_he 已提交
905
send(options: TCPSendOptions, callback: AsyncCallback\<void\>): void
S
shawn_he 已提交
906 907 908

Sends data over a TCPSocket connection. This API uses an asynchronous callback to return the result.

S
shawn_he 已提交
909 910
> **NOTE**
> This API can be called only after **connect** is successfully called.
S
shawn_he 已提交
911

S
shawn_he 已提交
912
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
913 914 915 916 917 918 919 920 921 922

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                   | Mandatory| Description                                                        |
| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| options  | [TCPSendOptions](#tcpsendoptions) | Yes  | Parameters for sending data over the TCPSocket connection. For details, see [TCPSendOptions](#tcpsendoptions).|
| callback | AsyncCallback\<void\>                   | Yes  | Callback used to return the result.                                                  |

S
shawn_he 已提交
923 924 925 926 927 928 929
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 401     | Parameter error.        |
| 201     | Permission denied.      |

S
shawn_he 已提交
930 931
**Example**

S
shawn_he 已提交
932
```js
S
shawn_he 已提交
933
let tcp = socket.constructTCPSocketInstance();
S
shawn_he 已提交
934
tcp.connect({ address: { address: '192.168.xx.xxx', port: xxxx, family: 1 }, timeout: 6000 }, () => {
S
shawn_he 已提交
935 936
  console.log('connect success');
  tcp.send({
S
shawn_he 已提交
937 938 939 940 941 942 943 944
    data: 'Hello, server!'
    // Encoding is omitted here. The UTF-8 encoding format is used by default.
  }, err => {
    if (err) {
      console.log('send fail');
      return;
    }
    console.log('send success');
S
shawn_he 已提交
945
  })
S
shawn_he 已提交
946
})
S
shawn_he 已提交
947 948
```

S
shawn_he 已提交
949
### send<sup>7+</sup>
S
shawn_he 已提交
950

S
shawn_he 已提交
951
send(options: TCPSendOptions): Promise\<void\>
S
shawn_he 已提交
952 953 954

Sends data over a TCPSocket connection. This API uses a promise to return the result.

S
shawn_he 已提交
955 956
> **NOTE**
> This API can be called only after **connect** is successfully called.
S
shawn_he 已提交
957

S
shawn_he 已提交
958
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
959 960 961 962 963 964 965 966 967

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name | Type                                   | Mandatory| Description                                                        |
| ------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPSendOptions](#tcpsendoptions) | Yes  | Parameters for sending data over the TCPSocket connection. For details, see [TCPSendOptions](#tcpsendoptions).|

S
shawn_he 已提交
968
**Return value**
S
shawn_he 已提交
969 970

| Type           | Description                                              |
S
shawn_he 已提交
971
| :-------------- | :------------------------------------------------- |
S
shawn_he 已提交
972 973
| Promise\<void\> | Promise used to return the result.|

S
shawn_he 已提交
974 975 976 977 978 979 980
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 401     | Parameter error.        |
| 201     | Permission denied.      |

S
shawn_he 已提交
981 982
**Example**

S
shawn_he 已提交
983
```js
S
shawn_he 已提交
984
let tcp = socket.constructTCPSocketInstance();
S
shawn_he 已提交
985
let promise1 = tcp.connect({ address: { address: '192.168.xx.xxx', port: xxxx, family: 1 }, timeout: 6000 });
S
shawn_he 已提交
986 987 988
promise1.then(() => {
  console.log('connect success');
  let promise2 = tcp.send({
S
shawn_he 已提交
989
    data: 'Hello, server!'
S
shawn_he 已提交
990 991
  });
  promise2.then(() => {
S
shawn_he 已提交
992
    console.log('send success');
S
shawn_he 已提交
993
  }).catch(err => {
S
shawn_he 已提交
994
    console.log('send fail');
S
shawn_he 已提交
995 996 997 998 999 1000
  });
}).catch(err => {
  console.log('connect fail');
});
```

S
shawn_he 已提交
1001
### close<sup>7+</sup>
S
shawn_he 已提交
1002

S
shawn_he 已提交
1003
close(callback: AsyncCallback\<void\>): void
S
shawn_he 已提交
1004 1005 1006

Closes a TCPSocket connection. This API uses an asynchronous callback to return the result.

S
shawn_he 已提交
1007
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
1008 1009 1010 1011 1012 1013 1014 1015 1016

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                 | Mandatory| Description      |
| -------- | --------------------- | ---- | ---------- |
| callback | AsyncCallback\<void\> | Yes  | Callback used to return the result.|

S
shawn_he 已提交
1017 1018 1019 1020 1021
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 201     | Permission denied.      |
S
shawn_he 已提交
1022 1023 1024

**Example**

S
shawn_he 已提交
1025
```js
S
shawn_he 已提交
1026 1027 1028
let tcp = socket.constructTCPSocketInstance();
tcp.close(err => {
  if (err) {
S
shawn_he 已提交
1029 1030
    console.log('close fail');
    return;
S
shawn_he 已提交
1031 1032 1033 1034 1035
  }
  console.log('close success');
})
```

S
shawn_he 已提交
1036
### close<sup>7+</sup>
S
shawn_he 已提交
1037

S
shawn_he 已提交
1038
close(): Promise\<void\>
S
shawn_he 已提交
1039 1040 1041

Closes a TCPSocket connection. This API uses a promise to return the result.

S
shawn_he 已提交
1042
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
1043 1044 1045

**System capability**: SystemCapability.Communication.NetStack

S
shawn_he 已提交
1046
**Return value**
S
shawn_he 已提交
1047 1048

| Type           | Description                                      |
S
shawn_he 已提交
1049
| :-------------- | :----------------------------------------- |
S
shawn_he 已提交
1050 1051
| Promise\<void\> | Promise used to return the result.|

S
shawn_he 已提交
1052 1053 1054 1055 1056 1057
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 201     | Permission denied.      |

S
shawn_he 已提交
1058 1059
**Example**

S
shawn_he 已提交
1060
```js
S
shawn_he 已提交
1061 1062 1063 1064 1065 1066 1067 1068 1069
let tcp = socket.constructTCPSocketInstance();
let promise = tcp.close();
promise.then(() => {
  console.log('close success');
}).catch(err => {
  console.log('close fail');
});
```

S
shawn_he 已提交
1070
### getRemoteAddress<sup>7+</sup>
S
shawn_he 已提交
1071

S
shawn_he 已提交
1072
getRemoteAddress(callback: AsyncCallback\<NetAddress\>): void
S
shawn_he 已提交
1073

S
shawn_he 已提交
1074
Obtains the remote address of a socket connection. This API uses an asynchronous callback to return the result.
S
shawn_he 已提交
1075

S
shawn_he 已提交
1076 1077
> **NOTE**
> This API can be called only after **connect** is successfully called.
S
shawn_he 已提交
1078

S
shawn_he 已提交
1079
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
1080 1081 1082 1083 1084 1085 1086 1087 1088

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                             | Mandatory| Description      |
| -------- | ------------------------------------------------- | ---- | ---------- |
| callback | AsyncCallback<[NetAddress](#netaddress)> | Yes  | Callback used to return the result.|

S
shawn_he 已提交
1089 1090 1091 1092 1093 1094
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 201     | Permission denied.      |

S
shawn_he 已提交
1095 1096
**Example**

S
shawn_he 已提交
1097
```js
S
shawn_he 已提交
1098
let tcp = socket.constructTCPSocketInstance();
S
shawn_he 已提交
1099
tcp.connect({ address: { address: '192.168.xx.xxx', port: xxxx, family: 1 }, timeout: 6000 }, () => {
S
shawn_he 已提交
1100 1101
  console.log('connect success');
  tcp.getRemoteAddress((err, data) => {
S
shawn_he 已提交
1102 1103 1104 1105 1106
    if (err) {
      console.log('getRemoteAddressfail');
      return;
    }
    console.log('getRemoteAddresssuccess:' + JSON.stringify(data));
S
shawn_he 已提交
1107 1108 1109 1110
  })
});
```

S
shawn_he 已提交
1111
### getRemoteAddress<sup>7+</sup>
S
shawn_he 已提交
1112

S
shawn_he 已提交
1113
getRemoteAddress(): Promise\<NetAddress\>
S
shawn_he 已提交
1114

S
shawn_he 已提交
1115
Obtains the remote address of a socket connection. This API uses a promise to return the result.
S
shawn_he 已提交
1116

S
shawn_he 已提交
1117 1118
> **NOTE**
> This API can be called only after **connect** is successfully called.
S
shawn_he 已提交
1119

S
shawn_he 已提交
1120
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
1121 1122 1123

**System capability**: SystemCapability.Communication.NetStack

S
shawn_he 已提交
1124
**Return value**
S
shawn_he 已提交
1125 1126

| Type                                       | Description                                       |
S
shawn_he 已提交
1127
| :------------------------------------------ | :------------------------------------------ |
S
shawn_he 已提交
1128 1129
| Promise<[NetAddress](#netaddress)> | Promise used to return the result.|

S
shawn_he 已提交
1130 1131 1132 1133 1134 1135
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 201     | Permission denied.      |

S
shawn_he 已提交
1136 1137
**Example**

S
shawn_he 已提交
1138
```js
S
shawn_he 已提交
1139
let tcp = socket.constructTCPSocketInstance();
S
shawn_he 已提交
1140
let promise1 = tcp.connect({ address: { address: '192.168.xx.xxx', port: xxxx, family: 1 }, timeout: 6000 });
S
shawn_he 已提交
1141 1142 1143 1144
promise1.then(() => {
  console.log('connect success');
  let promise2 = tcp.getRemoteAddress();
  promise2.then(() => {
S
shawn_he 已提交
1145
    console.log('getRemoteAddress success');
S
shawn_he 已提交
1146
  }).catch(err => {
S
shawn_he 已提交
1147
    console.log('getRemoteAddressfail');
S
shawn_he 已提交
1148 1149 1150 1151 1152 1153
  });
}).catch(err => {
  console.log('connect fail');
});
```

S
shawn_he 已提交
1154
### getState<sup>7+</sup>
S
shawn_he 已提交
1155

S
shawn_he 已提交
1156
getState(callback: AsyncCallback\<SocketStateBase\>): void
S
shawn_he 已提交
1157 1158 1159

Obtains the status of the TCPSocket connection. This API uses an asynchronous callback to return the result.

S
shawn_he 已提交
1160 1161
> **NOTE**
> This API can be called only after **bind** or **connect** is successfully called.
S
shawn_he 已提交
1162

S
shawn_he 已提交
1163
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
1164 1165 1166 1167 1168 1169 1170 1171 1172

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                                  | Mandatory| Description      |
| -------- | ------------------------------------------------------ | ---- | ---------- |
| callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | Yes  | Callback used to return the result.|

S
shawn_he 已提交
1173 1174 1175 1176 1177
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 201     | Permission denied.      |
S
shawn_he 已提交
1178 1179 1180

**Example**

S
shawn_he 已提交
1181
```js
S
shawn_he 已提交
1182
let tcp = socket.constructTCPSocketInstance();
S
shawn_he 已提交
1183
let promise = tcp.connect({ address: { address: '192.168.xx.xxx', port: xxxx, family: 1 }, timeout: 6000 }, () => {
S
shawn_he 已提交
1184 1185
  console.log('connect success');
  tcp.getState((err, data) => {
S
shawn_he 已提交
1186 1187 1188 1189 1190
    if (err) {
      console.log('getState fail');
      return;
    }
    console.log('getState success:' + JSON.stringify(data));
S
shawn_he 已提交
1191 1192 1193 1194
  });
});
```

S
shawn_he 已提交
1195
### getState<sup>7+</sup>
S
shawn_he 已提交
1196

S
shawn_he 已提交
1197
getState(): Promise\<SocketStateBase\>
S
shawn_he 已提交
1198 1199 1200

Obtains the status of the TCPSocket connection. This API uses a promise to return the result.

S
shawn_he 已提交
1201 1202
> **NOTE**
> This API can be called only after **bind** or **connect** is successfully called.
S
shawn_he 已提交
1203

S
shawn_he 已提交
1204
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
1205 1206 1207

**System capability**: SystemCapability.Communication.NetStack

S
shawn_he 已提交
1208
**Return value**
S
shawn_he 已提交
1209 1210

| Type                                            | Description                                      |
S
shawn_he 已提交
1211
| :----------------------------------------------- | :----------------------------------------- |
S
shawn_he 已提交
1212 1213
| Promise<[SocketStateBase](#socketstatebase)> | Promise used to return the result.|

S
shawn_he 已提交
1214 1215 1216 1217 1218
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 201     | Permission denied.      |
S
shawn_he 已提交
1219 1220 1221

**Example**

S
shawn_he 已提交
1222
```js
S
shawn_he 已提交
1223
let tcp = socket.constructTCPSocketInstance();
S
shawn_he 已提交
1224
let promise = tcp.connect({ address: { address: '192.168.xx.xxx', port: xxxx, family: 1 }, timeout: 6000 });
S
shawn_he 已提交
1225 1226 1227 1228
promise.then(() => {
  console.log('connect success');
  let promise1 = tcp.getState();
  promise1.then(() => {
S
shawn_he 已提交
1229
    console.log('getState success');
S
shawn_he 已提交
1230
  }).catch(err => {
S
shawn_he 已提交
1231
    console.log('getState fail');
S
shawn_he 已提交
1232 1233 1234 1235 1236 1237
  });
}).catch(err => {
  console.log('connect fail');
});
```

S
shawn_he 已提交
1238
### setExtraOptions<sup>7+</sup>
S
shawn_he 已提交
1239

S
shawn_he 已提交
1240
setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\<void\>): void
S
shawn_he 已提交
1241 1242 1243

Sets other properties of the TCPSocket connection. This API uses an asynchronous callback to return the result.

S
shawn_he 已提交
1244 1245
> **NOTE**
> This API can be called only after **bind** or **connect** is successfully called.
S
shawn_he 已提交
1246

S
shawn_he 已提交
1247
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                     | Mandatory| Description                                                        |
| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| options  | [TCPExtraOptions](#tcpextraoptions) | Yes  | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).|
| callback | AsyncCallback\<void\>                     | Yes  | Callback used to return the result.                                                  |

S
shawn_he 已提交
1258 1259 1260 1261 1262 1263 1264
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 401     | Parameter error.        |
| 201     | Permission denied.      |

S
shawn_he 已提交
1265 1266
**Example**

S
shawn_he 已提交
1267
```js
S
shawn_he 已提交
1268
let tcp = socket.constructTCPSocketInstance();
S
shawn_he 已提交
1269
let promise = tcp.connect({ address: { address: '192.168.xx.xxx', port: xxxx, family: 1 }, timeout: 6000 }, () => {
S
shawn_he 已提交
1270 1271
  console.log('connect success');
  tcp.setExtraOptions({
S
shawn_he 已提交
1272 1273 1274
    keepAlive: true,
    OOBInline: true,
    TCPNoDelay: true,
S
shawn_he 已提交
1275
    socketLinger: { on: true, linger: 10 },
S
shawn_he 已提交
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
    receiveBufferSize: 1000,
    sendBufferSize: 1000,
    reuseAddress: true,
    socketTimeout: 3000,
  }, err => {
    if (err) {
      console.log('setExtraOptions fail');
      return;
    }
    console.log('setExtraOptions success');
S
shawn_he 已提交
1286 1287 1288 1289
  });
});
```

S
shawn_he 已提交
1290
### setExtraOptions<sup>7+</sup>
S
shawn_he 已提交
1291

S
shawn_he 已提交
1292
setExtraOptions(options: TCPExtraOptions): Promise\<void\>
S
shawn_he 已提交
1293 1294 1295

Sets other properties of the TCPSocket connection. This API uses a promise to return the result.

S
shawn_he 已提交
1296 1297
> **NOTE**
> This API can be called only after **bind** or **connect** is successfully called.
S
shawn_he 已提交
1298

S
shawn_he 已提交
1299
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
1300 1301 1302 1303 1304 1305 1306 1307 1308

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name | Type                                     | Mandatory| Description                                                        |
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPExtraOptions](#tcpextraoptions) | Yes  | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).|

S
shawn_he 已提交
1309
**Return value**
S
shawn_he 已提交
1310 1311

| Type           | Description                                                |
S
shawn_he 已提交
1312
| :-------------- | :--------------------------------------------------- |
S
shawn_he 已提交
1313 1314
| Promise\<void\> | Promise used to return the result.|

S
shawn_he 已提交
1315 1316 1317 1318 1319 1320
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 401     | Parameter error.        |
| 201     | Permission denied.      |
S
shawn_he 已提交
1321 1322 1323

**Example**

S
shawn_he 已提交
1324
```js
S
shawn_he 已提交
1325
let tcp = socket.constructTCPSocketInstance();
S
shawn_he 已提交
1326
let promise = tcp.connect({ address: { address: '192.168.xx.xxx', port: xxxx, family: 1 }, timeout: 6000 });
S
shawn_he 已提交
1327 1328 1329
promise.then(() => {
  console.log('connect success');
  let promise1 = tcp.setExtraOptions({
S
shawn_he 已提交
1330 1331 1332
    keepAlive: true,
    OOBInline: true,
    TCPNoDelay: true,
S
shawn_he 已提交
1333
    socketLinger: { on: true, linger: 10 },
S
shawn_he 已提交
1334 1335 1336 1337
    receiveBufferSize: 1000,
    sendBufferSize: 1000,
    reuseAddress: true,
    socketTimeout: 3000,
S
shawn_he 已提交
1338 1339
  });
  promise1.then(() => {
S
shawn_he 已提交
1340
    console.log('setExtraOptions success');
S
shawn_he 已提交
1341
  }).catch(err => {
S
shawn_he 已提交
1342
    console.log('setExtraOptions fail');
S
shawn_he 已提交
1343 1344 1345 1346 1347 1348
  });
}).catch(err => {
  console.log('connect fail');
});
```

S
shawn_he 已提交
1349
### on('message')<sup>7+</sup>
S
shawn_he 已提交
1350

S
shawn_he 已提交
1351
on(type: 'message', callback: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void
S
shawn_he 已提交
1352 1353 1354 1355 1356 1357 1358 1359 1360

Enables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                                        | Mandatory| Description                                     |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
S
shawn_he 已提交
1361
| type     | string                                                       | Yes  | Type of the event to subscribe to.<br /> **message**: message receiving event|
S
shawn_he 已提交
1362 1363 1364 1365
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | Yes  | Callback used to return the result.                               |

**Example**

S
shawn_he 已提交
1366
```js
S
shawn_he 已提交
1367
let tcp = socket.constructTCPSocketInstance();
S
shawn_he 已提交
1368
let messageView = '';
S
shawn_he 已提交
1369
tcp.on('message', value => {
S
shawn_he 已提交
1370 1371 1372
  for (var i = 0; i < value.message.length; i++) {
    let messages = value.message[i]
    let message = String.fromCharCode(messages);
S
shawn_he 已提交
1373
    messageView += message;
S
shawn_he 已提交
1374 1375 1376
  }
  console.log('on message message: ' + JSON.stringify(messageView));
  console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo));
S
shawn_he 已提交
1377 1378 1379
});
```

S
shawn_he 已提交
1380
### off('message')<sup>7+</sup>
S
shawn_he 已提交
1381

S
shawn_he 已提交
1382
off(type: 'message', callback?: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void
S
shawn_he 已提交
1383 1384 1385

Disables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result.

S
shawn_he 已提交
1386 1387
> **NOTE**
> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
S
shawn_he 已提交
1388 1389 1390 1391 1392 1393 1394

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                                        | Mandatory| Description                                     |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
S
shawn_he 已提交
1395
| type     | string                                                       | Yes  | Type of the event to subscribe to.<br /> **message**: message receiving event|
S
shawn_he 已提交
1396 1397 1398 1399
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No  | Callback used to return the result.                               |

**Example**

S
shawn_he 已提交
1400
```js
S
shawn_he 已提交
1401
let tcp = socket.constructTCPSocketInstance();
S
shawn_he 已提交
1402
let messageView = '';
S
shawn_he 已提交
1403
let callback = value => {
S
shawn_he 已提交
1404 1405 1406
  for (var i = 0; i < value.message.length; i++) {
    let messages = value.message[i]
    let message = String.fromCharCode(messages);
S
shawn_he 已提交
1407
    messageView += message;
S
shawn_he 已提交
1408 1409 1410
  }
  console.log('on message message: ' + JSON.stringify(messageView));
  console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo));
S
shawn_he 已提交
1411 1412
}
tcp.on('message', callback);
S
shawn_he 已提交
1413
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
S
shawn_he 已提交
1414 1415 1416 1417
tcp.off('message', callback);
tcp.off('message');
```

S
shawn_he 已提交
1418
### on('connect' | 'close')<sup>7+</sup>
S
shawn_he 已提交
1419

S
shawn_he 已提交
1420
on(type: 'connect' | 'close', callback: Callback\<void\>): void
S
shawn_he 已提交
1421 1422 1423 1424 1425 1426 1427 1428 1429

Enables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type            | Mandatory| Description                                                        |
| -------- | ---------------- | ---- | ------------------------------------------------------------ |
S
shawn_he 已提交
1430
| type     | string           | Yes  | Type of the event to subscribe to.<br /><br>- **connect**: connection event<br>- **close**: close event|
S
shawn_he 已提交
1431 1432 1433 1434
| callback | Callback\<void\> | Yes  | Callback used to return the result.                                                  |

**Example**

S
shawn_he 已提交
1435
```js
S
shawn_he 已提交
1436 1437
let tcp = socket.constructTCPSocketInstance();
tcp.on('connect', () => {
S
shawn_he 已提交
1438
  console.log("on connect success")
S
shawn_he 已提交
1439
});
S
shawn_he 已提交
1440
tcp.on('close', () => {
S
shawn_he 已提交
1441
  console.log("on close success")
S
shawn_he 已提交
1442 1443 1444
});
```

S
shawn_he 已提交
1445
### off('connect' | 'close')<sup>7+</sup>
S
shawn_he 已提交
1446

S
shawn_he 已提交
1447
off(type: 'connect' | 'close', callback?: Callback\<void\>): void
S
shawn_he 已提交
1448 1449 1450

Disables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result.

S
shawn_he 已提交
1451 1452
> **NOTE**
> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
S
shawn_he 已提交
1453 1454 1455 1456 1457 1458 1459

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type            | Mandatory| Description                                                        |
| -------- | ---------------- | ---- | ------------------------------------------------------------ |
S
shawn_he 已提交
1460
| type     | string           | Yes  | Type of the event to subscribe to.<br /><br>- **connect**: connection event<br>- **close**: close event|
S
shawn_he 已提交
1461 1462 1463 1464
| callback | Callback\<void\> | No  | Callback used to return the result.                                                  |

**Example**

S
shawn_he 已提交
1465
```js
S
shawn_he 已提交
1466
let tcp = socket.constructTCPSocketInstance();
S
shawn_he 已提交
1467 1468
let callback1 = () => {
  console.log("on connect success");
S
shawn_he 已提交
1469 1470
}
tcp.on('connect', callback1);
S
shawn_he 已提交
1471
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
S
shawn_he 已提交
1472 1473
tcp.off('connect', callback1);
tcp.off('connect');
S
shawn_he 已提交
1474 1475
let callback2 = () => {
  console.log("on close success");
S
shawn_he 已提交
1476 1477
}
tcp.on('close', callback2);
S
shawn_he 已提交
1478
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
S
shawn_he 已提交
1479 1480 1481 1482
tcp.off('close', callback2);
tcp.off('close');
```

S
shawn_he 已提交
1483
### on('error')<sup>7+</sup>
S
shawn_he 已提交
1484

S
shawn_he 已提交
1485
on(type: 'error', callback: ErrorCallback): void
S
shawn_he 已提交
1486 1487 1488 1489 1490 1491 1492 1493 1494

Enables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type         | Mandatory| Description                                |
| -------- | ------------- | ---- | ------------------------------------ |
S
shawn_he 已提交
1495
| type     | string        | Yes  | Type of the event to subscribe to.<br /> **error**: error event|
S
shawn_he 已提交
1496 1497 1498 1499
| callback | ErrorCallback | Yes  | Callback used to return the result.                          |

**Example**

S
shawn_he 已提交
1500
```js
S
shawn_he 已提交
1501 1502
let tcp = socket.constructTCPSocketInstance();
tcp.on('error', err => {
S
shawn_he 已提交
1503
  console.log("on error, err:" + JSON.stringify(err))
S
shawn_he 已提交
1504 1505 1506
});
```

S
shawn_he 已提交
1507
### off('error')<sup>7+</sup>
S
shawn_he 已提交
1508

S
shawn_he 已提交
1509
off(type: 'error', callback?: ErrorCallback): void
S
shawn_he 已提交
1510 1511 1512

Disables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result.

S
shawn_he 已提交
1513 1514
> **NOTE**
> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
S
shawn_he 已提交
1515 1516 1517 1518 1519 1520 1521

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type         | Mandatory| Description                                |
| -------- | ------------- | ---- | ------------------------------------ |
S
shawn_he 已提交
1522
| type     | string        | Yes  | Type of the event to subscribe to.<br /> **error**: error event|
S
shawn_he 已提交
1523 1524 1525 1526
| callback | ErrorCallback | No  | Callback used to return the result.                          |

**Example**

S
shawn_he 已提交
1527
```js
S
shawn_he 已提交
1528
let tcp = socket.constructTCPSocketInstance();
S
shawn_he 已提交
1529 1530
let callback = err => {
  console.log("on error, err:" + JSON.stringify(err));
S
shawn_he 已提交
1531 1532
}
tcp.on('error', callback);
S
shawn_he 已提交
1533
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
S
shawn_he 已提交
1534 1535 1536 1537
tcp.off('error', callback);
tcp.off('error');
```

S
shawn_he 已提交
1538
## TCPConnectOptions<sup>7+</sup>
S
shawn_he 已提交
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548

Defines TCPSocket connection parameters.

**System capability**: SystemCapability.Communication.NetStack

| Name | Type                              | Mandatory| Description                      |
| ------- | ---------------------------------- | ---- | -------------------------- |
| address | [NetAddress](#netaddress) | Yes  | Bound IP address and port number.      |
| timeout | number                             | No  | Timeout duration of the TCPSocket connection, in ms.|

S
shawn_he 已提交
1549
## TCPSendOptions<sup>7+</sup>
S
shawn_he 已提交
1550 1551 1552 1553 1554 1555 1556

Defines the parameters for sending data over the TCPSocket connection.

**System capability**: SystemCapability.Communication.NetStack

| Name  | Type  | Mandatory| Description                                                        |
| -------- | ------ | ---- | ------------------------------------------------------------ |
S
shawn_he 已提交
1557
| data     | string\| ArrayBuffer<sup>7+</sup>  | Yes  | Data to send.                                                |
S
shawn_he 已提交
1558 1559
| encoding | string | No  | Character encoding format. The options are as follows: **UTF-8**, **UTF-16BE**, **UTF-16LE**, **UTF-16**, **US-AECII**, and **ISO-8859-1**. The default value is **UTF-8**.|

S
shawn_he 已提交
1560
## TCPExtraOptions<sup>7+</sup>
S
shawn_he 已提交
1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571

Defines other properties of the TCPSocket connection.

**System capability**: SystemCapability.Communication.NetStack

| Name           | Type   | Mandatory| Description                                                        |
| ----------------- | ------- | ---- | ------------------------------------------------------------ |
| keepAlive         | boolean | No  | Whether to keep the connection alive. The default value is **false**.                                 |
| OOBInline         | boolean | No  | Whether to enable OOBInline. The default value is **false**.                                |
| TCPNoDelay        | boolean | No  | Whether to enable no-delay on the TCPSocket connection. The default value is **false**.                      |
| socketLinger      | Object  | Yes  | Socket linger.<br>- **on**: whether to enable socket linger. The value true means to enable socket linger and false means the opposite.<br>- **linger**: linger time, in ms. The value ranges from **0** to **65535**.<br>Specify this parameter only when **on** is set to **true**.|
S
shawn_he 已提交
1572 1573
| receiveBufferSize | number  | No  | Size of the receive buffer, in bytes. The default value is **0**.                              |
| sendBufferSize    | number  | No  | Size of the send buffer, in bytes. The default value is **0**.                              |
S
shawn_he 已提交
1574
| reuseAddress      | boolean | No  | Whether to reuse addresses. The default value is **false**.                                 |
S
shawn_he 已提交
1575
| socketTimeout     | number  | No  | Timeout duration of the TCPSocket connection, in ms. The default value is **0**.                            |
S
shawn_he 已提交
1576 1577 1578 1579 1580 1581

## Description of TCP Error Codes

The TCP error code mapping is in the format of 2301000 + Linux kernel error code.

For details about error codes, see [Socket Error Codes](../errorcodes/errorcode-net-socket.md).
S
shawn_he 已提交
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593

## socket.constructTLSSocketInstance<sup>9+</sup>

constructTLSSocketInstance(): TLSSocket

Creates a **TLSSocket** object.

**System capability**: SystemCapability.Communication.NetStack

**Return value**

| Type                              | Description                   |
S
shawn_he 已提交
1594
| :--------------------------------- | :---------------------- |
S
shawn_he 已提交
1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
| [TLSSocket](#tlssocket9) | **TLSSocket** object.|

**Example**

```js
let tls = socket.constructTLSSocketInstance();
```

## TLSSocket<sup>9+</sup>

Defines a TLSSocket connection. Before invoking TLSSocket APIs, you need to call [socket.constructTLSSocketInstance](#socketconstructtlssocketinstance9) to create a **TLSSocket** object.

### bind<sup>9+</sup>

S
shawn_he 已提交
1609
bind(address: NetAddress, callback: AsyncCallback\<void\>): void
S
shawn_he 已提交
1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635

Binds the IP address and port number. This API uses an asynchronous callback to return the result.

**Required permissions**: ohos.permission.INTERNET

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                              | Mandatory| Description                                                  |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address  | [NetAddress](#netaddress) | Yes  | Destination address. For details, see [NetAddress](#netaddress).|
| callback | AsyncCallback\<void\>              | Yes  | Callback used to return the result. If the operation is successful, the result of binding the local IP address and port number is returned. If the operation fails, an error message is returned.|

**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 401     | Parameter error.        |
| 201     | Permission denied.      |
| 2303198 | Address already in use. |
| 2300002 | System internal error.  |

**Example**

```js
S
shawn_he 已提交
1636
tls.bind({ address: '192.168.xx.xxx', port: xxxx, family: 1 }, err => {
S
shawn_he 已提交
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646
  if (err) {
    console.log('bind fail');
    return;
  }
  console.log('bind success');
});
```

### bind<sup>9+</sup>

S
shawn_he 已提交
1647
bind(address: NetAddress): Promise\<void\>
S
shawn_he 已提交
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663

Binds the IP address and port number. This API uses a promise to return the result.

**Required permissions**: ohos.permission.INTERNET

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name | Type                              | Mandatory| Description                                                  |
| ------- | ---------------------------------- | ---- | ------------------------------------------------------ |
| address | [NetAddress](#netaddress)          | Yes  | Destination address. For details, see [NetAddress](#netaddress).|

**Return value**

| Type           | Description                                                    |
S
shawn_he 已提交
1664
| :-------------- | :------------------------------------------------------- |
S
shawn_he 已提交
1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678
| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.|

**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 401     | Parameter error.        |
| 201     | Permission denied.      |
| 2303198 | Address already in use. |
| 2300002 | System internal error.  |

**Example**

```js
S
shawn_he 已提交
1679
let promise = tls.bind({ address: '192.168.xx.xxx', port: xxxx, family: 1 });
S
shawn_he 已提交
1680 1681 1682 1683 1684 1685 1686 1687 1688
promise.then(() => {
  console.log('bind success');
}).catch(err => {
  console.log('bind fail');
});
```

### getState<sup>9+</sup>

S
shawn_he 已提交
1689
getState(callback: AsyncCallback\<SocketStateBase\>): void
S
shawn_he 已提交
1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710

Obtains the status of the TLSSocket connection. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                                  | Mandatory| Description      |
| -------- | ------------------------------------------------------ | ---- | ---------- |
| callback | AsyncCallback\<[SocketStateBase](#socketstatebase)> | Yes  | Callback used to return the result. If the operation is successful, the status of the TLSSocket connection is returned. If the operation fails, an error message is returned.|

**Error codes**

| ID| Error Message                       |
| ------- | ------------------------------ |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error.         |

**Example**

```js
S
shawn_he 已提交
1711
let promise = tls.bind({ address: '192.168.xx.xxx', port: xxxx, family: 1 }, err => {
S
shawn_he 已提交
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
  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>

S
shawn_he 已提交
1729
getState(): Promise\<SocketStateBase\>
S
shawn_he 已提交
1730 1731 1732 1733 1734 1735 1736 1737

Obtains the status of the TLSSocket connection. This API uses a promise to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Return value**

| Type                                            | Description                                      |
S
shawn_he 已提交
1738
| :----------------------------------------------- | :----------------------------------------- |
S
shawn_he 已提交
1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750
| Promise\<[SocketStateBase](#socketstatebase)> | Promise used to return the result. If the operation fails, an error message is returned.|

**Error codes**

| ID| Error Message                       |
| ------- | ------------------------------ |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error.         |

**Example**

```js
S
shawn_he 已提交
1751
let promiseBind = tls.bind({ address: '192.168.xx.xxx', port: xxxx, family: 1 });
S
shawn_he 已提交
1752
promiseBind.then(() => {
S
shawn_he 已提交
1753
  console.log('bind success');
S
shawn_he 已提交
1754 1755
}).catch((err) => {
  console.log('bind fail');
S
shawn_he 已提交
1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766
});
let promise = tls.getState();
promise.then(() => {
  console.log('getState success');
}).catch(err => {
  console.log('getState fail');
});
```

### setExtraOptions<sup>9+</sup>

S
shawn_he 已提交
1767
setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\<void\>): void
S
shawn_he 已提交
1768

S
shawn_he 已提交
1769
Sets other properties of the TCPSocket connection after successful binding of the local IP address and port number of the connection. This API uses an asynchronous callback to return the result.
S
shawn_he 已提交
1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                     | Mandatory| Description                                                        |
| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| options  | [TCPExtraOptions](#tcpextraoptions) | Yes  | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).|
| callback | AsyncCallback\<void\>                     | Yes  | Callback used to return the result. If the operation is successful, the result of setting other properties of the TCPSocket connection is returned. If the operation fails, an error message is returned.|

**Error codes**

| ID| Error Message                       |
| ------- | -----------------------------  |
| 401     | Parameter error.               |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error.         |

**Example**

```js
S
shawn_he 已提交
1791
tls.bind({ address: '192.168.xx.xxx', port: xxxx, family: 1 }, err => {
S
shawn_he 已提交
1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
  if (err) {
    console.log('bind fail');
    return;
  }
  console.log('bind success');
});

tls.setExtraOptions({
  keepAlive: true,
  OOBInline: true,
  TCPNoDelay: true,
S
shawn_he 已提交
1803
  socketLinger: { on: true, linger: 10 },
S
shawn_he 已提交
1804 1805 1806 1807
  receiveBufferSize: 1000,
  sendBufferSize: 1000,
  reuseAddress: true,
  socketTimeout: 3000,
S
shawn_he 已提交
1808
}, err => {
S
shawn_he 已提交
1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
  if (err) {
    console.log('setExtraOptions fail');
    return;
  }
  console.log('setExtraOptions success');
});
```

### setExtraOptions<sup>9+</sup>

S
shawn_he 已提交
1819
setExtraOptions(options: TCPExtraOptions): Promise\<void\>
S
shawn_he 已提交
1820

S
shawn_he 已提交
1821
Sets other properties of the TCPSocket connection after successful binding of the local IP address and port number of the connection. This API uses a promise to return the result.
S
shawn_he 已提交
1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name | Type                                     | Mandatory| Description                                                        |
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPExtraOptions](#tcpextraoptions) | Yes  | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).|

**Return value**

| Type           | Description                                                |
S
shawn_he 已提交
1834
| :-------------- | :--------------------------------------------------- |
S
shawn_he 已提交
1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847
| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.|

**Error codes**

| ID| Error Message                       |
| ------- | ------------------------------ |
| 401     | Parameter error.               |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error.         |

**Example**

```js
S
shawn_he 已提交
1848
tls.bind({ address: '192.168.xx.xxx', port: xxxx, family: 1 }, err => {
S
shawn_he 已提交
1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
  if (err) {
    console.log('bind fail');
    return;
  }
  console.log('bind success');
});
let promise = tls.setExtraOptions({
  keepAlive: true,
  OOBInline: true,
  TCPNoDelay: true,
S
shawn_he 已提交
1859
  socketLinger: { on: true, linger: 10 },
S
shawn_he 已提交
1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871
  receiveBufferSize: 1000,
  sendBufferSize: 1000,
  reuseAddress: true,
  socketTimeout: 3000,
});
promise.then(() => {
  console.log('setExtraOptions success');
}).catch(err => {
  console.log('setExtraOptions fail');
});
```

S
shawn_he 已提交
1872
### on('message')<sup>9+</sup>
S
shawn_he 已提交
1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890

on(type: 'message', callback: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}>): void;

Subscribes to **message** events of the TLSSocket connection. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                                        | Mandatory| Description                                     |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type     | string                                                       | Yes  | Type of the event to subscribe to.<br /> **message**: message receiving event|
| callback | Callback\<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}\> | Yes  | Callback used to return the result.<br> **message**: received message.<br>**remoteInfo**: socket connection information.|

**Example**

```js
let tls = socket.constructTLSSocketInstance();
S
shawn_he 已提交
1891
let messageView = '';
S
shawn_he 已提交
1892 1893 1894 1895
tls.on('message', value => {
  for (var i = 0; i < value.message.length; i++) {
    let messages = value.message[i]
    let message = String.fromCharCode(messages);
S
shawn_he 已提交
1896
    messageView += message;
S
shawn_he 已提交
1897 1898 1899 1900 1901 1902
  }
  console.log('on message message: ' + JSON.stringify(messageView));
  console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo));
});
```

S
shawn_he 已提交
1903
### off('message')<sup>9+</sup>
S
shawn_he 已提交
1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924

off(type: 'message', callback?: Callback\<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void

Unsubscribes from **message** events of the TLSSocket connection. This API uses an asynchronous callback to return the result.

> **NOTE**
> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                                        | Mandatory| Description                                     |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type     | string                                                       | Yes  | Type of the event to subscribe to.<br /> **message**: message receiving event|
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No  | Callback used to return the result. **message**: received message.<br>**remoteInfo**: socket connection information.|

**Example**

```js
let tls = socket.constructTLSSocketInstance();
S
shawn_he 已提交
1925
let messageView = '';
S
shawn_he 已提交
1926 1927 1928 1929
let callback = value => {
  for (var i = 0; i < value.message.length; i++) {
    let messages = value.message[i]
    let message = String.fromCharCode(messages);
S
shawn_he 已提交
1930
    messageView += message;
S
shawn_he 已提交
1931 1932 1933 1934 1935 1936 1937 1938
  }
  console.log('on message message: ' + JSON.stringify(messageView));
  console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo));
}
tls.on('message', callback);
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
tls.off('message', callback);
```
S
shawn_he 已提交
1939
### on('connect' | 'close')<sup>9+</sup>
S
shawn_he 已提交
1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965

on(type: 'connect' | 'close', callback: Callback\<void\>): void

Enables listening for connection or close events of the TLSSocket connection. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type            | Mandatory| Description                                                        |
| -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type     | string           | Yes  | Type of the event to subscribe to.<br /><br>- **connect**: connection event<br>- **close**: close event|
| callback | Callback\<void\> | Yes  | Callback used to return the result.                                                  |

**Example**

```js
let tls = socket.constructTLSSocketInstance();
tls.on('connect', () => {
  console.log("on connect success")
});
tls.on('close', () => {
  console.log("on close success")
});
```

S
shawn_he 已提交
1966
### off('connect' | 'close')<sup>9+</sup>
S
shawn_he 已提交
1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002

off(type: 'connect' | 'close', callback?: Callback\<void\>): void

Disables listening for connection or close events of the TLSSocket connection. This API uses an asynchronous callback to return the result.

> **NOTE**
> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type            | Mandatory| Description                                                        |
| -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type     | string           | Yes  | Type of the event to subscribe to.<br /><br>- **connect**: connection event<br>- **close**: close event|
| callback | Callback\<void\> | No  | Callback used to return the result.                                                  |

**Example**

```js
let tls = socket.constructTLSSocketInstance();
let callback1 = () => {
  console.log("on connect success");
}
tls.on('connect', callback1);
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
tls.off('connect', callback1);
tls.off('connect');
let callback2 = () => {
  console.log("on close success");
}
tls.on('close', callback2);
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
tls.off('close', callback2);
```

S
shawn_he 已提交
2003
### on('error')<sup>9+</sup>
S
shawn_he 已提交
2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026

on(type: 'error', callback: ErrorCallback): void

Enables listening for error events of the TLSSocket connection. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type         | Mandatory| Description                                |
| -------- | ------------- | ---- | ------------------------------------ |
| type     | string        | Yes  | Type of the event to subscribe to.<br /> **error**: error event|
| callback | ErrorCallback | Yes  | Callback used to return the result.                          |

**Example**

```js
let tls = socket.constructTLSSocketInstance();
tls.on('error', err => {
  console.log("on error, err:" + JSON.stringify(err))
});
```

S
shawn_he 已提交
2027
### off('error')<sup>9+</sup>
S
shawn_he 已提交
2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056

off(type: 'error', callback?: ErrorCallback): void

Disables listening for error events of the TLSSocket connection. This API uses an asynchronous callback to return the result.

> **NOTE**
> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type         | Mandatory| Description                                |
| -------- | ------------- | ---- | ------------------------------------ |
| type     | string        | Yes  | Type of the event to subscribe to.<br /> **error**: error event|
| callback | ErrorCallback | No  | Callback used to return the result.                          |

**Example**

```js
let tls = socket.constructTLSSocketInstance();
let callback = err => {
  console.log("on error, err:" + JSON.stringify(err));
}
tls.on('error', callback);
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
tls.off('error', callback);
```

S
shawn_he 已提交
2057 2058
### connect<sup>9+</sup>

S
shawn_he 已提交
2059
connect(options: TLSConnectOptions, callback: AsyncCallback\<void\>): void
S
shawn_he 已提交
2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095

Sets up a TLSSocket connection, and creates and initializes a TLS session after successful binding of the local IP address and port number of the TLSSocket connection. During this process, a TLS/SSL handshake is performed between the application and the server to implement data transmission. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                  | Mandatory| Description|
| -------- | ---------------------------------------| ----| --------------- |
| options  | [TLSConnectOptions](#tlsconnectoptions9) | Yes  | Parameters required for the TLSSocket connection.|
| callback | AsyncCallback\<void>                  | Yes  | Callback used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|

**Error codes**

| ID| Error Message                                     |
| ------- | -------------------------------------------- |
| 401     | Parameter error.                             |
| 2303104 | Interrupted system call.                     |
| 2303109 | Bad file number.                             |
| 2303111 | Resource temporarily unavailable try again.  |
| 2303188 | Socket operation on non-socket.              |
| 2303191 | Protocol wrong type for socket.              |
| 2303198 | Address already in use.                      |
| 2303199 | Cannot assign requested address.             |
| 2303210 | Connection timed out.                        |
| 2303501 | SSL is null.                                 |
| 2303502 | Error in tls reading.                        |
| 2303503 | Error in tls writing                         |
| 2303505 | Error occurred in the tls system call.       |
| 2303506 | Error clearing tls connection.               |
| 2300002 | System internal error.                       |

**Example**

```js
let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication
S
shawn_he 已提交
2096
tlsTwoWay.bind({ address: '192.168.xxx.xxx', port: 8080, family: 1 }, err => {
S
shawn_he 已提交
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106
  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",
S
shawn_he 已提交
2107
    port: 8080,
S
shawn_he 已提交
2108 2109 2110 2111 2112 2113
    family: 1,
  },
  secureOptions: {
    key: "xxxx",
    cert: "xxxx",
    ca: ["xxxx"],
S
shawn_he 已提交
2114
    password: "xxxx",
S
shawn_he 已提交
2115 2116 2117 2118 2119 2120 2121
    protocols: [socket.Protocol.TLSv12],
    useRemoteCipherPrefer: true,
    signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
    cipherSuite: "AES256-SHA256",
  },
};
tlsTwoWay.connect(options, (err, data) => {
S
shawn_he 已提交
2122
  console.error("connect callback error" + err);
S
shawn_he 已提交
2123
  console.log(JSON.stringify(data));
S
shawn_he 已提交
2124 2125 2126
});

let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
S
shawn_he 已提交
2127
tlsOneWay.bind({ address: '192.168.xxx.xxx', port: 8080, family: 1 }, err => {
S
shawn_he 已提交
2128 2129 2130 2131 2132 2133 2134 2135 2136
  if (err) {
    console.log('bind fail');
    return;
  }
  console.log('bind success');
});
let oneWayOptions = {
  address: {
    address: "192.168.xxx.xxx",
S
shawn_he 已提交
2137
    port: 8080,
S
shawn_he 已提交
2138 2139 2140
    family: 1,
  },
  secureOptions: {
S
shawn_he 已提交
2141
    ca: ["xxxx", "xxxx"],
S
shawn_he 已提交
2142 2143 2144 2145
    cipherSuite: "AES256-SHA256",
  },
};
tlsOneWay.connect(oneWayOptions, (err, data) => {
S
shawn_he 已提交
2146
  console.error("connect callback error" + err);
S
shawn_he 已提交
2147
  console.log(JSON.stringify(data));
S
shawn_he 已提交
2148 2149 2150 2151 2152
});
```

### connect<sup>9+</sup>

S
shawn_he 已提交
2153
connect(options: TLSConnectOptions): Promise\<void\>
S
shawn_he 已提交
2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168

Sets up a TLSSocket connection, and creates and initializes a TLS session after successful binding of the local IP address and port number of the TLSSocket connection. During this process, a TLS/SSL handshake is performed between the application and the server to implement data transmission. Both two-way and one-way authentication modes are supported. This API uses a promise to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                  | Mandatory| Description|
| -------- | --------------------------------------| ----| --------------- |
| options  | [TLSConnectOptions](#tlsconnectoptions9) | Yes  | Parameters required for the connection.|

**Return value**

| Type                                       | Description                         |
| ------------------------------------------- | ----------------------------- |
S
shawn_he 已提交
2169
| Promise\<void\>                              | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
S
shawn_he 已提交
2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194

**Error codes**

| ID| Error Message                                     |
| ------- | -------------------------------------------- |
| 401     | Parameter error.                             |
| 2303104 | Interrupted system call.                     |
| 2303109 | Bad file number.                             |
| 2303111 | Resource temporarily unavailable try again.  |
| 2303188 | Socket operation on non-socket.              |
| 2303191 | Protocol wrong type for socket.              |
| 2303198 | Address already in use.                      |
| 2303199 | Cannot assign requested address.             |
| 2303210 | Connection timed out.                        |
| 2303501 | SSL is null.                                 |
| 2303502 | Error in tls reading.                        |
| 2303503 | Error in tls writing                         |
| 2303505 | Error occurred in the tls system call.       |
| 2303506 | Error clearing tls connection.               |
| 2300002 | System internal error.                       |

**Example**

```js
let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication
S
shawn_he 已提交
2195
tlsTwoWay.bind({ address: '192.168.xxx.xxx', port: 8080, family: 1 }, err => {
S
shawn_he 已提交
2196 2197 2198 2199 2200 2201 2202 2203 2204 2205
  if (err) {
    console.log('bind fail');
    return;
  }
  console.log('bind success');
});
let options = {
  ALPNProtocols: ["spdy/1", "http/1.1"],
  address: {
    address: "xxxx",
S
shawn_he 已提交
2206
    port: 8080,
S
shawn_he 已提交
2207 2208 2209 2210 2211 2212
    family: 1,
  },
  secureOptions: {
    key: "xxxx",
    cert: "xxxx",
    ca: ["xxxx"],
S
shawn_he 已提交
2213
    password: "xxxx",
S
shawn_he 已提交
2214 2215 2216 2217 2218 2219 2220
    protocols: [socket.Protocol.TLSv12],
    useRemoteCipherPrefer: true,
    signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
    cipherSuite: "AES256-SHA256",
  },
};
tlsTwoWay.connect(options).then(data => {
S
shawn_he 已提交
2221
  console.log(JSON.stringify(data));
S
shawn_he 已提交
2222 2223 2224 2225 2226
}).catch(err => {
  console.error(err);
});

let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
S
shawn_he 已提交
2227
tlsOneWay.bind({ address: '192.168.xxx.xxx', port: 8080, family: 1 }, err => {
S
shawn_he 已提交
2228 2229 2230 2231 2232 2233 2234 2235 2236
  if (err) {
    console.log('bind fail');
    return;
  }
  console.log('bind success');
});
let oneWayOptions = {
  address: {
    address: "192.168.xxx.xxx",
S
shawn_he 已提交
2237
    port: 8080,
S
shawn_he 已提交
2238 2239 2240
    family: 1,
  },
  secureOptions: {
S
shawn_he 已提交
2241
    ca: ["xxxx", "xxxx"],
S
shawn_he 已提交
2242 2243 2244 2245
    cipherSuite: "AES256-SHA256",
  },
};
tlsOneWay.connect(oneWayOptions).then(data => {
S
shawn_he 已提交
2246
  console.log(JSON.stringify(data));
S
shawn_he 已提交
2247 2248 2249 2250 2251 2252 2253
}).catch(err => {
  console.error(err);
});
```

### getRemoteAddress<sup>9+</sup>

S
shawn_he 已提交
2254
getRemoteAddress(callback: AsyncCallback\<NetAddress\>): void
S
shawn_he 已提交
2255 2256 2257 2258 2259 2260 2261 2262 2263

Obtains the remote address of a TLSSocket connection. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                             | Mandatory| Description      |
| -------- | ------------------------------------------------- | ---- | ---------- |
S
shawn_he 已提交
2264
| callback | AsyncCallback\<[NetAddress](#netaddress)\> | Yes  | Callback used to return the result. If the operation is successful, the remote address is returned. If the operation fails, an error message is returned.|
S
shawn_he 已提交
2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286

**Error codes**

| ID| Error Message                       |
| ------- | -----------------------------  |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error.         |

**Example**

```js
tls.getRemoteAddress((err, data) => {
  if (err) {
    console.log('getRemoteAddress fail');
    return;
  }
  console.log('getRemoteAddress success:' + JSON.stringify(data));
});
```

### getRemoteAddress<sup>9+</sup>

S
shawn_he 已提交
2287
getRemoteAddress(): Promise\<NetAddress\>
S
shawn_he 已提交
2288 2289 2290 2291 2292 2293 2294 2295

Obtains the remote address of a TLSSocket connection. This API uses a promise to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Return value**

| Type                                       | Description                                       |
S
shawn_he 已提交
2296
| :------------------------------------------ | :------------------------------------------ |
S
shawn_he 已提交
2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318
| Promise\<[NetAddress](#netaddress)> | Promise used to return the result. If the operation fails, an error message is returned.|

**Error codes**

| ID| Error Message                       |
| ------- | ------------------------------ |
| 2303188 | Socket operation on non-socket.|
| 2300002 | System internal error.         |

**Example**

```js
let promise = tls.getRemoteAddress();
promise.then(() => {
  console.log('getRemoteAddress success');
}).catch(err => {
  console.log('getRemoteAddress fail');
});
```

### getCertificate<sup>9+</sup>

S
shawn_he 已提交
2319
getCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)\>): void
S
shawn_he 已提交
2320 2321 2322 2323 2324 2325 2326 2327 2328

Obtains the local digital certificate after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                  | Mandatory| Description|
| -------- | ----------------------------------------| ---- | ---------------|
S
shawn_he 已提交
2329
| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)\>    | Yes  | Callback used to return the result. If the operation is successful, the local certificate is returned. If the operation fails, an error message is returned.|
S
shawn_he 已提交
2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352

**Error codes**

| ID| Error Message                       |
| ------- | ------------------------------ |
| 2303501 | SSL is null.                   |
| 2303504 | Error looking up x509.         |
| 2300002 | System internal error.         |

**Example**

```js
tls.getCertificate((err, data) => {
  if (err) {
    console.log("getCertificate callback error = " + err);
  } else {
    console.log("getCertificate callback = " + data);
  }
});
```

### getCertificate<sup>9+</sup>

S
shawn_he 已提交
2353
getCertificate():Promise\<[X509CertRawData](#x509certrawdata9)\>
S
shawn_he 已提交
2354 2355 2356 2357 2358 2359 2360

Obtains the local digital certificate after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses a promise to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Return value**

S
shawn_he 已提交
2361
| Type           | Description                 |
S
shawn_he 已提交
2362
| -------------- | -------------------- |
S
shawn_he 已提交
2363
| Promise\<[X509CertRawData](#x509certrawdata9)\> | Promise used to return the result. If the operation fails, an error message is returned.|
S
shawn_he 已提交
2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384

**Error codes**

| ID| Error Message                       |
| ------- | ------------------------------ |
| 2303501 | SSL is null.                   |
| 2303504 | Error looking up x509.         |
| 2300002 | System internal error.         |

**Example**

```js
tls.getCertificate().then(data => {
  console.log(data);
}).catch(err => {
  console.error(err);
});
```

### getRemoteCertificate<sup>9+</sup>

S
shawn_he 已提交
2385
getRemoteCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)\>): void
S
shawn_he 已提交
2386 2387 2388 2389 2390 2391 2392 2393 2394

Obtains the digital certificate of the server after a TLSSocket connection is established. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name   | Type                                   | Mandatory | Description          |
| -------- | ----------------------------------------| ---- | ---------------|
S
shawn_he 已提交
2395
| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)\>  | Yes  | Callback used to return the result. If the operation fails, an error message is returned.|
S
shawn_he 已提交
2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417

**Error codes**

| ID| Error Message                       |
| ------- | ------------------------------ |
| 2303501 | SSL is null.                   |
| 2300002 | System internal error.         |

**Example**

```js
tls.getRemoteCertificate((err, data) => {
  if (err) {
    console.log("getRemoteCertificate callback error = " + err);
  } else {
    console.log("getRemoteCertificate callback = " + data);
  }
});
```

### getRemoteCertificate<sup>9+</sup>

S
shawn_he 已提交
2418
getRemoteCertificate():Promise\<[X509CertRawData](#x509certrawdata9)\>
S
shawn_he 已提交
2419 2420 2421 2422 2423 2424 2425 2426 2427

Obtains the digital certificate of the server after a TLSSocket connection is established. This API uses a promise to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Return value**

| Type           | Description                 |
| -------------- | -------------------- |
S
shawn_he 已提交
2428
| Promise\<[X509CertRawData](#x509certrawdata9)\> | Promise used to return the result. If the operation fails, an error message is returned.|
S
shawn_he 已提交
2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448

**Error codes**

| ID| Error Message                       |
| ------- | ------------------------------ |
| 2303501 | SSL is null.                   |
| 2300002 | System internal error.         |

**Example**

```js
tls.getRemoteCertificate().then(data => {
  console.log(data);
}).catch(err => {
  console.error(err);
});
```

### getProtocol<sup>9+</sup>

S
shawn_he 已提交
2449
getProtocol(callback: AsyncCallback\<string\>): void
S
shawn_he 已提交
2450 2451 2452 2453 2454 2455 2456 2457 2458

Obtains the communication protocol version after a TLSSocket connection is established. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                      | Mandatory| Description          |
| -------- | ----------------------------------------| ---- | ---------------|
S
shawn_he 已提交
2459
| callback | AsyncCallback\<string\>                  | Yes  | Callback used to return the result. If the operation fails, an error message is returned.|
S
shawn_he 已提交
2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482

**Error codes**

| ID| Error Message                       |
| ------- | -----------------------------  |
| 2303501 | SSL is null.                   |
| 2303505 | Error occurred in the tls system call. |
| 2300002 | System internal error.         |

**Example**

```js
tls.getProtocol((err, data) => {
  if (err) {
    console.log("getProtocol callback error = " + err);
  } else {
    console.log("getProtocol callback = " + data);
  }
});
```

### getProtocol<sup>9+</sup>

S
shawn_he 已提交
2483
getProtocol():Promise\<string\>
S
shawn_he 已提交
2484 2485 2486 2487 2488 2489 2490 2491 2492

Obtains the communication protocol version after a TLSSocket connection is established. This API uses a promise to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Return value**

| Type           | Description                 |
| -------------- | -------------------- |
S
shawn_he 已提交
2493
| Promise\<string\> | Promise used to return the result. If the operation fails, an error message is returned.|
S
shawn_he 已提交
2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514

**Error codes**

| ID| Error Message                       |
| ------- | ------------------------------ |
| 2303501 | SSL is null.                   |
| 2303505 | Error occurred in the tls system call. |
| 2300002 | System internal error.         |

**Example**

```js
tls.getProtocol().then(data => {
  console.log(data);
}).catch(err => {
  console.error(err);
});
```

### getCipherSuite<sup>9+</sup>

S
shawn_he 已提交
2515
getCipherSuite(callback: AsyncCallback\<Array\<string\>\>): void
S
shawn_he 已提交
2516 2517 2518 2519 2520 2521 2522 2523 2524

Obtains the cipher suite negotiated by both communication parties after a TLSSocket connection is established. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                    | Mandatory| Description|
| -------- | ----------------------------------------| ---- | ---------------|
S
shawn_he 已提交
2525
| callback | AsyncCallback\<Array\<string\>\>          | Yes  | Callback used to return the result. If the operation fails, an error message is returned.|
S
shawn_he 已提交
2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549

**Error codes**

| ID| Error Message                       |
| ------- | ------------------------------ |
| 2303501 | SSL is null.                   |
| 2303502 | Error in tls reading.          |
| 2303505 | Error occurred in the tls system call. |
| 2300002 | System internal error.         |

**Example**

```js
tls.getCipherSuite((err, data) => {
  if (err) {
    console.log("getCipherSuite callback error = " + err);
  } else {
    console.log("getCipherSuite callback = " + data);
  }
});
```

### getCipherSuite<sup>9+</sup>

S
shawn_he 已提交
2550
getCipherSuite(): Promise\<Array\<string\>\>
S
shawn_he 已提交
2551 2552 2553 2554 2555 2556 2557 2558 2559

Obtains the cipher suite negotiated by both communication parties after a TLSSocket connection is established. This API uses a promise to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Return value**

| Type                   | Description                 |
| ---------------------- | --------------------- |
S
shawn_he 已提交
2560
| Promise\<Array\<string\>\> | Promise used to return the result. If the operation fails, an error message is returned.|
S
shawn_he 已提交
2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574

**Error codes**

| ID| Error Message                       |
| ------- | ------------------------------ |
| 2303501 | SSL is null.                   |
| 2303502 | Error in tls reading.          |
| 2303505 | Error occurred in the tls system call. |
| 2300002 | System internal error.         |

**Example**

```js
tls.getCipherSuite().then(data => {
S
shawn_he 已提交
2575
  console.log('getCipherSuite success:' + JSON.stringify(data));
S
shawn_he 已提交
2576 2577 2578 2579 2580 2581 2582
}).catch(err => {
  console.error(err);
});
```

### getSignatureAlgorithms<sup>9+</sup>

S
shawn_he 已提交
2583
getSignatureAlgorithms(callback: AsyncCallback\<Array\<string\>\>): void
S
shawn_he 已提交
2584 2585 2586 2587 2588 2589 2590 2591 2592

Obtains the signing algorithm negotiated by both communication parties after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                  | Mandatory| Description           |
| -------- | -------------------------------------| ---- | ---------------|
S
shawn_he 已提交
2593
| callback | AsyncCallback\<Array\<string\>\>         | Yes  | Callback used to return the result.  |
S
shawn_he 已提交
2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615

**Error codes**

| ID| Error Message                       |
| ------- | ------------------------------ |
| 2303501 | SSL is null.                   |
| 2300002 | System internal error.         |

**Example**

```js
tls.getSignatureAlgorithms((err, data) => {
  if (err) {
    console.log("getSignatureAlgorithms callback error = " + err);
  } else {
    console.log("getSignatureAlgorithms callback = " + data);
  }
});
```

### getSignatureAlgorithms<sup>9+</sup>

S
shawn_he 已提交
2616
getSignatureAlgorithms(): Promise\<Array\<string\>\>
S
shawn_he 已提交
2617 2618 2619 2620 2621 2622 2623 2624 2625

Obtains the signing algorithm negotiated by both communication parties after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses a promise to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Return value**

| Type                   | Description                 |
| ---------------------- | -------------------- |
S
shawn_he 已提交
2626
| Promise\<Array\<string\>\> | Promise used to return the result.|
S
shawn_he 已提交
2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638

**Error codes**

| ID| Error Message                       |
| ------- | ------------------------------ |
| 2303501 | SSL is null.                   |
| 2300002 | System internal error.         |

**Example**

```js
tls.getSignatureAlgorithms().then(data => {
S
shawn_he 已提交
2639
  console.log("getSignatureAlgorithms success" + data);
S
shawn_he 已提交
2640 2641 2642 2643 2644 2645 2646
}).catch(err => {
  console.error(err);
});
```

### send<sup>9+</sup>

S
shawn_he 已提交
2647
send(data: string, callback: AsyncCallback\<void\>): void
S
shawn_he 已提交
2648 2649 2650 2651 2652 2653 2654 2655 2656 2657

Sends a message to the server after a TLSSocket connection is established. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name   | Type                         | Mandatory| Description           |
| -------- | -----------------------------| ---- | ---------------|
|   data   | string                       | Yes  | Data content of the message to send.  |
S
shawn_he 已提交
2658
| callback | AsyncCallback\<void\>         | Yes  | Callback used to return the result. If the operation fails, an error message is returned.|
S
shawn_he 已提交
2659 2660 2661 2662 2663 2664 2665

**Error codes**

| ID| Error Message                                     |
| ------- | -------------------------------------------- |
| 401     | Parameter error.                             |
| 2303501 | SSL is null.                                 |
S
shawn_he 已提交
2666
| 2303503 | Error in tls writing.                         |
S
shawn_he 已提交
2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684
| 2303505 | Error occurred in the tls system call.       |
| 2303506 | Error clearing tls connection.               |
| 2300002 | System internal error.                       |

**Example**

```js
tls.send("xxxx", (err) => {
  if (err) {
    console.log("send callback error = " + err);
  } else {
    console.log("send success");
  }
});
```

### send<sup>9+</sup>

S
shawn_he 已提交
2685
send(data: string): Promise\<void\>
S
shawn_he 已提交
2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702

Sends a message to the server after a TLSSocket connection is established. This API uses a promise to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name   | Type                         | Mandatory| Description           |
| -------- | -----------------------------| ---- | ---------------|
|   data   | string                       | Yes  | Data content of the message to send.  |

**Error codes**

| ID| Error Message                                     |
| ------- | -------------------------------------------- |
| 401     | Parameter error.                             |
| 2303501 | SSL is null.                                 |
S
shawn_he 已提交
2703
| 2303503 | Error in tls writing.                         |
S
shawn_he 已提交
2704 2705 2706 2707 2708 2709 2710 2711
| 2303505 | Error occurred in the tls system call.       |
| 2303506 | Error clearing tls connection.               |
| 2300002 | System internal error.                       |

**Return value**

| Type          | Description                 |
| -------------- | -------------------- |
S
shawn_he 已提交
2712
| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.|
S
shawn_he 已提交
2713 2714 2715 2716

**Example**

```js
S
shawn_he 已提交
2717
tls.send("xxxx").then(() => {
S
shawn_he 已提交
2718 2719 2720 2721 2722 2723 2724 2725
  console.log("send success");
}).catch(err => {
  console.error(err);
});
```

### close<sup>9+</sup>

S
shawn_he 已提交
2726
close(callback: AsyncCallback\<void\>): void
S
shawn_he 已提交
2727 2728 2729 2730 2731 2732 2733 2734 2735

Closes a TLSSocket connection. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name   | Type                         | Mandatory| Description           |
| -------- | -----------------------------| ---- | ---------------|
S
shawn_he 已提交
2736
| callback | AsyncCallback\<void\>         | Yes  | Callback used to return the result. If the operation fails, an error message is returned.|
S
shawn_he 已提交
2737 2738 2739 2740 2741

**Error codes**

| ID| Error Message                                     |
| ------- | -------------------------------------------- |
S
shawn_he 已提交
2742
| 401 | Parameter error.                                 |
S
shawn_he 已提交
2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761
| 2303501 | SSL is null.                                 |
| 2303505 | Error occurred in the tls system call.       |
| 2303506 | Error clearing tls connection.               |
| 2300002 | System internal error.                       |

**Example**

```js
tls.close((err) => {
  if (err) {
    console.log("close callback error = " + err);
  } else {
    console.log("close success");
  }
});
```

### close<sup>9+</sup>

S
shawn_he 已提交
2762
close(): Promise\<void\>
S
shawn_he 已提交
2763 2764 2765 2766 2767 2768 2769 2770 2771

Closes a TLSSocket connection. This API uses a promise to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Return value**

| Type          | Description                 |
| -------------- | -------------------- |
S
shawn_he 已提交
2772
| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.|
S
shawn_he 已提交
2773 2774 2775 2776 2777

**Error codes**

| ID| Error Message                                     |
| ------- | -------------------------------------------- |
S
shawn_he 已提交
2778
| 401 | Parameter error.                                 |
S
shawn_he 已提交
2779 2780 2781 2782 2783 2784 2785 2786
| 2303501 | SSL is null.                                 |
| 2303505 | Error occurred in the tls system call.       |
| 2303506 | Error clearing tls connection.               |
| 2300002 | System internal error.                       |

**Example**

```js
S
shawn_he 已提交
2787
tls.close().then(() => {
S
shawn_he 已提交
2788
  console.log("close success");
S
shawn_he 已提交
2789
}).catch((err) => {
S
shawn_he 已提交
2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803
  console.error(err);
});
```

## TLSConnectOptions<sup>9+</sup>

Defines TLS connection options.

**System capability**: SystemCapability.Communication.NetStack

| Name         | Type                                    | Mandatory| Description           |
| -------------- | ------------------------------------- | ---  |-------------- |
| address        | [NetAddress](#netaddress)             | Yes |  Gateway address.      |
| secureOptions  | [TLSSecureOptions](#tlssecureoptions9) | Yes| TLS security options.|
S
shawn_he 已提交
2804
| ALPNProtocols  | Array\<string\>                         | No| ALPN protocol. The value range is ["spdy/1", "http/1.1"]. The default value is **[]**.     |
S
shawn_he 已提交
2805 2806 2807 2808 2809 2810 2811 2812 2813

## TLSSecureOptions<sup>9+</sup>

Defines TLS security options. The CA certificate is mandatory, and other parameters are optional. When **cert** (local certificate) and **key** (private key) are not empty, the two-way authentication mode is enabled. If **cert** or **key** is empty, one-way authentication is enabled.

**System capability**: SystemCapability.Communication.NetStack

| Name                | Type                                                   | Mandatory| Description                               |
| --------------------- | ------------------------------------------------------ | --- |----------------------------------- |
S
shawn_he 已提交
2814
| ca                    | string \| Array\<string\>                               | Yes| CA certificate of the server, which is used to authenticate the digital certificate of the server.|
S
shawn_he 已提交
2815 2816
| cert                  | string                                                  | No| Digital certificate of the local client.                |
| key                   | string                                                  | No| Private key of the local digital certificate.                  |
S
shawn_he 已提交
2817
| password                | string                                                  | No| Password for reading the private key.                     |
S
shawn_he 已提交
2818 2819 2820 2821
| protocols             | [Protocol](#protocol9) \|Array\<[Protocol](#protocol9)\> | No| TLS protocol version. The default value is **TLSv1.2**.                 |
| useRemoteCipherPrefer | boolean                                                 | No| Whether to use the remote cipher suite preferentially.       |
| signatureAlgorithms   | string                                                 | No| Signing algorithm used during communication. The default value is **""**.             |
| cipherSuite           | string                                                 | No| Cipher suite used during communication. The default value is **""**.             |
S
shawn_he 已提交
2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838

## Protocol<sup>9+</sup>

Enumerates TLS protocol versions.

**System capability**: SystemCapability.Communication.NetStack

| Name     |    Value   | Description               |
| --------- | --------- |------------------ |
| TLSv12    | "TLSv1.2" | TLSv1.2.|
| TLSv13    | "TLSv1.3" | TLSv1.3.|

## X509CertRawData<sup>9+</sup>

Defines the certificate raw data.

**System capability**: SystemCapability.Communication.NetStack