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