1# # @ohos.net.socket (Socket Connection) 2 3The **socket** module implements data transfer over TCPSocket, UDPSocket, WebSocket, and TLSSocket connections. 4 5> **NOTE** 6> 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. 8 9## Modules to Import 10 11```js 12import socket from '@ohos.net.socket'; 13``` 14 15## socket.constructUDPSocketInstance 16 17constructUDPSocketInstance(): UDPSocket 18 19Creates a **UDPSocket** object. 20 21**System capability**: SystemCapability.Communication.NetStack 22 23**Return value** 24 25| Type | Description | 26| :--------------------------------- | :---------------------- | 27| [UDPSocket](#udpsocket) | **UDPSocket** object.| 28 29**Example** 30 31```js 32let udp = socket.constructUDPSocketInstance(); 33``` 34 35## UDPSocket 36 37Defines a **UDPSocket** connection. Before invoking UDPSocket APIs, you need to call [socket.constructUDPSocketInstance](#socketconstructudpsocketinstance) to create a **UDPSocket** object. 38 39### bind 40 41bind(address: NetAddress, callback: AsyncCallback\<void\>): void 42 43Binds 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. 44 45**Required permissions**: ohos.permission.INTERNET 46 47**System capability**: SystemCapability.Communication.NetStack 48 49**Parameters** 50 51| Name | Type | Mandatory| Description | 52| -------- | ---------------------------------- | ---- | ------------------------------------------------------ | 53| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| 54| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | 55 56**Error codes** 57 58| ID| Error Message | 59| ------- | ----------------------- | 60| 401 | Parameter error. | 61| 201 | Permission denied. | 62 63**Example** 64 65```js 66let udp = socket.constructUDPSocketInstance(); 67udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { 68 if (err) { 69 console.log('bind fail'); 70 return; 71 } 72 console.log('bind success'); 73}) 74``` 75 76### bind 77 78bind(address: NetAddress): Promise\<void\> 79 80Binds 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. 81 82**Required permissions**: ohos.permission.INTERNET 83 84**System capability**: SystemCapability.Communication.NetStack 85 86**Parameters** 87 88| Name | Type | Mandatory| Description | 89| ------- | ---------------------------------- | ---- | ------------------------------------------------------ | 90| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| 91 92**Error codes** 93 94| ID| Error Message | 95| ------- | ----------------------- | 96| 401 | Parameter error. | 97| 201 | Permission denied. | 98 99**Return value** 100 101| Type | Description | 102| :-------------- | :----------------------------------------- | 103| Promise\<void\> | Promise used to return the result.| 104 105**Example** 106 107```js 108let udp = socket.constructUDPSocketInstance(); 109let promise = udp.bind({address: '192.168.xx.xxx', port: 8080, family: 1}); 110promise.then(() => { 111 console.log('bind success'); 112}).catch(err => { 113 console.log('bind fail'); 114}); 115``` 116 117### send 118 119send(options: UDPSendOptions, callback: AsyncCallback\<void\>): void 120 121Sends data over a UDPSocket connection. This API uses an asynchronous callback to return the result. 122 123Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and port. 124 125**Required permissions**: ohos.permission.INTERNET 126 127**System capability**: SystemCapability.Communication.NetStack 128 129**Parameters** 130 131| Name | Type | Mandatory| Description | 132| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | 133| options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).| 134| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | 135 136**Error codes** 137 138| ID| Error Message | 139| ------- | ----------------------- | 140| 401 | Parameter error. | 141| 201 | Permission denied. | 142 143**Example** 144 145```js 146let udp = socket.constructUDPSocketInstance(); 147udp.send({ 148 data: 'Hello, server!', 149 address: { 150 address: '192.168.xx.xxx', 151 port: xxxx, 152 family: 1 153 } 154}, err => { 155 if (err) { 156 console.log('send fail'); 157 return; 158 } 159 console.log('send success'); 160}) 161``` 162 163### send 164 165send(options: UDPSendOptions): Promise\<void\> 166 167Sends data over a UDPSocket connection. This API uses a promise to return the result. 168 169Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and port. 170 171**Required permissions**: ohos.permission.INTERNET 172 173**System capability**: SystemCapability.Communication.NetStack 174 175**Parameters** 176 177| Name | Type | Mandatory| Description | 178| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | 179| options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).| 180 181**Error codes** 182 183| ID| Error Message | 184| ------- | ----------------------- | 185| 401 | Parameter error. | 186| 201 | Permission denied. | 187 188**Return value** 189 190| Type | Description | 191| :-------------- | :--------------------------------------------- | 192| Promise\<void\> | Promise used to return the result.| 193 194**Example** 195 196```js 197let udp = socket.constructUDPSocketInstance(); 198let promise = udp.send({ 199 data: 'Hello, server!', 200 address: { 201 address: '192.168.xx.xxx', 202 port: xxxx, 203 family: 1 204 } 205}); 206promise.then(() => { 207 console.log('send success'); 208}).catch(err => { 209 console.log('send fail'); 210}); 211``` 212 213### close 214 215close(callback: AsyncCallback\<void\>): void 216 217Closes a UDPSocket connection. This API uses an asynchronous callback to return the result. 218 219**Required permissions**: ohos.permission.INTERNET 220 221**System capability**: SystemCapability.Communication.NetStack 222 223**Parameters** 224 225| Name | Type | Mandatory| Description | 226| -------- | --------------------- | ---- | ---------- | 227| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.| 228 229**Example** 230 231```js 232let udp = socket.constructUDPSocketInstance(); 233udp.close(err => { 234 if (err) { 235 console.log('close fail'); 236 return; 237 } 238 console.log('close success'); 239}) 240``` 241 242### close 243 244close(): Promise\<void\> 245 246Closes a UDPSocket connection. This API uses a promise to return the result. 247 248**Required permissions**: ohos.permission.INTERNET 249 250**System capability**: SystemCapability.Communication.NetStack 251 252**Return value** 253 254| Type | Description | 255| :-------------- | :----------------------------------------- | 256| Promise\<void\> | Promise used to return the result.| 257 258**Example** 259 260```js 261let udp = socket.constructUDPSocketInstance(); 262let promise = udp.close(); 263promise.then(() => { 264 console.log('close success'); 265}).catch(err => { 266 console.log('close fail'); 267}); 268``` 269 270### getState 271 272getState(callback: AsyncCallback\<SocketStateBase\>): void 273 274Obtains the status of the UDPSocket connection. This API uses an asynchronous callback to return the result. 275 276> **NOTE** 277> This API can be called only after **bind** is successfully called. 278 279**Required permissions**: ohos.permission.INTERNET 280 281**System capability**: SystemCapability.Communication.NetStack 282 283**Parameters** 284 285| Name | Type | Mandatory| Description | 286| -------- | ------------------------------------------------------ | ---- | ---------- | 287| callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | Yes | Callback used to return the result.| 288 289**Error codes** 290 291| ID| Error Message | 292| ------- | ----------------------- | 293| 201 | Permission denied. | 294 295**Example** 296 297```js 298let udp = socket.constructUDPSocketInstance(); 299udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { 300 if (err) { 301 console.log('bind fail'); 302 return; 303 } 304 console.log('bind success'); 305 udp.getState((err, data) => { 306 if (err) { 307 console.log('getState fail'); 308 return; 309 } 310 console.log('getState success:' + JSON.stringify(data)); 311 }) 312}) 313``` 314 315### getState 316 317getState(): Promise\<SocketStateBase\> 318 319Obtains the status of the UDPSocket connection. This API uses a promise to return the result. 320 321> **NOTE** 322> This API can be called only after **bind** is successfully called. 323 324**Required permissions**: ohos.permission.INTERNET 325 326**System capability**: SystemCapability.Communication.NetStack 327 328**Return value** 329 330| Type | Description | 331| :----------------------------------------------- | :----------------------------------------- | 332| Promise\<[SocketStateBase](#socketstatebase)\> | Promise used to return the result.| 333 334**Example** 335 336```js 337let udp = socket.constructUDPSocketInstance(); 338let promise = udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}); 339promise.then(err => { 340 if (err) { 341 console.log('bind fail'); 342 return; 343 } 344 console.log('bind success'); 345 let promise = udp.getState(); 346 promise.then(data => { 347 console.log('getState success:' + JSON.stringify(data)); 348 }).catch(err => { 349 console.log('getState fail'); 350 }); 351}); 352``` 353 354### setExtraOptions 355 356setExtraOptions(options: UDPExtraOptions, callback: AsyncCallback\<void\>): void 357 358Sets other attributes of the UDPSocket connection. This API uses an asynchronous callback to return the result. 359 360> **NOTE** 361> This API can be called only after **bind** is successfully called. 362 363**Required permissions**: ohos.permission.INTERNET 364 365**System capability**: SystemCapability.Communication.NetStack 366 367**Parameters** 368 369| Name | Type | Mandatory| Description | 370| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | 371| options | [UDPExtraOptions](#udpextraoptions) | Yes | Other properties of the UDPSocket connection. For details, see [UDPExtraOptions](#udpextraoptions).| 372| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | 373 374**Error codes** 375 376| ID| Error Message | 377| ------- | ----------------------- | 378| 401 | Parameter error. | 379| 201 | Permission denied. | 380 381**Example** 382 383```js 384let udp = socket.constructUDPSocketInstance(); 385udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { 386 if (err) { 387 console.log('bind fail'); 388 return; 389 } 390 console.log('bind success'); 391 udp.setExtraOptions({ 392 receiveBufferSize: 1000, 393 sendBufferSize: 1000, 394 reuseAddress: false, 395 socketTimeout: 6000, 396 broadcast: true 397 }, err => { 398 if (err) { 399 console.log('setExtraOptions fail'); 400 return; 401 } 402 console.log('setExtraOptions success'); 403 }) 404}) 405``` 406 407### setExtraOptions 408 409setExtraOptions(options: UDPExtraOptions): Promise\<void\> 410 411Sets other attributes of the UDPSocket connection. This API uses a promise to return the result. 412 413> **NOTE** 414> This API can be called only after **bind** is successfully called. 415 416**Required permissions**: ohos.permission.INTERNET 417 418**System capability**: SystemCapability.Communication.NetStack 419 420**Parameters** 421 422| Name | Type | Mandatory| Description | 423| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | 424| options | [UDPExtraOptions](#udpextraoptions) | Yes | Other properties of the UDPSocket connection. For details, see [UDPExtraOptions](#udpextraoptions).| 425 426**Return value** 427 428| Type | Description | 429| :-------------- | :--------------------------------------------------- | 430| Promise\<void\> | Promise used to return the result.| 431 432**Error codes** 433 434| ID| Error Message | 435| ------- | ----------------------- | 436| 401 | Parameter error. | 437| 201 | Permission denied. | 438 439**Example** 440 441```js 442let udp = socket.constructUDPSocketInstance(); 443let promise = udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}); 444promise.then(() => { 445 console.log('bind success'); 446 let promise1 = udp.setExtraOptions({ 447 receiveBufferSize: 1000, 448 sendBufferSize: 1000, 449 reuseAddress: false, 450 socketTimeout: 6000, 451 broadcast: true 452 }); 453 promise1.then(() => { 454 console.log('setExtraOptions success'); 455 }).catch(err => { 456 console.log('setExtraOptions fail'); 457 }); 458}).catch(err => { 459 console.log('bind fail'); 460}); 461``` 462 463### on('message') 464 465on(type: 'message', callback: Callback\<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void 466 467Enables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result. 468 469**System capability**: SystemCapability.Communication.NetStack 470 471**Parameters** 472 473| Name | Type | Mandatory| Description | 474| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 475| type | string | Yes | Type of the event to subscribe to.<br /> **message**: message receiving event| 476| callback | Callback\<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}\> | Yes | Callback used to return the result. | 477 478**Example** 479 480```js 481let udp = socket.constructUDPSocketInstance(); 482udp.on('message', value => { 483 console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); 484}); 485``` 486 487### off('message') 488 489off(type: 'message', callback?: Callback\<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void 490 491Disables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result. 492 493> **NOTE** 494> 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. 495 496**System capability**: SystemCapability.Communication.NetStack 497 498**Parameters** 499 500| Name | Type | Mandatory| Description | 501| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 502| type | string | Yes | Type of the event to subscribe to.<br /> **message**: message receiving event| 503| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No | Callback used to return the result. | 504 505**Example** 506 507```js 508let udp = socket.constructUDPSocketInstance(); 509let callback = value => { 510 console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); 511} 512udp.on('message', callback); 513// 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. 514udp.off('message', callback); 515udp.off('message'); 516``` 517 518### on('listening' | 'close') 519 520on(type: 'listening' | 'close', callback: Callback\<void\>): void 521 522Enables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result. 523 524**System capability**: SystemCapability.Communication.NetStack 525 526**Parameters** 527 528| Name | Type | Mandatory| Description | 529| -------- | ---------------- | ---- | ------------------------------------------------------------ | 530| type | string | Yes | Type of the event to subscribe to.<br /><br>- **listening**: data packet message event<br>- **close**: close event| 531| callback | Callback\<void\> | Yes | Callback used to return the result. | 532 533**Example** 534 535```js 536let udp = socket.constructUDPSocketInstance(); 537udp.on('listening', () => { 538 console.log("on listening success"); 539}); 540udp.on('close', () => { 541 console.log("on close success"); 542}); 543``` 544 545### off('listening' | 'close') 546 547off(type: 'listening' | 'close', callback?: Callback\<void\>): void 548 549Disables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result. 550 551> **NOTE** 552> 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. 553 554**System capability**: SystemCapability.Communication.NetStack 555 556**Parameters** 557 558| Name | Type | Mandatory| Description | 559| -------- | ---------------- | ---- | ------------------------------------------------------------ | 560| type | string | Yes | Type of the event to subscribe to.<br>- **listening**: data packet message event<br>- **close**: close event| 561| callback | Callback\<void\> | No | Callback used to return the result. | 562 563**Example** 564 565```js 566let udp = socket.constructUDPSocketInstance(); 567let callback1 = () => { 568 console.log("on listening, success"); 569} 570udp.on('listening', callback1); 571// 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. 572udp.off('listening', callback1); 573udp.off('listening'); 574let callback2 = () => { 575 console.log("on close, success"); 576} 577udp.on('close', callback2); 578// 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. 579udp.off('close', callback2); 580udp.off('close'); 581``` 582 583### on('error') 584 585on(type: 'error', callback: ErrorCallback): void 586 587Enables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result. 588 589**System capability**: SystemCapability.Communication.NetStack 590 591**Parameters** 592 593| Name | Type | Mandatory| Description | 594| -------- | ------------- | ---- | ------------------------------------ | 595| type | string | Yes | Type of the event to subscribe to.<br /> **error**: error event| 596| callback | ErrorCallback | Yes | Callback used to return the result. | 597 598**Example** 599 600```js 601let udp = socket.constructUDPSocketInstance(); 602udp.on('error', err => { 603 console.log("on error, err:" + JSON.stringify(err)) 604}); 605``` 606 607### off('error') 608 609off(type: 'error', callback?: ErrorCallback): void 610 611Disables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result. 612 613> **NOTE** 614> 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. 615 616**System capability**: SystemCapability.Communication.NetStack 617 618**Parameters** 619 620| Name | Type | Mandatory| Description | 621| -------- | ------------- | ---- | ------------------------------------ | 622| type | string | Yes | Type of the event to subscribe to.<br /> **error**: error event| 623| callback | ErrorCallback | No | Callback used to return the result. | 624 625**Example** 626 627```js 628let udp = socket.constructUDPSocketInstance(); 629let callback = err => { 630 console.log("on error, err:" + JSON.stringify(err)); 631} 632udp.on('error', callback); 633// 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. 634udp.off('error', callback); 635udp.off('error'); 636``` 637 638## NetAddress 639 640Defines the destination address. 641 642**System capability**: SystemCapability.Communication.NetStack 643 644| Name | Type | Mandatory| Description | 645| ------- | ------ | ---- | ------------------------------------------------------------ | 646| address | string | Yes | Bound IP address. | 647| port | number | No | Port number. The value ranges from **0** to **65535**. If this parameter is not specified, the system randomly allocates a port. | 648| family | number | No | Network protocol type.<br>- **1**: IPv4<br>- **2**: IPv6<br>The default value is **1**.| 649 650## UDPSendOptions 651 652Defines the parameters for sending data over the UDPSocket connection. 653 654**System capability**: SystemCapability.Communication.NetStack 655 656| Name | Type | Mandatory| Description | 657| ------- | ---------------------------------- | ---- | -------------- | 658| data | string \| ArrayBuffer<sup>7+</sup> | Yes | Data to send. | 659| address | [NetAddress](#netaddress) | Yes | Destination address.| 660 661## UDPExtraOptions 662 663Defines other properties of the UDPSocket connection. 664 665**System capability**: SystemCapability.Communication.NetStack 666 667| Name | Type | Mandatory| Description | 668| ----------------- | ------- | ---- | -------------------------------- | 669| broadcast | boolean | No | Whether to send broadcast messages. The default value is **false**. | 670| receiveBufferSize | number | No | Size of the receive buffer, in bytes. | 671| sendBufferSize | number | No | Size of the send buffer, in bytes. | 672| reuseAddress | boolean | No | Whether to reuse addresses. The default value is **false**. | 673| socketTimeout | number | No | Timeout duration of the UDPSocket connection, in ms.| 674 675## SocketStateBase 676 677Defines the status of the socket connection. 678 679**System capability**: SystemCapability.Communication.NetStack 680 681| Name | Type | Mandatory| Description | 682| ----------- | ------- | ---- | ---------- | 683| isBound | boolean | Yes | Whether the connection is in the bound state.| 684| isClose | boolean | Yes | Whether the connection is in the closed state.| 685| isConnected | boolean | Yes | Whether the connection is in the connected state.| 686 687## SocketRemoteInfo 688 689Defines information about the socket connection. 690 691**System capability**: SystemCapability.Communication.NetStack 692 693| Name | Type | Mandatory| Description | 694| ------- | ------ | ---- | ------------------------------------------------------------ | 695| address | string | Yes | Bound IP address. | 696| family | string | Yes | Network protocol type.<br>- IPv4<br>- IPv6<br>The default value is **IPv4**.| 697| port | number | Yes | Port number. The value ranges from **0** to **65535**. | 698| size | number | Yes | Length of the server response message, in bytes. | 699 700## Description of UDP Error Codes 701 702The UDP error code mapping is in the format of 2301000 + Linux kernel error code. 703 704For details about error codes, see [Socket Error Codes](../errorcodes/errorcode-net-socket.md). 705 706## socket.constructTCPSocketInstance 707 708constructTCPSocketInstance(): TCPSocket 709 710Creates a **TCPSocket** object. 711 712**System capability**: SystemCapability.Communication.NetStack 713 714**Return value** 715 716| Type | Description | 717 | :--------------------------------- | :---------------------- | 718| [TCPSocket](#tcpsocket) | **TCPSocket** object.| 719 720**Example** 721 722```js 723let tcp = socket.constructTCPSocketInstance(); 724``` 725 726## TCPSocket 727 728Defines a TCPSocket connection. Before invoking TCPSocket APIs, you need to call [socket.constructTCPSocketInstance](#socketconstructtcpsocketinstance) to create a **TCPSocket** object. 729 730### bind 731 732bind(address: NetAddress, callback: AsyncCallback\<void\>): void 733 734Binds 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. 735 736**Required permissions**: ohos.permission.INTERNET 737 738**System capability**: SystemCapability.Communication.NetStack 739 740**Parameters** 741 742| Name | Type | Mandatory| Description | 743| -------- | ---------------------------------- | ---- | ------------------------------------------------------ | 744| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| 745| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | 746 747**Error codes** 748 749| ID| Error Message | 750| ------- | ----------------------- | 751| 401 | Parameter error. | 752| 201 | Permission denied. | 753 754**Example** 755 756```js 757let tcp = socket.constructTCPSocketInstance(); 758tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { 759 if (err) { 760 console.log('bind fail'); 761 return; 762 } 763 console.log('bind success'); 764}) 765``` 766 767### bind 768 769bind(address: NetAddress): Promise\<void\> 770 771Binds 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. 772 773**Required permissions**: ohos.permission.INTERNET 774 775**System capability**: SystemCapability.Communication.NetStack 776 777**Parameters** 778 779| Name | Type | Mandatory| Description | 780| ------- | ---------------------------------- | ---- | ------------------------------------------------------ | 781| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| 782 783**Return value** 784 785| Type | Description | 786| :-------------- | :------------------------------------------------------- | 787| Promise\<void\> | Promise used to return the result.| 788 789**Error codes** 790 791| ID| Error Message | 792| ------- | ----------------------- | 793| 401 | Parameter error. | 794| 201 | Permission denied. | 795 796**Example** 797 798```js 799let tcp = socket.constructTCPSocketInstance(); 800let promise = tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}); 801promise.then(() => { 802 console.log('bind success'); 803}).catch(err => { 804 console.log('bind fail'); 805}); 806``` 807 808### connect 809 810connect(options: TCPConnectOptions, callback: AsyncCallback\<void\>): void 811 812Sets up a connection to the specified IP address and port number. This API uses an asynchronous callback to return the result. 813 814> **NOTE** 815> This API can be called only after **bind** is successfully called. 816 817**Required permissions**: ohos.permission.INTERNET 818 819**System capability**: SystemCapability.Communication.NetStack 820 821**Parameters** 822 823| Name | Type | Mandatory| Description | 824| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | 825| options | [TCPConnectOptions](#tcpconnectoptions) | Yes | TCPSocket connection parameters. For details, see [TCPConnectOptions](#tcpconnectoptions).| 826| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | 827 828**Error codes** 829 830| ID| Error Message | 831| ------- | ----------------------- | 832| 401 | Parameter error. | 833| 201 | Permission denied. | 834 835**Example** 836 837```js 838let tcp = socket.constructTCPSocketInstance(); 839tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}, err => { 840 if (err) { 841 console.log('connect fail'); 842 return; 843 } 844 console.log('connect success'); 845}) 846``` 847 848### connect 849 850connect(options: TCPConnectOptions): Promise\<void\> 851 852Sets up a connection to the specified IP address and port number. This API uses a promise to return the result. 853 854**Required permissions**: ohos.permission.INTERNET 855 856**System capability**: SystemCapability.Communication.NetStack 857 858**Parameters** 859 860| Name | Type | Mandatory| Description | 861| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | 862| options | [TCPConnectOptions](#tcpconnectoptions) | Yes | TCPSocket connection parameters. For details, see [TCPConnectOptions](#tcpconnectoptions).| 863 864**Return value** 865 866| Type | Description | 867| :-------------- | :--------------------------------------------------------- | 868| Promise\<void\> | Promise used to return the result.| 869 870**Error codes** 871 872| ID| Error Message | 873| ------- | ----------------------- | 874| 401 | Parameter error. | 875| 201 | Permission denied. | 876 877**Example** 878 879```js 880let tcp = socket.constructTCPSocketInstance(); 881let promise = tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}); 882promise.then(() => { 883 console.log('connect success') 884}).catch(err => { 885 console.log('connect fail'); 886}); 887``` 888 889### send 890 891send(options: TCPSendOptions, callback: AsyncCallback\<void\>): void 892 893Sends data over a TCPSocket connection. This API uses an asynchronous callback to return the result. 894 895> **NOTE** 896> This API can be called only after **connect** is successfully called. 897 898**Required permissions**: ohos.permission.INTERNET 899 900**System capability**: SystemCapability.Communication.NetStack 901 902**Parameters** 903 904| Name | Type | Mandatory| Description | 905| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | 906| options | [TCPSendOptions](#tcpsendoptions) | Yes | Parameters for sending data over the TCPSocket connection. For details, see [TCPSendOptions](#tcpsendoptions).| 907| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | 908 909**Error codes** 910 911| ID| Error Message | 912| ------- | ----------------------- | 913| 401 | Parameter error. | 914| 201 | Permission denied. | 915 916**Example** 917 918```js 919let tcp = socket.constructTCPSocketInstance(); 920tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}, () => { 921 console.log('connect success'); 922 tcp.send({ 923 data: 'Hello, server!' 924 // Encoding is omitted here. The UTF-8 encoding format is used by default. 925 }, err => { 926 if (err) { 927 console.log('send fail'); 928 return; 929 } 930 console.log('send success'); 931 }) 932}) 933``` 934 935### send 936 937send(options: TCPSendOptions): Promise\<void\> 938 939Sends data over a TCPSocket connection. This API uses a promise to return the result. 940 941> **NOTE** 942> This API can be called only after **connect** is successfully called. 943 944**Required permissions**: ohos.permission.INTERNET 945 946**System capability**: SystemCapability.Communication.NetStack 947 948**Parameters** 949 950| Name | Type | Mandatory| Description | 951| ------- | --------------------------------------- | ---- | ------------------------------------------------------------ | 952| options | [TCPSendOptions](#tcpsendoptions) | Yes | Parameters for sending data over the TCPSocket connection. For details, see [TCPSendOptions](#tcpsendoptions).| 953 954**Return value** 955 956| Type | Description | 957| :-------------- | :------------------------------------------------- | 958| Promise\<void\> | Promise used to return the result.| 959 960**Error codes** 961 962| ID| Error Message | 963| ------- | ----------------------- | 964| 401 | Parameter error. | 965| 201 | Permission denied. | 966 967**Example** 968 969```js 970let tcp = socket.constructTCPSocketInstance(); 971let promise1 = tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}); 972promise1.then(() => { 973 console.log('connect success'); 974 let promise2 = tcp.send({ 975 data: 'Hello, server!' 976 }); 977 promise2.then(() => { 978 console.log('send success'); 979 }).catch(err => { 980 console.log('send fail'); 981 }); 982}).catch(err => { 983 console.log('connect fail'); 984}); 985``` 986 987### close 988 989close(callback: AsyncCallback\<void\>): void 990 991Closes a TCPSocket connection. This API uses an asynchronous callback to return the result. 992 993**Required permissions**: ohos.permission.INTERNET 994 995**System capability**: SystemCapability.Communication.NetStack 996 997**Parameters** 998 999| Name | Type | Mandatory| Description | 1000| -------- | --------------------- | ---- | ---------- | 1001| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.| 1002 1003**Error codes** 1004 1005| ID| Error Message | 1006| ------- | ----------------------- | 1007| 201 | Permission denied. | 1008 1009**Example** 1010 1011```js 1012let tcp = socket.constructTCPSocketInstance(); 1013tcp.close(err => { 1014 if (err) { 1015 console.log('close fail'); 1016 return; 1017 } 1018 console.log('close success'); 1019}) 1020``` 1021 1022### close 1023 1024close(): Promise\<void\> 1025 1026Closes a TCPSocket connection. This API uses a promise to return the result. 1027 1028**Required permissions**: ohos.permission.INTERNET 1029 1030**System capability**: SystemCapability.Communication.NetStack 1031 1032**Return value** 1033 1034| Type | Description | 1035| :-------------- | :----------------------------------------- | 1036| Promise\<void\> | Promise used to return the result.| 1037 1038**Error codes** 1039 1040| ID| Error Message | 1041| ------- | ----------------------- | 1042| 201 | Permission denied. | 1043 1044**Example** 1045 1046```js 1047let tcp = socket.constructTCPSocketInstance(); 1048let promise = tcp.close(); 1049promise.then(() => { 1050 console.log('close success'); 1051}).catch(err => { 1052 console.log('close fail'); 1053}); 1054``` 1055 1056### getRemoteAddress 1057 1058getRemoteAddress(callback: AsyncCallback\<NetAddress\>): void 1059 1060Obtains the remote address of a socket connection. This API uses an asynchronous callback to return the result. 1061 1062> **NOTE** 1063> This API can be called only after **connect** is successfully called. 1064 1065**Required permissions**: ohos.permission.INTERNET 1066 1067**System capability**: SystemCapability.Communication.NetStack 1068 1069**Parameters** 1070 1071| Name | Type | Mandatory| Description | 1072| -------- | ------------------------------------------------- | ---- | ---------- | 1073| callback | AsyncCallback<[NetAddress](#netaddress)> | Yes | Callback used to return the result.| 1074 1075**Error codes** 1076 1077| ID| Error Message | 1078| ------- | ----------------------- | 1079| 201 | Permission denied. | 1080 1081**Example** 1082 1083```js 1084let tcp = socket.constructTCPSocketInstance(); 1085tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}, () => { 1086 console.log('connect success'); 1087 tcp.getRemoteAddress((err, data) => { 1088 if (err) { 1089 console.log('getRemoteAddressfail'); 1090 return; 1091 } 1092 console.log('getRemoteAddresssuccess:' + JSON.stringify(data)); 1093 }) 1094}); 1095``` 1096 1097### getRemoteAddress 1098 1099getRemoteAddress(): Promise\<NetAddress\> 1100 1101Obtains the remote address of a socket connection. This API uses a promise to return the result. 1102 1103> **NOTE** 1104> This API can be called only after **connect** is successfully called. 1105 1106**Required permissions**: ohos.permission.INTERNET 1107 1108**System capability**: SystemCapability.Communication.NetStack 1109 1110**Return value** 1111 1112| Type | Description | 1113| :------------------------------------------ | :------------------------------------------ | 1114| Promise<[NetAddress](#netaddress)> | Promise used to return the result.| 1115 1116**Error codes** 1117 1118| ID| Error Message | 1119| ------- | ----------------------- | 1120| 201 | Permission denied. | 1121 1122**Example** 1123 1124```js 1125let tcp = socket.constructTCPSocketInstance(); 1126let promise1 = tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}); 1127promise1.then(() => { 1128 console.log('connect success'); 1129 let promise2 = tcp.getRemoteAddress(); 1130 promise2.then(() => { 1131 console.log('getRemoteAddress success'); 1132 }).catch(err => { 1133 console.log('getRemoteAddressfail'); 1134 }); 1135}).catch(err => { 1136 console.log('connect fail'); 1137}); 1138``` 1139 1140### getState 1141 1142getState(callback: AsyncCallback\<SocketStateBase\>): void 1143 1144Obtains the status of the TCPSocket connection. This API uses an asynchronous callback to return the result. 1145 1146> **NOTE** 1147> This API can be called only after **bind** or **connect** is successfully called. 1148 1149**Required permissions**: ohos.permission.INTERNET 1150 1151**System capability**: SystemCapability.Communication.NetStack 1152 1153**Parameters** 1154 1155| Name | Type | Mandatory| Description | 1156| -------- | ------------------------------------------------------ | ---- | ---------- | 1157| callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | Yes | Callback used to return the result.| 1158 1159**Error codes** 1160 1161| ID| Error Message | 1162| ------- | ----------------------- | 1163| 201 | Permission denied. | 1164 1165**Example** 1166 1167```js 1168let tcp = socket.constructTCPSocketInstance(); 1169let promise = tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}, () => { 1170 console.log('connect success'); 1171 tcp.getState((err, data) => { 1172 if (err) { 1173 console.log('getState fail'); 1174 return; 1175 } 1176 console.log('getState success:' + JSON.stringify(data)); 1177 }); 1178}); 1179``` 1180 1181### getState 1182 1183getState(): Promise\<SocketStateBase\> 1184 1185Obtains the status of the TCPSocket connection. This API uses a promise to return the result. 1186 1187> **NOTE** 1188> This API can be called only after **bind** or **connect** is successfully called. 1189 1190**Required permissions**: ohos.permission.INTERNET 1191 1192**System capability**: SystemCapability.Communication.NetStack 1193 1194**Return value** 1195 1196| Type | Description | 1197| :----------------------------------------------- | :----------------------------------------- | 1198| Promise<[SocketStateBase](#socketstatebase)> | Promise used to return the result.| 1199 1200**Error codes** 1201 1202| ID| Error Message | 1203| ------- | ----------------------- | 1204| 201 | Permission denied. | 1205 1206**Example** 1207 1208```js 1209let tcp = socket.constructTCPSocketInstance(); 1210let promise = tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}); 1211promise.then(() => { 1212 console.log('connect success'); 1213 let promise1 = tcp.getState(); 1214 promise1.then(() => { 1215 console.log('getState success'); 1216 }).catch(err => { 1217 console.log('getState fail'); 1218 }); 1219}).catch(err => { 1220 console.log('connect fail'); 1221}); 1222``` 1223 1224### setExtraOptions 1225 1226setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\<void\>): void 1227 1228Sets other properties of the TCPSocket connection. This API uses an asynchronous callback to return the result. 1229 1230> **NOTE** 1231> This API can be called only after **bind** or **connect** is successfully called. 1232 1233**Required permissions**: ohos.permission.INTERNET 1234 1235**System capability**: SystemCapability.Communication.NetStack 1236 1237**Parameters** 1238 1239| Name | Type | Mandatory| Description | 1240| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | 1241| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).| 1242| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | 1243 1244**Error codes** 1245 1246| ID| Error Message | 1247| ------- | ----------------------- | 1248| 401 | Parameter error. | 1249| 201 | Permission denied. | 1250 1251**Example** 1252 1253```js 1254let tcp = socket.constructTCPSocketInstance(); 1255let promise = tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}, () => { 1256 console.log('connect success'); 1257 tcp.setExtraOptions({ 1258 keepAlive: true, 1259 OOBInline: true, 1260 TCPNoDelay: true, 1261 socketLinger: {on: true, linger: 10}, 1262 receiveBufferSize: 1000, 1263 sendBufferSize: 1000, 1264 reuseAddress: true, 1265 socketTimeout: 3000, 1266 }, err => { 1267 if (err) { 1268 console.log('setExtraOptions fail'); 1269 return; 1270 } 1271 console.log('setExtraOptions success'); 1272 }); 1273}); 1274``` 1275 1276### setExtraOptions 1277 1278setExtraOptions(options: TCPExtraOptions): Promise\<void\> 1279 1280Sets other properties of the TCPSocket connection. This API uses a promise to return the result. 1281 1282> **NOTE** 1283> This API can be called only after **bind** or **connect** is successfully called. 1284 1285**Required permissions**: ohos.permission.INTERNET 1286 1287**System capability**: SystemCapability.Communication.NetStack 1288 1289**Parameters** 1290 1291| Name | Type | Mandatory| Description | 1292| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | 1293| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).| 1294 1295**Return value** 1296 1297| Type | Description | 1298| :-------------- | :--------------------------------------------------- | 1299| Promise\<void\> | Promise used to return the result.| 1300 1301**Error codes** 1302 1303| ID| Error Message | 1304| ------- | ----------------------- | 1305| 401 | Parameter error. | 1306| 201 | Permission denied. | 1307 1308**Example** 1309 1310```js 1311let tcp = socket.constructTCPSocketInstance(); 1312let promise = tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}); 1313promise.then(() => { 1314 console.log('connect success'); 1315 let promise1 = tcp.setExtraOptions({ 1316 keepAlive: true, 1317 OOBInline: true, 1318 TCPNoDelay: true, 1319 socketLinger: {on: true, linger: 10}, 1320 receiveBufferSize: 1000, 1321 sendBufferSize: 1000, 1322 reuseAddress: true, 1323 socketTimeout: 3000, 1324 }); 1325 promise1.then(() => { 1326 console.log('setExtraOptions success'); 1327 }).catch(err => { 1328 console.log('setExtraOptions fail'); 1329 }); 1330}).catch(err => { 1331 console.log('connect fail'); 1332}); 1333``` 1334 1335### on('message') 1336 1337on(type: 'message', callback: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void 1338 1339Enables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result. 1340 1341**System capability**: SystemCapability.Communication.NetStack 1342 1343**Parameters** 1344 1345| Name | Type | Mandatory| Description | 1346| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 1347| type | string | Yes | Type of the event to subscribe to.<br /> **message**: message receiving event| 1348| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | Yes | Callback used to return the result. | 1349 1350**Example** 1351 1352```js 1353let tcp = socket.constructTCPSocketInstance(); 1354tcp.on('message', value => { 1355 console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo) 1356}); 1357``` 1358 1359### off('message') 1360 1361off(type: 'message', callback?: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void 1362 1363Disables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result. 1364 1365> **NOTE** 1366> 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. 1367 1368**System capability**: SystemCapability.Communication.NetStack 1369 1370**Parameters** 1371 1372| Name | Type | Mandatory| Description | 1373| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 1374| type | string | Yes | Type of the event to subscribe to.<br /> **message**: message receiving event| 1375| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No | Callback used to return the result. | 1376 1377**Example** 1378 1379```js 1380let tcp = socket.constructTCPSocketInstance(); 1381let callback = value => { 1382 console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); 1383} 1384tcp.on('message', callback); 1385// 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. 1386tcp.off('message', callback); 1387tcp.off('message'); 1388``` 1389 1390### on('connect' | 'close') 1391 1392on(type: 'connect' | 'close', callback: Callback\<void\>): void 1393 1394Enables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result. 1395 1396**System capability**: SystemCapability.Communication.NetStack 1397 1398**Parameters** 1399 1400| Name | Type | Mandatory| Description | 1401| -------- | ---------------- | ---- | ------------------------------------------------------------ | 1402| type | string | Yes | Type of the event to subscribe to.<br /><br>- **connect**: connection event<br>- **close**: close event| 1403| callback | Callback\<void\> | Yes | Callback used to return the result. | 1404 1405**Example** 1406 1407```js 1408let tcp = socket.constructTCPSocketInstance(); 1409tcp.on('connect', () => { 1410 console.log("on connect success") 1411}); 1412tcp.on('close', data => { 1413 console.log("on close success") 1414}); 1415``` 1416 1417### off('connect' | 'close') 1418 1419off(type: 'connect' | 'close', callback?: Callback\<void\>): void 1420 1421Disables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result. 1422 1423> **NOTE** 1424> 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. 1425 1426**System capability**: SystemCapability.Communication.NetStack 1427 1428**Parameters** 1429 1430| Name | Type | Mandatory| Description | 1431| -------- | ---------------- | ---- | ------------------------------------------------------------ | 1432| type | string | Yes | Type of the event to subscribe to.<br /><br>- **connect**: connection event<br>- **close**: close event| 1433| callback | Callback\<void\> | No | Callback used to return the result. | 1434 1435**Example** 1436 1437```js 1438let tcp = socket.constructTCPSocketInstance(); 1439let callback1 = () => { 1440 console.log("on connect success"); 1441} 1442tcp.on('connect', callback1); 1443// 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. 1444tcp.off('connect', callback1); 1445tcp.off('connect'); 1446let callback2 = () => { 1447 console.log("on close success"); 1448} 1449tcp.on('close', callback2); 1450// 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. 1451tcp.off('close', callback2); 1452tcp.off('close'); 1453``` 1454 1455### on('error') 1456 1457on(type: 'error', callback: ErrorCallback): void 1458 1459Enables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result. 1460 1461**System capability**: SystemCapability.Communication.NetStack 1462 1463**Parameters** 1464 1465| Name | Type | Mandatory| Description | 1466| -------- | ------------- | ---- | ------------------------------------ | 1467| type | string | Yes | Type of the event to subscribe to.<br /> **error**: error event| 1468| callback | ErrorCallback | Yes | Callback used to return the result. | 1469 1470**Example** 1471 1472```js 1473let tcp = socket.constructTCPSocketInstance(); 1474tcp.on('error', err => { 1475 console.log("on error, err:" + JSON.stringify(err)) 1476}); 1477``` 1478 1479### off('error') 1480 1481off(type: 'error', callback?: ErrorCallback): void 1482 1483Disables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result. 1484 1485> **NOTE** 1486> 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. 1487 1488**System capability**: SystemCapability.Communication.NetStack 1489 1490**Parameters** 1491 1492| Name | Type | Mandatory| Description | 1493| -------- | ------------- | ---- | ------------------------------------ | 1494| type | string | Yes | Type of the event to subscribe to.<br /> **error**: error event| 1495| callback | ErrorCallback | No | Callback used to return the result. | 1496 1497**Example** 1498 1499```js 1500let tcp = socket.constructTCPSocketInstance(); 1501let callback = err => { 1502 console.log("on error, err:" + JSON.stringify(err)); 1503} 1504tcp.on('error', callback); 1505// 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. 1506tcp.off('error', callback); 1507tcp.off('error'); 1508``` 1509 1510## TCPConnectOptions 1511 1512Defines TCPSocket connection parameters. 1513 1514**System capability**: SystemCapability.Communication.NetStack 1515 1516| Name | Type | Mandatory| Description | 1517| ------- | ---------------------------------- | ---- | -------------------------- | 1518| address | [NetAddress](#netaddress) | Yes | Bound IP address and port number. | 1519| timeout | number | No | Timeout duration of the TCPSocket connection, in ms.| 1520 1521## TCPSendOptions 1522 1523Defines the parameters for sending data over the TCPSocket connection. 1524 1525**System capability**: SystemCapability.Communication.NetStack 1526 1527| Name | Type | Mandatory| Description | 1528| -------- | ------ | ---- | ------------------------------------------------------------ | 1529| data | string\| ArrayBuffer<sup>7+</sup> | Yes | Data to send. | 1530| 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**.| 1531 1532## TCPExtraOptions 1533 1534Defines other properties of the TCPSocket connection. 1535 1536**System capability**: SystemCapability.Communication.NetStack 1537 1538| Name | Type | Mandatory| Description | 1539| ----------------- | ------- | ---- | ------------------------------------------------------------ | 1540| keepAlive | boolean | No | Whether to keep the connection alive. The default value is **false**. | 1541| OOBInline | boolean | No | Whether to enable OOBInline. The default value is **false**. | 1542| TCPNoDelay | boolean | No | Whether to enable no-delay on the TCPSocket connection. The default value is **false**. | 1543| 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**.| 1544| receiveBufferSize | number | No | Size of the receive buffer, in bytes. | 1545| sendBufferSize | number | No | Size of the send buffer, in bytes. | 1546| reuseAddress | boolean | No | Whether to reuse addresses. The default value is **false**. | 1547| socketTimeout | number | No | Timeout duration of the UDPSocket connection, in ms. | 1548 1549## Description of TCP Error Codes 1550 1551The TCP error code mapping is in the format of 2301000 + Linux kernel error code. 1552 1553For details about error codes, see [Socket Error Codes](../errorcodes/errorcode-net-socket.md). 1554 1555## socket.constructTLSSocketInstance<sup>9+</sup> 1556 1557constructTLSSocketInstance(): TLSSocket 1558 1559Creates a **TLSSocket** object. 1560 1561**System capability**: SystemCapability.Communication.NetStack 1562 1563**Return value** 1564 1565| Type | Description | 1566| :--------------------------------- | :---------------------- | 1567| [TLSSocket](#tlssocket9) | **TLSSocket** object.| 1568 1569**Example** 1570 1571```js 1572let tls = socket.constructTLSSocketInstance(); 1573``` 1574 1575## TLSSocket<sup>9+</sup> 1576 1577Defines a TLSSocket connection. Before invoking TLSSocket APIs, you need to call [socket.constructTLSSocketInstance](#socketconstructtlssocketinstance9) to create a **TLSSocket** object. 1578 1579### bind<sup>9+</sup> 1580 1581bind(address: NetAddress, callback: AsyncCallback\<void\>): void 1582 1583Binds the IP address and port number. This API uses an asynchronous callback to return the result. 1584 1585**Required permissions**: ohos.permission.INTERNET 1586 1587**System capability**: SystemCapability.Communication.NetStack 1588 1589**Parameters** 1590 1591| Name | Type | Mandatory| Description | 1592| -------- | ---------------------------------- | ---- | ------------------------------------------------------ | 1593| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| 1594| 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.| 1595 1596**Error codes** 1597 1598| ID| Error Message | 1599| ------- | ----------------------- | 1600| 401 | Parameter error. | 1601| 201 | Permission denied. | 1602| 2303198 | Address already in use. | 1603| 2300002 | System internal error. | 1604 1605**Example** 1606 1607```js 1608tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { 1609 if (err) { 1610 console.log('bind fail'); 1611 return; 1612 } 1613 console.log('bind success'); 1614}); 1615``` 1616 1617### bind<sup>9+</sup> 1618 1619bind(address: NetAddress): Promise\<void\> 1620 1621Binds the IP address and port number. This API uses a promise to return the result. 1622 1623**Required permissions**: ohos.permission.INTERNET 1624 1625**System capability**: SystemCapability.Communication.NetStack 1626 1627**Parameters** 1628 1629| Name | Type | Mandatory| Description | 1630| ------- | ---------------------------------- | ---- | ------------------------------------------------------ | 1631| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| 1632 1633**Return value** 1634 1635| Type | Description | 1636| :-------------- | :------------------------------------------------------- | 1637| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.| 1638 1639**Error codes** 1640 1641| ID| Error Message | 1642| ------- | ----------------------- | 1643| 401 | Parameter error. | 1644| 201 | Permission denied. | 1645| 2303198 | Address already in use. | 1646| 2300002 | System internal error. | 1647 1648**Example** 1649 1650```js 1651let promise = tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}); 1652promise.then(() => { 1653 console.log('bind success'); 1654}).catch(err => { 1655 console.log('bind fail'); 1656}); 1657``` 1658 1659### getState<sup>9+</sup> 1660 1661getState(callback: AsyncCallback\<SocketStateBase\>): void 1662 1663Obtains the status of the TLSSocket connection. This API uses an asynchronous callback to return the result. 1664 1665**System capability**: SystemCapability.Communication.NetStack 1666 1667**Parameters** 1668 1669| Name | Type | Mandatory| Description | 1670| -------- | ------------------------------------------------------ | ---- | ---------- | 1671| 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.| 1672 1673**Error codes** 1674 1675| ID| Error Message | 1676| ------- | ------------------------------ | 1677| 2303188 | Socket operation on non-socket.| 1678| 2300002 | System internal error. | 1679 1680**Example** 1681 1682```js 1683let promise = tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { 1684 if (err) { 1685 console.log('bind fail'); 1686 return; 1687 } 1688 console.log('bind success'); 1689}); 1690tls.getState((err, data) => { 1691 if (err) { 1692 console.log('getState fail'); 1693 return; 1694 } 1695 console.log('getState success:' + JSON.stringify(data)); 1696}); 1697``` 1698 1699### getState<sup>9+</sup> 1700 1701getState(): Promise\<SocketStateBase\> 1702 1703Obtains the status of the TLSSocket connection. This API uses a promise to return the result. 1704 1705**System capability**: SystemCapability.Communication.NetStack 1706 1707**Return value** 1708 1709| Type | Description | 1710| :----------------------------------------------- | :----------------------------------------- | 1711| Promise\<[SocketStateBase](#socketstatebase)> | Promise used to return the result. If the operation fails, an error message is returned.| 1712 1713**Error codes** 1714 1715| ID| Error Message | 1716| ------- | ------------------------------ | 1717| 2303188 | Socket operation on non-socket.| 1718| 2300002 | System internal error. | 1719 1720**Example** 1721 1722```js 1723let promiseBind = tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}); 1724promiseBind.then(() => { 1725 console.log('bind success'); 1726}).catch((err) => { 1727 console.log('bind fail'); 1728}); 1729let promise = tls.getState(); 1730promise.then(() => { 1731 console.log('getState success'); 1732}).catch(err => { 1733 console.log('getState fail'); 1734}); 1735``` 1736 1737### setExtraOptions<sup>9+</sup> 1738 1739setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\<void\>): void 1740 1741Sets other properties of the TCPSocket connection after successful binding of the local IP address and port number of the TLSSocket connection. This API uses an asynchronous callback to return the result. 1742 1743**System capability**: SystemCapability.Communication.NetStack 1744 1745**Parameters** 1746 1747| Name | Type | Mandatory| Description | 1748| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | 1749| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).| 1750| 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.| 1751 1752**Error codes** 1753 1754| ID| Error Message | 1755| ------- | ----------------------------- | 1756| 401 | Parameter error. | 1757| 2303188 | Socket operation on non-socket.| 1758| 2300002 | System internal error. | 1759 1760**Example** 1761 1762```js 1763tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { 1764 if (err) { 1765 console.log('bind fail'); 1766 return; 1767 } 1768 console.log('bind success'); 1769}); 1770 1771tls.setExtraOptions({ 1772 keepAlive: true, 1773 OOBInline: true, 1774 TCPNoDelay: true, 1775 socketLinger: {on: true, linger: 10}, 1776 receiveBufferSize: 1000, 1777 sendBufferSize: 1000, 1778 reuseAddress: true, 1779 socketTimeout: 3000, 1780}, err => { 1781 if (err) { 1782 console.log('setExtraOptions fail'); 1783 return; 1784 } 1785 console.log('setExtraOptions success'); 1786}); 1787 1788``` 1789 1790### setExtraOptions<sup>9+</sup> 1791 1792setExtraOptions(options: TCPExtraOptions): Promise\<void\> 1793 1794Sets other properties of the TCPSocket connection after successful binding of the local IP address and port number of the TLSSocket connection. This API uses a promise to return the result. 1795 1796**System capability**: SystemCapability.Communication.NetStack 1797 1798**Parameters** 1799 1800| Name | Type | Mandatory| Description | 1801| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | 1802| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).| 1803 1804**Return value** 1805 1806| Type | Description | 1807| :-------------- | :--------------------------------------------------- | 1808| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.| 1809 1810**Error codes** 1811 1812| ID| Error Message | 1813| ------- | ------------------------------ | 1814| 401 | Parameter error. | 1815| 2303188 | Socket operation on non-socket.| 1816| 2300002 | System internal error. | 1817 1818**Example** 1819 1820```js 1821tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { 1822 if (err) { 1823 console.log('bind fail'); 1824 return; 1825 } 1826 console.log('bind success'); 1827}); 1828let promise = tls.setExtraOptions({ 1829 keepAlive: true, 1830 OOBInline: true, 1831 TCPNoDelay: true, 1832 socketLinger: {on: true, linger: 10}, 1833 receiveBufferSize: 1000, 1834 sendBufferSize: 1000, 1835 reuseAddress: true, 1836 socketTimeout: 3000, 1837}); 1838promise.then(() => { 1839 console.log('setExtraOptions success'); 1840}).catch(err => { 1841 console.log('setExtraOptions fail'); 1842}); 1843``` 1844 1845### connect<sup>9+</sup> 1846 1847connect(options: TLSConnectOptions, callback: AsyncCallback\<void\>): void 1848 1849Sets 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. 1850 1851**System capability**: SystemCapability.Communication.NetStack 1852 1853**Parameters** 1854 1855| Name | Type | Mandatory| Description| 1856| -------- | ---------------------------------------| ----| --------------- | 1857| options | [TLSConnectOptions](#tlsconnectoptions9) | Yes | Parameters required for the TLSSocket connection.| 1858| 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.| 1859 1860**Error codes** 1861 1862| ID| Error Message | 1863| ------- | -------------------------------------------- | 1864| 401 | Parameter error. | 1865| 2303104 | Interrupted system call. | 1866| 2303109 | Bad file number. | 1867| 2303111 | Resource temporarily unavailable try again. | 1868| 2303188 | Socket operation on non-socket. | 1869| 2303191 | Protocol wrong type for socket. | 1870| 2303198 | Address already in use. | 1871| 2303199 | Cannot assign requested address. | 1872| 2303210 | Connection timed out. | 1873| 2303501 | SSL is null. | 1874| 2303502 | Error in tls reading. | 1875| 2303503 | Error in tls writing | 1876| 2303505 | Error occurred in the tls system call. | 1877| 2303506 | Error clearing tls connection. | 1878| 2300002 | System internal error. | 1879 1880**Example** 1881 1882```js 1883let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication 1884tlsTwoWay.bind({address: '192.168.xxx.xxx', port: 8080, family: 1}, err => { 1885 if (err) { 1886 console.log('bind fail'); 1887 return; 1888 } 1889 console.log('bind success'); 1890}); 1891let options = { 1892 ALPNProtocols: ["spdy/1", "http/1.1"], 1893 address: { 1894 address: "192.168.xx.xxx", 1895 port: 8080, 1896 family: 1, 1897 }, 1898 secureOptions: { 1899 key: "xxxx", 1900 cert: "xxxx", 1901 ca: ["xxxx"], 1902 password: "xxxx", 1903 protocols: [socket.Protocol.TLSv12], 1904 useRemoteCipherPrefer: true, 1905 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 1906 cipherSuite: "AES256-SHA256", 1907 }, 1908}; 1909tlsTwoWay.connect(options, (err, data) => { 1910 console.error("connect callback error" + err); 1911 console.log(JSON.stringify(data)); 1912}); 1913 1914let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication 1915tlsOneWay.bind({address: '192.168.xxx.xxx', port: 8080, family: 1}, err => { 1916 if (err) { 1917 console.log('bind fail'); 1918 return; 1919 } 1920 console.log('bind success'); 1921}); 1922let oneWayOptions = { 1923 address: { 1924 address: "192.168.xxx.xxx", 1925 port: 8080, 1926 family: 1, 1927 }, 1928 secureOptions: { 1929 ca: ["xxxx", "xxxx"], 1930 cipherSuite: "AES256-SHA256", 1931 }, 1932}; 1933tlsOneWay.connect(oneWayOptions, (err, data) => { 1934 console.error("connect callback error" + err); 1935 console.log(JSON.stringify(data)); 1936}); 1937``` 1938 1939### connect<sup>9+</sup> 1940 1941connect(options: TLSConnectOptions): Promise\<void\> 1942 1943Sets 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. 1944 1945**System capability**: SystemCapability.Communication.NetStack 1946 1947**Parameters** 1948 1949| Name | Type | Mandatory| Description| 1950| -------- | --------------------------------------| ----| --------------- | 1951| options | [TLSConnectOptions](#tlsconnectoptions9) | Yes | Parameters required for the connection.| 1952 1953**Return value** 1954 1955| Type | Description | 1956| ------------------------------------------- | ----------------------------- | 1957| 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.| 1958 1959**Error codes** 1960 1961| ID| Error Message | 1962| ------- | -------------------------------------------- | 1963| 401 | Parameter error. | 1964| 2303104 | Interrupted system call. | 1965| 2303109 | Bad file number. | 1966| 2303111 | Resource temporarily unavailable try again. | 1967| 2303188 | Socket operation on non-socket. | 1968| 2303191 | Protocol wrong type for socket. | 1969| 2303198 | Address already in use. | 1970| 2303199 | Cannot assign requested address. | 1971| 2303210 | Connection timed out. | 1972| 2303501 | SSL is null. | 1973| 2303502 | Error in tls reading. | 1974| 2303503 | Error in tls writing | 1975| 2303505 | Error occurred in the tls system call. | 1976| 2303506 | Error clearing tls connection. | 1977| 2300002 | System internal error. | 1978 1979**Example** 1980 1981```js 1982let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication 1983tlsTwoWay.bind({address: '192.168.xxx.xxx', port: 8080, family: 1}, err => { 1984 if (err) { 1985 console.log('bind fail'); 1986 return; 1987 } 1988 console.log('bind success'); 1989}); 1990let options = { 1991 ALPNProtocols: ["spdy/1", "http/1.1"], 1992 address: { 1993 address: "xxxx", 1994 port: 8080, 1995 family: 1, 1996 }, 1997 secureOptions: { 1998 key: "xxxx", 1999 cert: "xxxx", 2000 ca: ["xxxx"], 2001 password: "xxxx", 2002 protocols: [socket.Protocol.TLSv12], 2003 useRemoteCipherPrefer: true, 2004 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 2005 cipherSuite: "AES256-SHA256", 2006 }, 2007}; 2008tlsTwoWay.connect(options).then(data => { 2009 console.log(JSON.stringify(data)); 2010}).catch(err => { 2011 console.error(err); 2012}); 2013 2014let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication 2015tlsOneWay.bind({address: '192.168.xxx.xxx', port: 8080, family: 1}, err => { 2016 if (err) { 2017 console.log('bind fail'); 2018 return; 2019 } 2020 console.log('bind success'); 2021}); 2022let oneWayOptions = { 2023 address: { 2024 address: "192.168.xxx.xxx", 2025 port: 8080, 2026 family: 1, 2027 }, 2028 secureOptions: { 2029 ca: ["xxxx", "xxxx"], 2030 cipherSuite: "AES256-SHA256", 2031 }, 2032}; 2033tlsOneWay.connect(oneWayOptions).then(data => { 2034 console.log(JSON.stringify(data)); 2035}).catch(err => { 2036 console.error(err); 2037}); 2038``` 2039 2040### getRemoteAddress<sup>9+</sup> 2041 2042getRemoteAddress(callback: AsyncCallback\<NetAddress\>): void 2043 2044Obtains the remote address of a TLSSocket connection. This API uses an asynchronous callback to return the result. 2045 2046**System capability**: SystemCapability.Communication.NetStack 2047 2048**Parameters** 2049 2050| Name | Type | Mandatory| Description | 2051| -------- | ------------------------------------------------- | ---- | ---------- | 2052| 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.| 2053 2054**Error codes** 2055 2056| ID| Error Message | 2057| ------- | ----------------------------- | 2058| 2303188 | Socket operation on non-socket.| 2059| 2300002 | System internal error. | 2060 2061**Example** 2062 2063```js 2064tls.getRemoteAddress((err, data) => { 2065 if (err) { 2066 console.log('getRemoteAddress fail'); 2067 return; 2068 } 2069 console.log('getRemoteAddress success:' + JSON.stringify(data)); 2070}); 2071``` 2072 2073### getRemoteAddress<sup>9+</sup> 2074 2075getRemoteAddress(): Promise\<NetAddress\> 2076 2077Obtains the remote address of a TLSSocket connection. This API uses a promise to return the result. 2078 2079**System capability**: SystemCapability.Communication.NetStack 2080 2081**Return value** 2082 2083| Type | Description | 2084| :------------------------------------------ | :------------------------------------------ | 2085| Promise\<[NetAddress](#netaddress)> | Promise used to return the result. If the operation fails, an error message is returned.| 2086 2087**Error codes** 2088 2089| ID| Error Message | 2090| ------- | ------------------------------ | 2091| 2303188 | Socket operation on non-socket.| 2092| 2300002 | System internal error. | 2093 2094**Example** 2095 2096```js 2097let promise = tls.getRemoteAddress(); 2098promise.then(() => { 2099 console.log('getRemoteAddress success'); 2100}).catch(err => { 2101 console.log('getRemoteAddress fail'); 2102}); 2103``` 2104 2105### getCertificate<sup>9+</sup> 2106 2107getCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)\>): void 2108 2109Obtains 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. 2110 2111**System capability**: SystemCapability.Communication.NetStack 2112 2113**Parameters** 2114 2115| Name | Type | Mandatory| Description| 2116| -------- | ----------------------------------------| ---- | ---------------| 2117| 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.| 2118 2119**Error codes** 2120 2121| ID| Error Message | 2122| ------- | ------------------------------ | 2123| 2303501 | SSL is null. | 2124| 2303504 | Error looking up x509. | 2125| 2300002 | System internal error. | 2126 2127**Example** 2128 2129```js 2130tls.getCertificate((err, data) => { 2131 if (err) { 2132 console.log("getCertificate callback error = " + err); 2133 } else { 2134 console.log("getCertificate callback = " + data); 2135 } 2136}); 2137``` 2138 2139### getCertificate<sup>9+</sup> 2140 2141getCertificate():Promise\<[X509CertRawData](#x509certrawdata9)\> 2142 2143Obtains 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. 2144 2145**System capability**: SystemCapability.Communication.NetStack 2146 2147**Return value** 2148 2149| Type | Description | 2150| -------------- | -------------------- | 2151| Promise\<[X509CertRawData](#x509certrawdata9)\> | Promise used to return the result. If the operation fails, an error message is returned.| 2152 2153**Error codes** 2154 2155| ID| Error Message | 2156| ------- | ------------------------------ | 2157| 2303501 | SSL is null. | 2158| 2303504 | Error looking up x509. | 2159| 2300002 | System internal error. | 2160 2161**Example** 2162 2163```js 2164tls.getCertificate().then(data => { 2165 console.log(data); 2166}).catch(err => { 2167 console.error(err); 2168}); 2169``` 2170 2171### getRemoteCertificate<sup>9+</sup> 2172 2173getRemoteCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)\>): void 2174 2175Obtains the digital certificate of the server after a TLSSocket connection is established. This API uses an asynchronous callback to return the result. 2176 2177**System capability**: SystemCapability.Communication.NetStack 2178 2179**Parameters** 2180 2181| Name | Type | Mandatory | Description | 2182| -------- | ----------------------------------------| ---- | ---------------| 2183| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| 2184 2185**Error codes** 2186 2187| ID| Error Message | 2188| ------- | ------------------------------ | 2189| 2303501 | SSL is null. | 2190| 2300002 | System internal error. | 2191 2192**Example** 2193 2194```js 2195tls.getRemoteCertificate((err, data) => { 2196 if (err) { 2197 console.log("getRemoteCertificate callback error = " + err); 2198 } else { 2199 console.log("getRemoteCertificate callback = " + data); 2200 } 2201}); 2202``` 2203 2204### getRemoteCertificate<sup>9+</sup> 2205 2206getRemoteCertificate():Promise\<[X509CertRawData](#x509certrawdata9)\> 2207 2208Obtains the digital certificate of the server after a TLSSocket connection is established. This API uses a promise to return the result. 2209 2210**System capability**: SystemCapability.Communication.NetStack 2211 2212**Return value** 2213 2214| Type | Description | 2215| -------------- | -------------------- | 2216| Promise\<[X509CertRawData](#x509certrawdata9)\> | Promise used to return the result. If the operation fails, an error message is returned.| 2217 2218**Error codes** 2219 2220| ID| Error Message | 2221| ------- | ------------------------------ | 2222| 2303501 | SSL is null. | 2223| 2300002 | System internal error. | 2224 2225**Example** 2226 2227```js 2228tls.getRemoteCertificate().then(data => { 2229 console.log(data); 2230}).catch(err => { 2231 console.error(err); 2232}); 2233``` 2234 2235### getProtocol<sup>9+</sup> 2236 2237getProtocol(callback: AsyncCallback\<string\>): void 2238 2239Obtains the communication protocol version after a TLSSocket connection is established. This API uses an asynchronous callback to return the result. 2240 2241**System capability**: SystemCapability.Communication.NetStack 2242 2243**Parameters** 2244 2245| Name | Type | Mandatory| Description | 2246| -------- | ----------------------------------------| ---- | ---------------| 2247| callback | AsyncCallback\<string\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| 2248 2249**Error codes** 2250 2251| ID| Error Message | 2252| ------- | ----------------------------- | 2253| 2303501 | SSL is null. | 2254| 2303505 | Error occurred in the tls system call. | 2255| 2300002 | System internal error. | 2256 2257**Example** 2258 2259```js 2260tls.getProtocol((err, data) => { 2261 if (err) { 2262 console.log("getProtocol callback error = " + err); 2263 } else { 2264 console.log("getProtocol callback = " + data); 2265 } 2266}); 2267``` 2268 2269### getProtocol<sup>9+</sup> 2270 2271getProtocol():Promise\<string\> 2272 2273Obtains the communication protocol version after a TLSSocket connection is established. This API uses a promise to return the result. 2274 2275**System capability**: SystemCapability.Communication.NetStack 2276 2277**Return value** 2278 2279| Type | Description | 2280| -------------- | -------------------- | 2281| Promise\<string\> | Promise used to return the result. If the operation fails, an error message is returned.| 2282 2283**Error codes** 2284 2285| ID| Error Message | 2286| ------- | ------------------------------ | 2287| 2303501 | SSL is null. | 2288| 2303505 | Error occurred in the tls system call. | 2289| 2300002 | System internal error. | 2290 2291**Example** 2292 2293```js 2294tls.getProtocol().then(data => { 2295 console.log(data); 2296}).catch(err => { 2297 console.error(err); 2298}); 2299``` 2300 2301### getCipherSuite<sup>9+</sup> 2302 2303getCipherSuite(callback: AsyncCallback\<Array\<string\>\>): void 2304 2305Obtains the cipher suite negotiated by both communication parties after a TLSSocket connection is established. This API uses an asynchronous callback to return the result. 2306 2307**System capability**: SystemCapability.Communication.NetStack 2308 2309**Parameters** 2310 2311| Name | Type | Mandatory| Description| 2312| -------- | ----------------------------------------| ---- | ---------------| 2313| callback | AsyncCallback\<Array\<string\>\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| 2314 2315**Error codes** 2316 2317| ID| Error Message | 2318| ------- | ------------------------------ | 2319| 2303501 | SSL is null. | 2320| 2303502 | Error in tls reading. | 2321| 2303505 | Error occurred in the tls system call. | 2322| 2300002 | System internal error. | 2323 2324**Example** 2325 2326```js 2327tls.getCipherSuite((err, data) => { 2328 if (err) { 2329 console.log("getCipherSuite callback error = " + err); 2330 } else { 2331 console.log("getCipherSuite callback = " + data); 2332 } 2333}); 2334``` 2335 2336### getCipherSuite<sup>9+</sup> 2337 2338getCipherSuite(): Promise\<Array\<string\>\> 2339 2340Obtains the cipher suite negotiated by both communication parties after a TLSSocket connection is established. This API uses a promise to return the result. 2341 2342**System capability**: SystemCapability.Communication.NetStack 2343 2344**Return value** 2345 2346| Type | Description | 2347| ---------------------- | --------------------- | 2348| Promise\<Array\<string\>\> | Promise used to return the result. If the operation fails, an error message is returned.| 2349 2350**Error codes** 2351 2352| ID| Error Message | 2353| ------- | ------------------------------ | 2354| 2303501 | SSL is null. | 2355| 2303502 | Error in tls reading. | 2356| 2303505 | Error occurred in the tls system call. | 2357| 2300002 | System internal error. | 2358 2359**Example** 2360 2361```js 2362tls.getCipherSuite().then(data => { 2363 console.log('getCipherSuite success:' + JSON.stringify(data)); 2364}).catch(err => { 2365 console.error(err); 2366}); 2367``` 2368 2369### getSignatureAlgorithms<sup>9+</sup> 2370 2371getSignatureAlgorithms(callback: AsyncCallback\<Array\<string\>\>): void 2372 2373Obtains 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. 2374 2375**System capability**: SystemCapability.Communication.NetStack 2376 2377**Parameters** 2378 2379| Name | Type | Mandatory| Description | 2380| -------- | -------------------------------------| ---- | ---------------| 2381| callback | AsyncCallback\<Array\<string\>\> | Yes | Callback used to return the result. | 2382 2383**Error codes** 2384 2385| ID| Error Message | 2386| ------- | ------------------------------ | 2387| 2303501 | SSL is null. | 2388| 2300002 | System internal error. | 2389 2390**Example** 2391 2392```js 2393tls.getSignatureAlgorithms((err, data) => { 2394 if (err) { 2395 console.log("getSignatureAlgorithms callback error = " + err); 2396 } else { 2397 console.log("getSignatureAlgorithms callback = " + data); 2398 } 2399}); 2400``` 2401 2402### getSignatureAlgorithms<sup>9+</sup> 2403 2404getSignatureAlgorithms(): Promise\<Array\<string\>\> 2405 2406Obtains 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. 2407 2408**System capability**: SystemCapability.Communication.NetStack 2409 2410**Return value** 2411 2412| Type | Description | 2413| ---------------------- | -------------------- | 2414| Promise\<Array\<string\>\> | Promise used to return the result.| 2415 2416**Error codes** 2417 2418| ID| Error Message | 2419| ------- | ------------------------------ | 2420| 2303501 | SSL is null. | 2421| 2300002 | System internal error. | 2422 2423**Example** 2424 2425```js 2426tls.getSignatureAlgorithms().then(data => { 2427 console.log("getSignatureAlgorithms success" + data); 2428}).catch(err => { 2429 console.error(err); 2430}); 2431``` 2432 2433### send<sup>9+</sup> 2434 2435send(data: string, callback: AsyncCallback\<void\>): void 2436 2437Sends a message to the server after a TLSSocket connection is established. This API uses an asynchronous callback to return the result. 2438 2439**System capability**: SystemCapability.Communication.NetStack 2440 2441**Parameters** 2442 2443| Name | Type | Mandatory| Description | 2444| -------- | -----------------------------| ---- | ---------------| 2445| data | string | Yes | Data content of the message to send. | 2446| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| 2447 2448**Error codes** 2449 2450| ID| Error Message | 2451| ------- | -------------------------------------------- | 2452| 401 | Parameter error. | 2453| 2303501 | SSL is null. | 2454| 2303503 | Error in tls writing | 2455| 2303505 | Error occurred in the tls system call. | 2456| 2303506 | Error clearing tls connection. | 2457| 2300002 | System internal error. | 2458 2459**Example** 2460 2461```js 2462tls.send("xxxx", (err) => { 2463 if (err) { 2464 console.log("send callback error = " + err); 2465 } else { 2466 console.log("send success"); 2467 } 2468}); 2469``` 2470 2471### send<sup>9+</sup> 2472 2473send(data: string): Promise\<void\> 2474 2475Sends a message to the server after a TLSSocket connection is established. This API uses a promise to return the result. 2476 2477**System capability**: SystemCapability.Communication.NetStack 2478 2479**Parameters** 2480 2481| Name | Type | Mandatory| Description | 2482| -------- | -----------------------------| ---- | ---------------| 2483| data | string | Yes | Data content of the message to send. | 2484 2485**Error codes** 2486 2487| ID| Error Message | 2488| ------- | -------------------------------------------- | 2489| 401 | Parameter error. | 2490| 2303501 | SSL is null. | 2491| 2303503 | Error in tls writing | 2492| 2303505 | Error occurred in the tls system call. | 2493| 2303506 | Error clearing tls connection. | 2494| 2300002 | System internal error. | 2495 2496**Return value** 2497 2498| Type | Description | 2499| -------------- | -------------------- | 2500| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.| 2501 2502**Example** 2503 2504```js 2505tls.send("xxxx").then(() => { 2506 console.log("send success"); 2507}).catch(err => { 2508 console.error(err); 2509}); 2510``` 2511 2512### close<sup>9+</sup> 2513 2514close(callback: AsyncCallback\<void\>): void 2515 2516Closes a TLSSocket connection. This API uses an asynchronous callback to return the result. 2517 2518**System capability**: SystemCapability.Communication.NetStack 2519 2520**Parameters** 2521 2522| Name | Type | Mandatory| Description | 2523| -------- | -----------------------------| ---- | ---------------| 2524| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| 2525 2526**Error codes** 2527 2528| ID| Error Message | 2529| ------- | -------------------------------------------- | 2530| 2303501 | SSL is null. | 2531| 2303505 | Error occurred in the tls system call. | 2532| 2303506 | Error clearing tls connection. | 2533| 2300002 | System internal error. | 2534 2535**Example** 2536 2537```js 2538tls.close((err) => { 2539 if (err) { 2540 console.log("close callback error = " + err); 2541 } else { 2542 console.log("close success"); 2543 } 2544}); 2545``` 2546 2547### close<sup>9+</sup> 2548 2549close(): Promise\<void\> 2550 2551Closes a TLSSocket connection. This API uses a promise to return the result. 2552 2553**System capability**: SystemCapability.Communication.NetStack 2554 2555**Return value** 2556 2557| Type | Description | 2558| -------------- | -------------------- | 2559| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.| 2560 2561**Error codes** 2562 2563| ID| Error Message | 2564| ------- | -------------------------------------------- | 2565| 2303501 | SSL is null. | 2566| 2303505 | Error occurred in the tls system call. | 2567| 2303506 | Error clearing tls connection. | 2568| 2300002 | System internal error. | 2569 2570**Example** 2571 2572```js 2573tls.close().then(() => { 2574 console.log("close success"); 2575}).catch(err => { 2576 console.error(err); 2577}); 2578``` 2579 2580## TLSConnectOptions<sup>9+</sup> 2581 2582Defines TLS connection options. 2583 2584**System capability**: SystemCapability.Communication.NetStack 2585 2586| Name | Type | Mandatory| Description | 2587| -------------- | ------------------------------------- | --- |-------------- | 2588| address | [NetAddress](#netaddress) | Yes | Gateway address. | 2589| secureOptions | [TLSSecureOptions](#tlssecureoptions9) | Yes| TLS security options.| 2590| ALPNProtocols | Array\<string\> | No| Application Layer Protocol Negotiation (ALPN) protocols. | 2591 2592## TLSSecureOptions<sup>9+</sup> 2593 2594Defines 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. 2595 2596**System capability**: SystemCapability.Communication.NetStack 2597 2598| Name | Type | Mandatory| Description | 2599| --------------------- | ------------------------------------------------------ | --- |----------------------------------- | 2600| ca | string \| Array\<string\> | Yes| CA certificate of the server, which is used to authenticate the digital certificate of the server.| 2601| cert | string | No| Digital certificate of the local client. | 2602| key | string | No| Private key of the local digital certificate. | 2603| password | string | No| Password for reading the private key. | 2604| protocols | [Protocol](#protocol9) \|Array\<[Protocol](#protocol9)\> | No| TLS protocol version. | 2605| useRemoteCipherPrefer | boolean | No| Whether to use the remote cipher suite preferentially. | 2606| signatureAlgorithms | string | No| Signing algorithm used during communication. | 2607| cipherSuite | string | No| Cipher suite used during communication. | 2608 2609## Protocol<sup>9+</sup> 2610 2611Enumerates TLS protocol versions. 2612 2613**System capability**: SystemCapability.Communication.NetStack 2614 2615| Name | Value | Description | 2616| --------- | --------- |------------------ | 2617| TLSv12 | "TLSv1.2" | TLSv1.2.| 2618| TLSv13 | "TLSv1.3" | TLSv1.3.| 2619 2620## X509CertRawData<sup>9+</sup> 2621 2622Defines the certificate raw data. 2623 2624**System capability**: SystemCapability.Communication.NetStack 2625 2626| Type | Description | 2627| --------------------------------------------------------------------- | --------------------- | 2628|[cert.EncodingBlob](js-apis-cert.md#datablob) | Data and encoding format of the certificate.| 2629