1# @ohos.net.socket (Socket Connection) 2 3The **socket** module implements data transfer over TCP, UDP, Web, and TLS socket 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```ts 12import { socket } from '@kit.NetworkKit'; 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```ts 32import { socket } from '@kit.NetworkKit'; 33let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 34``` 35 36## UDPSocket 37 38Defines a UDP socket connection. Before calling UDPSocket APIs, you need to call [socket.constructUDPSocketInstance](#socketconstructudpsocketinstance) to create a **UDPSocket** object. 39 40### bind 41 42bind(address: NetAddress, callback: AsyncCallback\<void\>): void 43 44Binds 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. 45 46**Required permissions**: ohos.permission.INTERNET 47 48**System capability**: SystemCapability.Communication.NetStack 49 50**Parameters** 51 52| Name | Type | Mandatory| Description | 53| -------- | ---------------------------------- | ---- | ------------------------------------------------------ | 54| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| 55| 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. | 56 57**Error codes** 58 59| ID| Error Message | 60| ------- | ----------------------- | 61| 401 | Parameter error. | 62| 201 | Permission denied. | 63 64**Example** 65 66```ts 67import { socket } from '@kit.NetworkKit'; 68import { BusinessError } from '@kit.BasicServicesKit'; 69 70let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 71let bindAddr: socket.NetAddress = { 72 address: '192.168.xx.xxx', 73 port: 1234 74} 75udp.bind(bindAddr, (err: BusinessError) => { 76 if (err) { 77 console.log('bind fail'); 78 return; 79 } 80 console.log('bind success'); 81}); 82``` 83 84### bind 85 86bind(address: NetAddress): Promise\<void\> 87 88Binds 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. 89 90**Required permissions**: ohos.permission.INTERNET 91 92**System capability**: SystemCapability.Communication.NetStack 93 94**Parameters** 95 96| Name | Type | Mandatory| Description | 97| ------- | ---------------------------------- | ---- | ------------------------------------------------------ | 98| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| 99 100**Error codes** 101 102| ID| Error Message | 103| ------- | ----------------------- | 104| 401 | Parameter error. | 105| 201 | Permission denied. | 106 107**Return value** 108 109| Type | Description | 110| -------------- | ----------------------------------------- | 111| Promise\<void\> | Promise used to return the result.| 112 113**Example** 114 115```ts 116import { socket } from '@kit.NetworkKit'; 117import { BusinessError } from '@kit.BasicServicesKit'; 118 119let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 120let bindAddr: socket.NetAddress = { 121 address: '192.168.xx.xxx', 122 port: 8080 123} 124udp.bind(bindAddr).then(() => { 125 console.log('bind success'); 126}).catch((err: BusinessError) => { 127 console.log('bind fail'); 128}); 129``` 130 131### send 132 133send(options: UDPSendOptions, callback: AsyncCallback\<void\>): void 134 135Sends data over a UDP socket connection. This API uses an asynchronous callback to return the result. 136 137Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and port. Call the API in the worker thread or taskpool thread as this operation is time-consuming. 138 139**Required permissions**: ohos.permission.INTERNET 140 141**System capability**: SystemCapability.Communication.NetStack 142 143**Parameters** 144 145| Name | Type | Mandatory| Description | 146| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | 147| options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over a UDP socket connection. For details, see [UDPSendOptions](#udpsendoptions).| 148| 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. | 149 150**Error codes** 151 152| ID| Error Message | 153| ------- | ----------------------- | 154| 401 | Parameter error. | 155| 201 | Permission denied. | 156 157**Example** 158 159```ts 160import { socket } from '@kit.NetworkKit'; 161import { BusinessError } from '@kit.BasicServicesKit'; 162 163let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 164let netAddress: socket.NetAddress = { 165 address: '192.168.xx.xxx', 166 port: 8080 167} 168let sendOptions: socket.UDPSendOptions = { 169 data: 'Hello, server!', 170 address: netAddress 171} 172udp.send(sendOptions, (err: BusinessError) => { 173 if (err) { 174 console.log('send fail'); 175 return; 176 } 177 console.log('send success'); 178}); 179``` 180 181### send 182 183send(options: UDPSendOptions): Promise\<void\> 184 185Sends data over a UDP socket connection. This API uses a promise to return the result. 186 187Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and port. Call the API in the worker thread or taskpool thread as this operation is time-consuming. 188 189**Required permissions**: ohos.permission.INTERNET 190 191**System capability**: SystemCapability.Communication.NetStack 192 193**Parameters** 194 195| Name | Type | Mandatory| Description | 196| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | 197| options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over a UDP socket connection. For details, see [UDPSendOptions](#udpsendoptions).| 198 199**Error codes** 200 201| ID| Error Message | 202| ------- | ----------------------- | 203| 401 | Parameter error. | 204| 201 | Permission denied. | 205 206**Return value** 207 208| Type | Description | 209| -------------- | --------------------------------------------- | 210| Promise\<void\> | Promise used to return the result.| 211 212**Example** 213 214```ts 215import { socket } from '@kit.NetworkKit'; 216import { BusinessError } from '@kit.BasicServicesKit'; 217 218let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 219let netAddress: socket.NetAddress = { 220 address: '192.168.xx.xxx', 221 port: 8080 222} 223let sendOptions: socket.UDPSendOptions = { 224 data: 'Hello, server!', 225 address: netAddress 226} 227udp.send(sendOptions).then(() => { 228 console.log('send success'); 229}).catch((err: BusinessError) => { 230 console.log('send fail'); 231}); 232``` 233 234### close 235 236close(callback: AsyncCallback\<void\>): void 237 238Closes a UDP socket connection. This API uses an asynchronous callback to return the result. 239 240**Required permissions**: ohos.permission.INTERNET 241 242**System capability**: SystemCapability.Communication.NetStack 243 244**Parameters** 245 246| Name | Type | Mandatory| Description | 247| -------- | --------------------- | ---- | ---------- | 248| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | 249 250**Error codes** 251 252| ID| Error Message | 253| ------- | ----------------------- | 254| 201 | Permission denied. | 255 256**Example** 257 258```ts 259import { socket } from '@kit.NetworkKit'; 260import { BusinessError } from '@kit.BasicServicesKit'; 261 262let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 263udp.close((err: BusinessError) => { 264 if (err) { 265 console.log('close fail'); 266 return; 267 } 268 console.log('close success'); 269}) 270``` 271 272### close 273 274close(): Promise\<void\> 275 276Closes a UDP socket connection. This API uses a promise to return the result. 277 278**Required permissions**: ohos.permission.INTERNET 279 280**System capability**: SystemCapability.Communication.NetStack 281 282**Error codes** 283 284| ID| Error Message | 285| ------- | ----------------------- | 286| 201 | Permission denied. | 287 288**Return value** 289 290| Type | Description | 291| -------------- | ----------------------------------------- | 292| Promise\<void\> | Promise used to return the result.| 293 294**Example** 295 296```ts 297import { socket } from '@kit.NetworkKit'; 298import { BusinessError } from '@kit.BasicServicesKit'; 299 300let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 301udp.close().then(() => { 302 console.log('close success'); 303}).catch((err: BusinessError) => { 304 console.log('close fail'); 305}); 306``` 307 308### getState 309 310getState(callback: AsyncCallback\<SocketStateBase\>): void 311 312Obtains the status of the UDP socket connection. This API uses an asynchronous callback to return the result. 313 314> **NOTE** 315> This API can be called only after **bind** is successfully called. 316 317**Required permissions**: ohos.permission.INTERNET 318 319**System capability**: SystemCapability.Communication.NetStack 320 321**Parameters** 322 323| Name | Type | Mandatory| Description | 324| -------- | ------------------------------------------------------ | ---- | ---------- | 325| callback | AsyncCallback\<[SocketStateBase](#socketstatebase)\> | Yes | Callback used to return the result. If the operation is successful, the status of the TLS socket server connection is returned. If the operation fails, an error message is returned.| 326 327**Error codes** 328 329| ID| Error Message | 330| ------- | ----------------------- | 331| 201 | Permission denied. | 332 333**Example** 334 335```ts 336import { socket } from '@kit.NetworkKit'; 337import { BusinessError } from '@kit.BasicServicesKit'; 338 339let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 340let bindAddr: socket.NetAddress = { 341 address: '192.168.xx.xxx', 342 port: 8080 343} 344udp.bind(bindAddr, (err: BusinessError) => { 345 if (err) { 346 console.log('bind fail'); 347 return; 348 } 349 console.log('bind success'); 350 udp.getState((err: BusinessError, data: socket.SocketStateBase) => { 351 if (err) { 352 console.log('getState fail'); 353 return; 354 } 355 console.log('getState success:' + JSON.stringify(data)); 356 }) 357}) 358``` 359 360### getState 361 362getState(): Promise\<SocketStateBase\> 363 364Obtains the status of the UDP socket connection. This API uses a promise to return the result. 365 366> **NOTE** 367> This API can be called only after **bind** is successfully called. 368 369**Required permissions**: ohos.permission.INTERNET 370 371**System capability**: SystemCapability.Communication.NetStack 372 373**Error codes** 374 375| ID| Error Message | 376| ------- | ----------------------- | 377| 201 | Permission denied. | 378 379**Return value** 380 381| Type | Description | 382| ----------------------------------------------- | ----------------------------------------- | 383| Promise\<[SocketStateBase](#socketstatebase)\> | Promise used to return the result.| 384 385**Example** 386 387```ts 388import { socket } from '@kit.NetworkKit'; 389import { BusinessError } from '@kit.BasicServicesKit'; 390 391let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 392let bindAddr: socket.NetAddress = { 393 address: '192.168.xx.xxx', 394 port: 8080 395} 396udp.bind(bindAddr, (err: BusinessError) => { 397 if (err) { 398 console.log('bind fail'); 399 return; 400 } 401 console.log('bind success'); 402 udp.getState().then((data: socket.SocketStateBase) => { 403 console.log('getState success:' + JSON.stringify(data)); 404 }).catch((err: BusinessError) => { 405 console.log('getState fail' + JSON.stringify(err)); 406 }); 407}); 408``` 409 410### setExtraOptions 411 412setExtraOptions(options: UDPExtraOptions, callback: AsyncCallback\<void\>): void 413 414Sets other properties of the UDP socket connection. This API uses an asynchronous callback to return the result. 415 416> **NOTE** 417> This API can be called only after **bind** is successfully called. 418 419**Required permissions**: ohos.permission.INTERNET 420 421**System capability**: SystemCapability.Communication.NetStack 422 423**Parameters** 424 425| Name | Type | Mandatory| Description | 426| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | 427| options | [UDPExtraOptions](#udpextraoptions) | Yes | Other properties of the UDP socket connection. For details, see [UDPExtraOptions](#udpextraoptions).| 428| 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. | 429 430**Error codes** 431 432| ID| Error Message | 433| ------- | ----------------------- | 434| 401 | Parameter error. | 435| 201 | Permission denied. | 436 437**Example** 438 439```ts 440import { socket } from '@kit.NetworkKit'; 441import { BusinessError } from '@kit.BasicServicesKit'; 442 443let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 444 445let bindAddr: socket.NetAddress = { 446 address: '192.168.xx.xxx', 447 port: 8080 448} 449udp.bind(bindAddr, (err: BusinessError) => { 450 if (err) { 451 console.log('bind fail'); 452 return; 453 } 454 console.log('bind success'); 455 let udpextraoptions: socket.UDPExtraOptions = { 456 receiveBufferSize: 1000, 457 sendBufferSize: 1000, 458 reuseAddress: false, 459 socketTimeout: 6000, 460 broadcast: true 461 } 462 udp.setExtraOptions(udpextraoptions, (err: BusinessError) => { 463 if (err) { 464 console.log('setExtraOptions fail'); 465 return; 466 } 467 console.log('setExtraOptions success'); 468 }) 469}) 470``` 471 472### setExtraOptions 473 474setExtraOptions(options: UDPExtraOptions): Promise\<void\> 475 476Sets other properties of the UDP socket connection. This API uses a promise to return the result. 477 478> **NOTE** 479> This API can be called only after **bind** is successfully called. 480 481**Required permissions**: ohos.permission.INTERNET 482 483**System capability**: SystemCapability.Communication.NetStack 484 485**Parameters** 486 487| Name | Type | Mandatory| Description | 488| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | 489| options | [UDPExtraOptions](#udpextraoptions) | Yes | Other properties of the UDP socket connection. For details, see [UDPExtraOptions](#udpextraoptions).| 490 491**Return value** 492 493| Type | Description | 494| -------------- | --------------------------------------------------- | 495| Promise\<void\> | Promise used to return the result.| 496 497**Error codes** 498 499| ID| Error Message | 500| ------- | ----------------------- | 501| 401 | Parameter error. | 502| 201 | Permission denied. | 503 504**Example** 505 506```ts 507import { socket } from '@kit.NetworkKit'; 508import { BusinessError } from '@kit.BasicServicesKit'; 509 510let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 511 512let bindAddr: socket.NetAddress = { 513 address: '192.168.xx.xxx', 514 port: 8080 515} 516udp.bind(bindAddr, (err: BusinessError) => { 517 if (err) { 518 console.log('bind fail'); 519 return; 520 } 521 console.log('bind success'); 522 let udpextraoptions: socket.UDPExtraOptions = { 523 receiveBufferSize: 1000, 524 sendBufferSize: 1000, 525 reuseAddress: false, 526 socketTimeout: 6000, 527 broadcast: true 528 } 529 udp.setExtraOptions(udpextraoptions).then(() => { 530 console.log('setExtraOptions success'); 531 }).catch((err: BusinessError) => { 532 console.log('setExtraOptions fail'); 533 }); 534}) 535``` 536 537### getLocalAddress<sup>12+</sup> 538 539getLocalAddress(): Promise\<NetAddress\> 540 541Obtains the local socket address of a **UDPSocket** connection. This API uses a promise to return the result. 542 543> **NOTE** 544> This API can be called only after **bind** is successfully called. 545 546**System capability**: SystemCapability.Communication.NetStack 547 548**Return value** 549 550| Type | Description | 551| -------------- | --------------------------------------------------- | 552| Promise\<[NetAddress](#netaddress)\> | Promise used to return the result.| 553 554**Error codes** 555 556| ID| Error Message | 557| -------- | ------------------------------------------- | 558| 2300002 | System internal error. | 559| 2301009 | Bad file descriptor. | 560| 2303188 | Socket operation on non-socket. | 561 562**Example** 563 564```ts 565import { socket } from '@kit.NetworkKit'; 566import { BusinessError } from '@kit.BasicServicesKit'; 567 568let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 569 570let bindAddr: socket.NetAddress = { 571 address: '192.168.xx.xxx', 572 port: 8080 573} 574udp.bind(bindAddr).then(() => { 575 console.info('bind success'); 576 udp.getLocalAddress().then((localAddress: socket.NetAddress) => { 577 console.info("UDP_Socket get SUCCESS! Address: " + JSON.stringify(localAddress)); 578 }).catch((err: BusinessError) => { 579 console.error("UDP_Socket get FAILED! Error: " + JSON.stringify(err)); 580 }) 581}).catch((err: BusinessError) => { 582 console.error('bind fail'); 583}); 584``` 585 586### on('message') 587 588on(type: 'message', callback: Callback\<SocketMessageInfo\>): void 589 590Subscribes to **message** events of the UDP socket connection. This API uses an asynchronous callback to return the result. 591 592**System capability**: SystemCapability.Communication.NetStack 593 594**Parameters** 595 596| Name | Type | Mandatory| Description | 597| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 598| type | string | Yes | Event type.<br/> **message**: message receiving event.| 599| callback | Callback\<[SocketMessageInfo](#socketmessageinfo11)\> | Yes | Callback used to return the result. | 600 601**Example** 602 603```ts 604import { socket } from '@kit.NetworkKit'; 605import { BusinessError } from '@kit.BasicServicesKit'; 606 607let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 608 609let messageView = ''; 610udp.on('message', (value: socket.SocketMessageInfo) => { 611 for (let i: number = 0; i < value.message.byteLength; i++) { 612 let uint8Array = new Uint8Array(value.message) 613 let messages = uint8Array[i] 614 let message = String.fromCharCode(messages); 615 messageView += message; 616 } 617 console.log('on message message: ' + JSON.stringify(messageView)); 618 console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo)); 619}); 620``` 621 622### off('message') 623 624off(type: 'message', callback?: Callback\<SocketMessageInfo\>): void 625 626Unsubscribes from **message** events of the UDP socket connection. This API uses an asynchronous callback to return the result. 627 628**System capability**: SystemCapability.Communication.NetStack 629 630**Parameters** 631 632| Name | Type | Mandatory| Description | 633| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 634| type | string | Yes | Event type.<br/> **message**: message receiving event.| 635| callback | Callback\<[SocketMessageInfo](#socketmessageinfo11)\> | No | Callback used to return the result. | 636 637**Example** 638 639```ts 640import { socket } from '@kit.NetworkKit'; 641import { BusinessError } from '@kit.BasicServicesKit'; 642 643let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 644let messageView = ''; 645let callback = (value: socket.SocketMessageInfo) => { 646 for (let i: number = 0; i < value.message.byteLength; i++) { 647 let uint8Array = new Uint8Array(value.message) 648 let messages = uint8Array[i] 649 let message = String.fromCharCode(messages); 650 messageView += message; 651 } 652 console.log('on message message: ' + JSON.stringify(messageView)); 653 console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo)); 654} 655udp.on('message', callback); 656// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 657udp.off('message', callback); 658udp.off('message'); 659``` 660 661### on('listening' | 'close') 662 663on(type: 'listening' | 'close', callback: Callback\<void\>): void 664 665Subscribes to **listening** events or **close** events of the UDP socket connection. This API uses an asynchronous callback to return the result. 666 667**System capability**: SystemCapability.Communication.NetStack 668 669**Parameters** 670 671| Name | Type | Mandatory| Description | 672| -------- | ---------------- | ---- | ------------------------------------------------------------ | 673| type | string | Yes | Event type.<br>- **listening**: data packet message event.<br>- **close**: close event.| 674| callback | Callback\<void\> | Yes | Callback used to return the result. | 675 676**Example** 677 678```ts 679import { socket } from '@kit.NetworkKit'; 680import { BusinessError } from '@kit.BasicServicesKit'; 681 682let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 683udp.on('listening', () => { 684 console.log("on listening success"); 685}); 686udp.on('close', () => { 687 console.log("on close success"); 688}); 689``` 690 691### off('listening' | 'close') 692 693off(type: 'listening' | 'close', callback?: Callback\<void\>): void 694 695Unsubscribes from **listening** events or **close** events of the UDP socket connection. This API uses an asynchronous callback to return the result. 696 697**System capability**: SystemCapability.Communication.NetStack 698 699**Parameters** 700 701| Name | Type | Mandatory| Description | 702| -------- | ---------------- | ---- | ------------------------------------------------------------ | 703| type | string | Yes | Event type.<br>- **listening**: data packet message event.<br>- **close**: close event.| 704| callback | Callback\<void\> | No | Callback used to return the result. | 705 706**Example** 707 708```ts 709import { socket } from '@kit.NetworkKit'; 710import { BusinessError } from '@kit.BasicServicesKit'; 711 712let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 713let callback1 = () => { 714 console.log("on listening, success"); 715} 716udp.on('listening', callback1); 717// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 718udp.off('listening', callback1); 719udp.off('listening'); 720let callback2 = () => { 721 console.log("on close, success"); 722} 723udp.on('close', callback2); 724// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 725udp.off('close', callback2); 726udp.off('close'); 727``` 728 729### on('error') 730 731on(type: 'error', callback: ErrorCallback): void 732 733Subscribes to **error** events of the UDP socket connection. This API uses an asynchronous callback to return the result. 734 735**System capability**: SystemCapability.Communication.NetStack 736 737**Parameters** 738 739| Name | Type | Mandatory| Description | 740| -------- | ------------- | ---- | ------------------------------------ | 741| type | string | Yes | Event type.<br/> **error**: error event.| 742| callback | ErrorCallback | Yes | Callback used to return the result. | 743 744**Example** 745 746```ts 747import { socket } from '@kit.NetworkKit'; 748import { BusinessError } from '@kit.BasicServicesKit'; 749 750let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 751udp.on('error', (err: BusinessError) => { 752 console.log("on error, err:" + JSON.stringify(err)) 753}); 754``` 755 756### off('error') 757 758off(type: 'error', callback?: ErrorCallback): void 759 760Unsubscribes from **error** events of the UDP socket connection. This API uses an asynchronous callback to return the result. 761 762**System capability**: SystemCapability.Communication.NetStack 763 764**Parameters** 765 766| Name | Type | Mandatory| Description | 767| -------- | ------------- | ---- | ------------------------------------ | 768| type | string | Yes | Event type.<br/> **error**: error event.| 769| callback | ErrorCallback | No | Callback used to return the result. | 770 771**Example** 772 773```ts 774import { socket } from '@kit.NetworkKit'; 775import { BusinessError } from '@kit.BasicServicesKit'; 776 777let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 778let callback = (err: BusinessError) => { 779 console.log("on error, err:" + JSON.stringify(err)); 780} 781udp.on('error', callback); 782// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 783udp.off('error', callback); 784udp.off('error'); 785``` 786 787## NetAddress 788 789Defines the destination address. 790 791**System capability**: SystemCapability.Communication.NetStack 792 793| Name | Type | Mandatory| Description | 794| ------- | ------ | ---- | ------------------------------------------------------------ | 795| address<sup>11+</sup> | string | Yes | Bound IP address. | 796| port | number | No | Port number. The value ranges from **0** to **65535**. If this parameter is not specified, the system randomly allocates a port. | 797| family | number | No | Network protocol type.<br>- **1**: IPv4<br>- **2**: IPv6<br>The default value is **1**. For an IPv6 address, this field must be explicitly set to **2**.| 798## UDPSendOptions 799 800Defines the parameters for sending data over a UDP socket connection. 801 802**System capability**: SystemCapability.Communication.NetStack 803 804| Name | Type | Mandatory| Description | 805| ------- | ---------------------------------- | ---- | -------------- | 806| data | string \| ArrayBuffer | Yes | Data to send. | 807| address | [NetAddress](#netaddress) | Yes | Destination address.| 808 809## UDPExtraOptions 810 811Defines other properties of the UDP socket connection. This API inherits from [ExtraOptionsBase](#extraoptionsbase7). 812 813**System capability**: SystemCapability.Communication.NetStack 814 815| Name | Type | Mandatory| Description | 816| ----------------- | ------- | ---- | -------------------------------- | 817| broadcast | boolean | No | Whether to send broadcast messages. The default value is **false**. | 818 819## SocketMessageInfo<sup>11+</sup> 820 821Defines the socket connection information. 822 823**System capability**: SystemCapability.Communication.NetStack 824 825| Name | Type | Mandatory| Description | 826| ---------- | ------ | ---- | ------------------------------------- | 827| message | ArrayBuffer | Yes | Received **message** event.| 828| remoteInfo | [SocketRemoteInfo](#socketremoteinfo) | Yes | Socket connection information.| 829 830## SocketStateBase 831 832Defines the status of the socket connection. 833 834**System capability**: SystemCapability.Communication.NetStack 835 836| Name | Type | Mandatory| Description | 837| ----------- | ------- | ---- | ---------- | 838| isBound | boolean | Yes | Whether the connection is in the bound state.| 839| isClose | boolean | Yes | Whether the connection is in the closed state.| 840| isConnected | boolean | Yes | Whether the connection is in the connected state.| 841 842## SocketRemoteInfo 843 844Defines information about the socket connection. 845 846**System capability**: SystemCapability.Communication.NetStack 847 848| Name | Type | Mandatory| Description | 849| ------- | ------ | ---- | ------------------------------------------------------------ | 850| address | string | Yes | Bound IP address. | 851| family | 'IPv4' \| 'IPv6' | Yes | Network protocol type.<br>- IPv4<br>- IPv6<br>The default value is **IPv4**.| 852| port | number | Yes | Port number. The value ranges from **0** to **65535**. | 853| size | number | Yes | Length of the server response message, in bytes. | 854 855## Description of UDP Error Codes 856 857The UDP error code mapping is in the format of 2301000 + Linux kernel error code. 858 859For details about error codes, see [Socket Error Codes](errorcode-net-socket.md). 860 861## socket.constructMulticastSocketInstance<sup>11+</sup> 862 863constructMulticastSocketInstance(): MulticastSocket 864 865Creates a **MulticastSocket** object. 866 867**System capability**: SystemCapability.Communication.NetStack 868 869**Return value** 870 871| Type | Description | 872| ----------------------------------- | ----------------------------- | 873| [MulticastSocket](#multicastsocket11) | **MulticastSocket** object.| 874 875**Example** 876 877```ts 878import { socket } from '@kit.NetworkKit'; 879let multicast: socket.MulticastSocket = socket.constructMulticastSocketInstance(); 880``` 881## MulticastSocket<sup>11+</sup> 882 883Defines a **MulticastSocket** connection. Before calling MulticastSocket APIs, you need to call [socket.constructMulticastSocketInstance](#socketconstructmulticastsocketinstance11) to create a **MulticastSocket** object. 884 885### addMembership<sup>11+</sup> 886 887addMembership(multicastAddress: NetAddress, callback: AsyncCallback\<void\>): void; 888 889Adds a member to a multicast group. This API uses an asynchronous callback to return the result. 890 891> **NOTE** 892> The IP addresses used for multicast belong to a specific range, for example, 224.0.0.0 to 239.255.255.255. 893> A member in a multicast group can serve as a sender or a receiver. Data is transmitted in broadcast mode, regardless of the client or server. 894 895**Required permissions**: ohos.permission.INTERNET 896 897**System capability**: SystemCapability.Communication.NetStack 898 899**Parameters** 900 901| Name | Type | Mandatory| Description | 902| ----------------- | ----------------------------- | ---- | ----------------------------------------- | 903| multicastAddress | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| 904| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error message is returned. | 905 906**Error codes** 907 908| ID| Error Message | 909| ------- | ----------------------- | 910| 401 | Parameter error. | 911| 201 | Permission denied. | 912| 2301022 | Invalid argument. | 913| 2301088 | Not a socket. | 914| 2301098 | Address in use. | 915 916**Example** 917 918```ts 919import { socket } from '@kit.NetworkKit'; 920 921let multicast: socket.MulticastSocket = socket.constructMulticastSocketInstance(); 922let addr: socket.NetAddress = { 923 address: '239.255.0.1', 924 port: 8080 925} 926multicast.addMembership(addr, (err: Object) => { 927 if (err) { 928 console.log('add membership fail, err: ' + JSON.stringify(err)); 929 return; 930 } 931 console.log('add membership success'); 932}) 933``` 934 935### addMembership<sup>11+</sup> 936 937addMembership(multicastAddress: NetAddress): Promise\<void\>; 938 939Adds a member to a multicast group. This API uses a promise to return the result. 940 941> **NOTE** 942> The IP addresses used for multicast belong to a specific range, for example, 224.0.0.0 to 239.255.255.255. 943> A member in a multicast group can serve as a sender or a receiver. Data is transmitted in broadcast mode, regardless of the client or server. 944 945**Required permissions**: ohos.permission.INTERNET 946 947**System capability**: SystemCapability.Communication.NetStack 948 949**Parameters** 950 951| Name | Type | Mandatory| Description | 952| ----------------- | ----------------------------- | ---- | -------------------------------------------- | 953| multicastAddress | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| 954 955**Return value** 956 957| Type | Description | 958| -------------- | ----------------------------------------------- | 959| Promise\<void\> | Promise used to return the result.| 960 961**Error codes** 962 963| ID| Error Message | 964| ------- | ----------------------- | 965| 401 | Parameter error. | 966| 201 | Permission denied. | 967| 2301088 | Not a socket. | 968| 2301098 | Address in use. | 969 970**Example** 971 972```ts 973import { socket } from '@kit.NetworkKit'; 974 975let multicast: socket.MulticastSocket = socket.constructMulticastSocketInstance(); 976let addr: socket.NetAddress = { 977 address: '239.255.0.1', 978 port: 8080 979} 980multicast.addMembership(addr).then(() => { 981 console.log('addMembership success'); 982}).catch((err: Object) => { 983 console.log('addMembership fail'); 984}); 985``` 986 987### dropMembership<sup>11+</sup> 988 989dropMembership(multicastAddress: NetAddress, callback: AsyncCallback\<void\>): void; 990 991Drop a **MulticastSocket** object from the multicast group. This API uses an asynchronous callback to return the result. 992 993> **NOTE** 994> The IP addresses used for multicast belong to a specific range, for example, 224.0.0.0 to 239.255.255.255. 995> You can drop only a member that has been added to a multicast group by using [addMembership](#addmembership11). 996 997**Required permissions**: ohos.permission.INTERNET 998 999**System capability**: SystemCapability.Communication.NetStack 1000 1001**Parameters** 1002 1003| Name | Type | Mandatory| Description | 1004| ----------------- | ----------------------------- | ---- | ------------------------------------------- | 1005| multicastAddress | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress). | 1006| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| 1007 1008**Error codes** 1009 1010| ID| Error Message | 1011| ------- | ----------------------- | 1012| 401 | Parameter error. | 1013| 201 | Permission denied. | 1014| 2301088 | Not a socket. | 1015| 2301098 | Address in use. | 1016 1017**Example** 1018 1019```ts 1020import { socket } from '@kit.NetworkKit'; 1021 1022let multicast: socket.MulticastSocket = socket.constructMulticastSocketInstance(); 1023let addr: socket.NetAddress = { 1024 address: '239.255.0.1', 1025 port: 8080 1026} 1027multicast.dropMembership(addr, (err: Object) => { 1028 if (err) { 1029 console.log('drop membership fail, err: ' + JSON.stringify(err)); 1030 return; 1031 } 1032 console.log('drop membership success'); 1033}) 1034``` 1035 1036### dropMembership<sup>11+</sup> 1037 1038dropMembership(multicastAddress: NetAddress): Promise\<void\>; 1039 1040Drop a **MulticastSocket** object from the multicast group. This API uses a promise to return the result. 1041 1042> **NOTE** 1043> The IP addresses used for multicast belong to a specific range, for example, 224.0.0.0 to 239.255.255.255. 1044> You can drop only a member that has been added to a multicast group by using [addMembership](#addmembership11). 1045 1046**Required permissions**: ohos.permission.INTERNET 1047 1048**System capability**: SystemCapability.Communication.NetStack 1049 1050**Parameters** 1051 1052| Name | Type | Mandatory| Description | 1053| ----------------- | ------------------------------------- | ---- | -------------------------------------------- | 1054| multicastAddress | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress). | 1055 1056**Return value** 1057 1058| Type | Description | 1059| -------------- | ----------------------------------------------- | 1060| Promise\<void\> | Promise used to return the result.| 1061 1062**Error codes** 1063 1064| ID| Error Message | 1065| ------- | ----------------------- | 1066| 401 | Parameter error. | 1067| 201 | Permission denied. | 1068| 2301088 | Not a socket. | 1069| 2301098 | Address in use. | 1070 1071**Example** 1072 1073```ts 1074import { socket } from '@kit.NetworkKit'; 1075 1076let multicast: socket.MulticastSocket = socket.constructMulticastSocketInstance(); 1077let addr: socket.NetAddress = { 1078 address: '239.255.0.1', 1079 port: 8080 1080} 1081multicast.dropMembership(addr).then(() => { 1082 console.log('drop membership success'); 1083}).catch((err: Object) => { 1084 console.log('drop membership fail'); 1085}); 1086``` 1087 1088### setMulticastTTL<sup>11+</sup> 1089 1090setMulticastTTL(ttl: number, callback: AsyncCallback\<void\>): void; 1091 1092Sets the time to live (TTL) for multicast packets. This API uses an asynchronous callback to return the result. 1093 1094> **NOTE** 1095> TTL is used to limit the maximum number of router hops for packet transmission on a network. 1096> The value ranges from 0 to 255. The default value is **1**. 1097> If the TTL value is **1**, multicast packets can be transmitted only to the host directly connected to the sender. If the TTL is set to a large value, multicast packets can be transmitted over a longer distance. 1098> This API is effective only after [addMembership](#addmembership11) is called. 1099 1100**System capability**: SystemCapability.Communication.NetStack 1101 1102**Parameters** 1103 1104| Name | Type | Mandatory| Description | 1105| ------------- | --------------------- | ---- | ----------------------------- | 1106| ttl | number | Yes | TTL value. The value is of the number type.| 1107| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error message is returned. | 1108 1109**Error codes** 1110 1111| ID| Error Message | 1112| ------- | ----------------------- | 1113| 401 | Parameter error. | 1114| 2301022 | Invalid argument. | 1115| 2301088 | Not a socket. | 1116 1117**Example** 1118 1119```ts 1120import { socket } from '@kit.NetworkKit'; 1121 1122let multicast: socket.MulticastSocket = socket.constructMulticastSocketInstance(); 1123let ttl = 8 1124multicast.setMulticastTTL(ttl, (err: Object) => { 1125 if (err) { 1126 console.log('set ttl fail, err: ' + JSON.stringify(err)); 1127 return; 1128 } 1129 console.log('set ttl success'); 1130}) 1131``` 1132 1133### setMulticastTTL<sup>11+</sup> 1134 1135setMulticastTTL(ttl: number): Promise\<void\>; 1136 1137Sets the time to live (TTL) for multicast packets. This API uses a promise to return the result. 1138 1139> **NOTE** 1140> TTL is used to limit the maximum number of router hops for packet transmission on a network. 1141> The value ranges from 0 to 255. The default value is **1**. 1142> If the TTL value is **1**, multicast packets can be transmitted only to the host directly connected to the sender. If the TTL is set to a large value, multicast packets can be transmitted over a longer distance. 1143> This API is effective only after [addMembership](#addmembership11) is called. 1144 1145**System capability**: SystemCapability.Communication.NetStack 1146 1147**Parameters** 1148 1149| Name | Type | Mandatory| Description | 1150| ------------- | ---------------------- | ---- | ------------------------------ | 1151| ttl | number | Yes | TTL value. The value is of the number type.| 1152 1153**Return value** 1154 1155| Type | Description | 1156| -------------- | ---------------------------------------------- | 1157| Promise\<void\> | Promise used to return the result.| 1158 1159**Error codes** 1160 1161| ID| Error Message | 1162| ------- | ----------------------- | 1163| 401 | Parameter error. | 1164| 2301022 | Invalid argument. | 1165| 2301088 | Not a socket. | 1166 1167**Example** 1168 1169```ts 1170import { socket } from '@kit.NetworkKit'; 1171 1172let multicast: socket.MulticastSocket = socket.constructMulticastSocketInstance(); 1173multicast.setMulticastTTL(8).then(() => { 1174 console.log('set ttl success'); 1175}).catch((err: Object) => { 1176 console.log('set ttl failed'); 1177}); 1178``` 1179 1180### getMulticastTTL<sup>11+</sup> 1181 1182getMulticastTTL(callback: AsyncCallback\<number\>): void; 1183 1184Obtains the TTL for multicast packets. This API uses an asynchronous callback to return the result. 1185 1186> **NOTE** 1187> TTL is used to limit the maximum number of router hops for packet transmission on a network. 1188> The value ranges from 0 to 255. The default value is **1**. 1189> If the TTL value is **1**, multicast packets can be transmitted only to the host directly connected to the sender. If the TTL is set to a large value, multicast packets can be transmitted over a longer distance. 1190> This API is effective only after [addMembership](#addmembership11) is called. 1191 1192**System capability**: SystemCapability.Communication.NetStack 1193 1194**Parameters** 1195 1196| Name | Type | Mandatory| Description | 1197| ------------- | ----------------------- | ---- | --------------------------- | 1198| callback | AsyncCallback\<number\> | Yes | Callback used to return the result. If the operation fails, an error message is returned. | 1199 1200**Error codes** 1201 1202| ID| Error Message | 1203| ------- | ----------------------- | 1204| 401 | Parameter error. | 1205| 2301088 | Not a socket. | 1206 1207**Example** 1208 1209```ts 1210import { socket } from '@kit.NetworkKit'; 1211 1212let multicast: socket.MulticastSocket = socket.constructMulticastSocketInstance(); 1213multicast.getMulticastTTL((err: Object, value: Number) => { 1214 if (err) { 1215 console.log('set ttl fail, err: ' + JSON.stringify(err)); 1216 return; 1217 } 1218 console.log('set ttl success, value: ' + JSON.stringify(value)); 1219}) 1220``` 1221 1222### getMulticastTTL<sup>11+</sup> 1223 1224getMulticastTTL(): Promise\<number\>; 1225 1226Obtains the TTL for multicast packets. This API uses a promise to return the result. 1227 1228> **NOTE** 1229> TTL is used to limit the maximum number of router hops for packet transmission on a network. 1230> The value ranges from 0 to 255. The default value is **1**. 1231> If the TTL value is **1**, multicast packets can be transmitted only to the host directly connected to the sender. If the TTL is set to a large value, multicast packets can be transmitted over a longer distance. 1232> This API is effective only after [addMembership](#addmembership11) is called. 1233 1234**System capability**: SystemCapability.Communication.NetStack 1235 1236**Return value** 1237 1238| Type | Description | 1239| ---------------- | --------------------------- | 1240| Promise\<number\> | Promise used to return the result.| 1241 1242**Error codes** 1243 1244| ID| Error Message | 1245| ------- | ----------------------- | 1246| 401 | Parameter error. | 1247| 2301088 | Not a socket. | 1248 1249**Example** 1250 1251```ts 1252import { socket } from '@kit.NetworkKit'; 1253 1254let multicast: socket.MulticastSocket = socket.constructMulticastSocketInstance(); 1255multicast.getMulticastTTL().then((value: Number) => { 1256 console.log('ttl: ', JSON.stringify(value)); 1257}).catch((err: Object) => { 1258 console.log('set ttl failed'); 1259}); 1260``` 1261 1262### setLoopbackMode<sup>11+</sup> 1263 1264setLoopbackMode(flag: boolean, callback: AsyncCallback\<void\>): void; 1265 1266Sets the loopback mode flag for multicast communication. This API uses an asynchronous callback to return the result. 1267 1268> **NOTE** 1269> Use this API to enable or disable the loopback mode. By default, the loopback mode is enabled. 1270> The value **true** indicates that the host is allowed to receive the multicast packets sent by itself, and the value **false** indicates the opposite. 1271> This API is effective only after [addMembership](#addmembership11) is called. 1272 1273**System capability**: SystemCapability.Communication.NetStack 1274 1275**Parameters** 1276 1277| Name | Type | Mandatory| Description | 1278| ------------- | --------------------- | ---- | ---------------------------- | 1279| flag | boolean | Yes | Loopback mode flag. The value is of the Boolean type. | 1280| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error message is returned. | 1281 1282**Error codes** 1283 1284| ID| Error Message | 1285| ------- | ----------------------- | 1286| 401 | Parameter error. | 1287| 2301088 | Not a socket. | 1288 1289**Example** 1290 1291```ts 1292import { socket } from '@kit.NetworkKit'; 1293 1294let multicast: socket.MulticastSocket = socket.constructMulticastSocketInstance(); 1295multicast.setLoopbackMode(false, (err: Object) => { 1296 if (err) { 1297 console.log('set loopback mode fail, err: ' + JSON.stringify(err)); 1298 return; 1299 } 1300 console.log('set loopback mode success'); 1301}) 1302``` 1303 1304### setLoopbackMode<sup>11+</sup> 1305 1306setLoopbackMode(flag: boolean): Promise\<void\>; 1307 1308Sets the loopback mode flag for multicast communication. This API uses an asynchronous callback to return the result. 1309 1310> **NOTE** 1311> Use this API to enable or disable the loopback mode. By default, the loopback mode is enabled. 1312> The value **true** indicates that the host is allowed to receive the multicast packets sent by itself, and the value **false** indicates the opposite. 1313> This API is effective only after [addMembership](#addmembership11) is called. 1314 1315**System capability**: SystemCapability.Communication.NetStack 1316 1317**Parameters** 1318 1319| Name | Type | Mandatory| Description | 1320| ------------- | ---------------------- | ---- | -------------------------------- | 1321| flag | boolean | Yes | Loopback mode flag. The value is of the Boolean type.| 1322 1323**Return value** 1324 1325| Type | Description | 1326| -------------- | ---------------------------------------------- | 1327| Promise\<void\> | Promise used to return the result.| 1328 1329**Error codes** 1330 1331| ID| Error Message | 1332| ------- | ----------------------- | 1333| 401 | Parameter error. | 1334| 2301088 | Not a socket. | 1335 1336**Example** 1337 1338```ts 1339import { socket } from '@kit.NetworkKit'; 1340 1341let multicast: socket.MulticastSocket = socket.constructMulticastSocketInstance(); 1342multicast.setLoopbackMode(false).then(() => { 1343 console.log('set loopback mode success'); 1344}).catch((err: Object) => { 1345 console.log('set loopback mode failed'); 1346}); 1347``` 1348 1349### getLoopbackMode<sup>11+</sup> 1350 1351getLoopbackMode(callback: AsyncCallback\<boolean\>): void; 1352 1353Obtains the loopback mode flag for multicast communication. This API uses a promise to return the result. 1354 1355> **NOTE** 1356> Use this API to check whether the loopback mode is enabled. 1357> The value **true** indicates that the loopback mode is enabled, and the value **false** indicates the opposite. When the loopback mode is disabled, the host is does not receive the multicast packets sent by itself. 1358> This API is effective only after [addMembership](#addmembership11) is called. 1359 1360**System capability**: SystemCapability.Communication.NetStack 1361 1362**Parameters** 1363 1364| Name | Type | Mandatory| Description | 1365| ------------- | ----------------------- | ---- | --------------------------- | 1366| callback | AsyncCallback\<number\> | Yes | Callback used to return the result. If the operation fails, an error message is returned. | 1367 1368**Error codes** 1369 1370| ID| Error Message | 1371| ------- | ----------------------- | 1372| 401 | Parameter error. | 1373| 2301088 | Not a socket. | 1374 1375**Example** 1376 1377```ts 1378import { socket } from '@kit.NetworkKit'; 1379 1380let multicast: socket.MulticastSocket = socket.constructMulticastSocketInstance(); 1381multicast.getLoopbackMode((err: Object, value: Boolean) => { 1382 if (err) { 1383 console.log('get loopback mode fail, err: ' + JSON.stringify(err)); 1384 return; 1385 } 1386 console.log('get loopback mode success, value: ' + JSON.stringify(value)); 1387}) 1388``` 1389 1390### getLoopbackMode<sup>11+</sup> 1391 1392getLoopbackMode(): Promise\<boolean\>; 1393 1394Obtains the loopback mode flag for multicast communication. This API uses a promise to return the result. 1395 1396> **NOTE** 1397> Use this API to check whether the loopback mode is enabled. 1398> The value **true** indicates that the loopback mode is enabled, and the value **false** indicates the opposite. When the loopback mode is disabled, the host is does not receive the multicast packets sent by itself. 1399> This API is effective only after [addMembership](#addmembership11) is called. 1400 1401**System capability**: SystemCapability.Communication.NetStack 1402 1403**Return value** 1404 1405| Type | Description | 1406| ---------------- | --------------------------- | 1407| Promise\<boolean\> | Promise used to return the result.| 1408 1409**Error codes** 1410 1411| ID| Error Message | 1412| ------- | ----------------------- | 1413| 401 | Parameter error. | 1414| 2301088 | Not a socket. | 1415 1416**Example** 1417 1418```ts 1419import { socket } from '@kit.NetworkKit'; 1420 1421let multicast: socket.MulticastSocket = socket.constructMulticastSocketInstance(); 1422multicast.getLoopbackMode().then((value: Boolean) => { 1423 console.log('loopback mode: ', JSON.stringify(value)); 1424}).catch((err: Object) => { 1425 console.log('get loopback mode failed'); 1426}); 1427``` 1428 1429## socket.constructTCPSocketInstance<sup>7+</sup> 1430 1431constructTCPSocketInstance(): TCPSocket 1432 1433Creates a **TCPSocket** object. 1434 1435**System capability**: SystemCapability.Communication.NetStack 1436 1437**Return value** 1438 1439| Type | Description | 1440| --------------------------------- | ---------------------- | 1441| [TCPSocket](#tcpsocket) | **TCPSocket** object.| 1442 1443**Example** 1444 1445```ts 1446import { socket } from '@kit.NetworkKit'; 1447let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1448``` 1449 1450## TCPSocket 1451 1452Defines a TCP socket connection. Before calling TCPSocket APIs, you need to call [socket.constructTCPSocketInstance](#socketconstructtcpsocketinstance7) to create a **TCPSocket** object. 1453 1454### bind 1455 1456bind(address: NetAddress, callback: AsyncCallback\<void\>): void 1457 1458Binds an IP address and a port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result. 1459 1460> **NOTE** 1461> If the bind operation fails due to a port conflict, the system will randomly allocate a port number. 1462> The TCP client can call **tcp.bind** to explicitly bind the IP address and port number, and then call **tcp.connect** to connect to the server. Alternatively, the TCP client can directly call **tcp.connect** to automatically bind the IP address and port number to connect to the server. 1463> If the IP address is **localhost** or **127.0.0.1**, only local loopback access is allowed; that is, the TCP client and the server are deployed on the same device. 1464 1465**Required permissions**: ohos.permission.INTERNET 1466 1467**System capability**: SystemCapability.Communication.NetStack 1468 1469**Parameters** 1470 1471| Name | Type | Mandatory| Description | 1472| -------- | ---------------------------------- | ---- | ------------------------------------------------------ | 1473| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| 1474| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error message is returned. | 1475 1476**Error codes** 1477 1478| ID| Error Message | 1479| ------- | ----------------------- | 1480| 401 | Parameter error. | 1481| 201 | Permission denied. | 1482 1483**Example** 1484 1485```ts 1486import { socket } from '@kit.NetworkKit'; 1487import { BusinessError } from '@kit.BasicServicesKit'; 1488 1489let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1490let bindAddr: socket.NetAddress = { 1491 address: '192.168.xx.xxx', 1492 port: 8080 1493} 1494tcp.bind(bindAddr, (err: BusinessError) => { 1495 if (err) { 1496 console.log('bind fail'); 1497 return; 1498 } 1499 console.log('bind success'); 1500}) 1501``` 1502 1503### bind 1504 1505bind(address: NetAddress): Promise\<void\> 1506 1507Binds an IP address and a port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result. 1508 1509> **NOTE** 1510> If the bind operation fails due to a port conflict, the system will randomly allocate a port number. 1511> The TCP client can call **tcp.bind** to explicitly bind the IP address and port number, and then call **tcp.connect** to connect to the server. Alternatively, the TCP client can directly call **tcp.connect** to automatically bind the IP address and port number to connect to the server. 1512> If the IP address is **localhost** or **127.0.0.1**, only local loopback access is allowed; that is, the TCP client and the server are deployed on the same device. 1513 1514**Required permissions**: ohos.permission.INTERNET 1515 1516**System capability**: SystemCapability.Communication.NetStack 1517 1518**Parameters** 1519 1520| Name | Type | Mandatory| Description | 1521| ------- | ---------------------------------- | ---- | ------------------------------------------------------ | 1522| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| 1523 1524**Return value** 1525 1526| Type | Description | 1527| --------------- | ------------------------------------------------------- | 1528| Promise\<void\> | Promise used to return the result.| 1529 1530**Error codes** 1531 1532| ID| Error Message | 1533| ------- | ----------------------- | 1534| 401 | Parameter error. | 1535| 201 | Permission denied. | 1536 1537**Example** 1538 1539```ts 1540import { socket } from '@kit.NetworkKit'; 1541import { BusinessError } from '@kit.BasicServicesKit'; 1542 1543let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1544let bindAddr: socket.NetAddress = { 1545 address: '192.168.xx.xxx', 1546 port: 8080 1547} 1548tcp.bind(bindAddr).then(() => { 1549 console.log('bind success'); 1550}).catch((err: BusinessError) => { 1551 console.log('bind fail'); 1552}); 1553``` 1554 1555### connect 1556 1557connect(options: TCPConnectOptions, callback: AsyncCallback\<void\>): void 1558 1559Sets up a connection to the specified IP address and port number. This API uses an asynchronous callback to return the result. 1560 1561> **NOTE** 1562> This API allows you to connect to the TCP server without first executing **tcp.bind**. 1563 1564**Required permissions**: ohos.permission.INTERNET 1565 1566**System capability**: SystemCapability.Communication.NetStack 1567 1568**Parameters** 1569 1570| Name | Type | Mandatory| Description | 1571| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | 1572| options | [TCPConnectOptions](#tcpconnectoptions) | Yes | TCP socket connection parameters. For details, see [TCPConnectOptions](#tcpconnectoptions).| 1573| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error message is returned. | 1574 1575**Error codes** 1576 1577| ID| Error Message | 1578| ------- | ----------------------- | 1579| 401 | Parameter error. | 1580| 201 | Permission denied. | 1581 1582**Example** 1583 1584```ts 1585import { socket } from '@kit.NetworkKit'; 1586import { BusinessError } from '@kit.BasicServicesKit'; 1587 1588let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1589let netAddress: socket.NetAddress = { 1590 address: '192.168.xx.xxx', 1591 port: 8080 1592} 1593let tcpconnectoptions: socket.TCPConnectOptions = { 1594 address: netAddress, 1595 timeout: 6000 1596} 1597tcp.connect(tcpconnectoptions, (err: BusinessError) => { 1598 if (err) { 1599 console.log('connect fail'); 1600 return; 1601 } 1602 console.log('connect success'); 1603}) 1604``` 1605 1606### connect 1607 1608connect(options: TCPConnectOptions): Promise\<void\> 1609 1610Sets up a connection to the specified IP address and port number. This API uses a promise to return the result. 1611 1612> **NOTE** 1613> This API allows you to connect to the TCP server without first executing **tcp.bind**. 1614 1615**Required permissions**: ohos.permission.INTERNET 1616 1617**System capability**: SystemCapability.Communication.NetStack 1618 1619**Parameters** 1620 1621| Name | Type | Mandatory| Description | 1622| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | 1623| options | [TCPConnectOptions](#tcpconnectoptions) | Yes | TCP socket connection parameters. For details, see [TCPConnectOptions](#tcpconnectoptions).| 1624 1625**Return value** 1626 1627| Type | Description | 1628| -------------- | --------------------------------------------------------- | 1629| Promise\<void\> | Promise used to return the result.| 1630 1631**Error codes** 1632 1633| ID| Error Message | 1634| ------- | ----------------------- | 1635| 401 | Parameter error. | 1636| 201 | Permission denied. | 1637 1638**Example** 1639 1640```ts 1641import { socket } from '@kit.NetworkKit'; 1642import { BusinessError } from '@kit.BasicServicesKit'; 1643 1644let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1645let netAddress: socket.NetAddress = { 1646 address: '192.168.xx.xxx', 1647 port: 8080 1648} 1649let tcpconnectoptions: socket.TCPConnectOptions = { 1650 address: netAddress, 1651 timeout: 6000 1652} 1653tcp.connect(tcpconnectoptions).then(() => { 1654 console.log('connect success') 1655}).catch((err: BusinessError) => { 1656 console.log('connect fail'); 1657}); 1658``` 1659 1660### send 1661 1662send(options: TCPSendOptions, callback: AsyncCallback\<void\>): void 1663 1664Sends data over a TCP socket connection. This API uses an asynchronous callback to return the result. 1665 1666> **NOTE** 1667> This API can be called only after **connect** is successfully called. Call the API in the worker thread or taskpool thread as this operation is time-consuming. 1668 1669**Required permissions**: ohos.permission.INTERNET 1670 1671**System capability**: SystemCapability.Communication.NetStack 1672 1673**Parameters** 1674 1675| Name | Type | Mandatory| Description | 1676| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | 1677| options | [TCPSendOptions](#tcpsendoptions) | Yes | Parameters for sending data over a TCP socket connection. For details, see [TCPSendOptions](#tcpsendoptions).| 1678| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error message is returned. | 1679 1680**Error codes** 1681 1682| ID| Error Message | 1683| ------- | ----------------------- | 1684| 401 | Parameter error. | 1685| 201 | Permission denied. | 1686 1687**Example** 1688 1689```ts 1690import { socket } from '@kit.NetworkKit'; 1691import { BusinessError } from '@kit.BasicServicesKit'; 1692 1693let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1694let netAddress: socket.NetAddress = { 1695 address: '192.168.xx.xxx', 1696 port: 8080 1697} 1698let tcpconnectoptions: socket.TCPConnectOptions = { 1699 address: netAddress, 1700 timeout: 6000 1701} 1702tcp.connect(tcpconnectoptions, () => { 1703 console.log('connect success'); 1704 let tcpSendOptions: socket.TCPSendOptions = { 1705 data: 'Hello, server!' 1706 } 1707 tcp.send(tcpSendOptions, (err: BusinessError) => { 1708 if (err) { 1709 console.log('send fail'); 1710 return; 1711 } 1712 console.log('send success'); 1713 }) 1714}) 1715``` 1716 1717### send 1718 1719send(options: TCPSendOptions): Promise\<void\> 1720 1721Sends data over a TCP socket connection. This API uses a promise to return the result. 1722 1723> **NOTE** 1724> This API can be called only after **connect** is successfully called. Call the API in the worker thread or taskpool thread as this operation is time-consuming. 1725 1726**Required permissions**: ohos.permission.INTERNET 1727 1728**System capability**: SystemCapability.Communication.NetStack 1729 1730**Parameters** 1731 1732| Name | Type | Mandatory| Description | 1733| ------- | --------------------------------------- | ---- | ------------------------------------------------------------ | 1734| options | [TCPSendOptions](#tcpsendoptions) | Yes | Parameters for sending data over a TCP socket connection. For details, see [TCPSendOptions](#tcpsendoptions).| 1735 1736**Return value** 1737 1738| Type | Description | 1739| -------------- | ------------------------------------------------- | 1740| Promise\<void\> | Promise used to return the result.| 1741 1742**Error codes** 1743 1744| ID| Error Message | 1745| ------- | ----------------------- | 1746| 401 | Parameter error. | 1747| 201 | Permission denied. | 1748 1749**Example** 1750 1751```ts 1752import { socket } from '@kit.NetworkKit'; 1753import { BusinessError } from '@kit.BasicServicesKit'; 1754 1755let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1756let netAddress: socket.NetAddress = { 1757 address: '192.168.xx.xxx', 1758 port: 8080 1759} 1760let tcpconnectoptions: socket.TCPConnectOptions = { 1761 address: netAddress, 1762 timeout: 6000 1763} 1764tcp.connect(tcpconnectoptions, () => { 1765 console.log('connect success'); 1766 let tcpSendOptions: socket.TCPSendOptions = { 1767 data: 'Hello, server!' 1768 } 1769 tcp.send(tcpSendOptions).then(() => { 1770 console.log('send success'); 1771 }).catch((err: BusinessError) => { 1772 console.log('send fail'); 1773 }); 1774}) 1775``` 1776 1777### close 1778 1779close(callback: AsyncCallback\<void\>): void 1780 1781Closes a TCP socket connection. This API uses an asynchronous callback to return the result. 1782 1783**Required permissions**: ohos.permission.INTERNET 1784 1785**System capability**: SystemCapability.Communication.NetStack 1786 1787**Parameters** 1788 1789| Name | Type | Mandatory| Description | 1790| -------- | --------------------- | ---- | ---------- | 1791| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| 1792 1793**Error codes** 1794 1795| ID| Error Message | 1796| ------- | ----------------------- | 1797| 201 | Permission denied. | 1798 1799**Example** 1800 1801```ts 1802import { socket } from '@kit.NetworkKit'; 1803import { BusinessError } from '@kit.BasicServicesKit'; 1804 1805let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1806 1807tcp.close((err: BusinessError) => { 1808 if (err) { 1809 console.log('close fail'); 1810 return; 1811 } 1812 console.log('close success'); 1813}) 1814``` 1815 1816### close 1817 1818close(): Promise\<void\> 1819 1820Closes a TCP socket connection. This API uses a promise to return the result. 1821 1822**Required permissions**: ohos.permission.INTERNET 1823 1824**System capability**: SystemCapability.Communication.NetStack 1825 1826**Return value** 1827 1828| Type | Description | 1829| -------------- | ----------------------------------------- | 1830| Promise\<void\> | Promise used to return the result.| 1831 1832**Error codes** 1833 1834| ID| Error Message | 1835| ------- | ----------------------- | 1836| 201 | Permission denied. | 1837 1838**Example** 1839 1840```ts 1841import { socket } from '@kit.NetworkKit'; 1842 1843let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1844 1845tcp.close().then(() => { 1846 console.log('close success'); 1847}).catch((err: BusinessError) => { 1848 console.log('close fail'); 1849}); 1850``` 1851 1852### getRemoteAddress 1853 1854getRemoteAddress(callback: AsyncCallback\<NetAddress\>): void 1855 1856Obtains the remote address of a socket connection. This API uses an asynchronous callback to return the result. 1857 1858> **NOTE** 1859> This API can be called only after **connect** is successfully called. 1860 1861**Required permissions**: ohos.permission.INTERNET 1862 1863**System capability**: SystemCapability.Communication.NetStack 1864 1865**Parameters** 1866 1867| Name | Type | Mandatory| Description | 1868| -------- | ------------------------------------------------- | ---- | ---------- | 1869| 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.| 1870 1871**Error codes** 1872 1873| ID| Error Message | 1874| ------- | ----------------------- | 1875| 201 | Permission denied. | 1876 1877**Example** 1878 1879```ts 1880import { socket } from '@kit.NetworkKit'; 1881import { BusinessError } from '@kit.BasicServicesKit'; 1882 1883let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1884let netAddress: socket.NetAddress = { 1885 address: '192.168.xx.xxx', 1886 port: 8080 1887} 1888let tcpconnectoptions: socket.TCPConnectOptions = { 1889 address: netAddress, 1890 timeout: 6000 1891} 1892tcp.connect(tcpconnectoptions, () => { 1893 console.log('connect success'); 1894 tcp.getRemoteAddress((err: BusinessError, data: socket.NetAddress) => { 1895 if (err) { 1896 console.log('getRemoteAddressfail'); 1897 return; 1898 } 1899 console.log('getRemoteAddresssuccess:' + JSON.stringify(data)); 1900 }) 1901}); 1902``` 1903 1904### getRemoteAddress 1905 1906getRemoteAddress(): Promise\<NetAddress\> 1907 1908Obtains the remote address of a socket connection. This API uses a promise to return the result. 1909 1910> **NOTE** 1911> This API can be called only after **connect** is successfully called. 1912 1913**Required permissions**: ohos.permission.INTERNET 1914 1915**System capability**: SystemCapability.Communication.NetStack 1916 1917**Return value** 1918 1919| Type | Description | 1920| ------------------------------------------ | ------------------------------------------ | 1921| Promise\<[NetAddress](#netaddress)\> | Promise used to return the result.| 1922 1923**Error codes** 1924 1925| ID| Error Message | 1926| ------- | ----------------------- | 1927| 201 | Permission denied. | 1928 1929**Example** 1930 1931```ts 1932import { socket } from '@kit.NetworkKit'; 1933import { BusinessError } from '@kit.BasicServicesKit'; 1934 1935let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1936let netAddress: socket.NetAddress = { 1937 address: '192.168.xx.xxx', 1938 port: 8080 1939} 1940let tcpconnectoptions: socket.TCPConnectOptions = { 1941 address: netAddress, 1942 timeout: 6000 1943} 1944tcp.connect(tcpconnectoptions).then(() => { 1945 console.log('connect success'); 1946 tcp.getRemoteAddress().then(() => { 1947 console.log('getRemoteAddress success'); 1948 }).catch((err: BusinessError) => { 1949 console.log('getRemoteAddressfail'); 1950 }); 1951}).catch((err: BusinessError) => { 1952 console.log('connect fail'); 1953}); 1954``` 1955 1956### getState 1957 1958getState(callback: AsyncCallback\<SocketStateBase\>): void 1959 1960Obtains the status of the TCP socket connection. This API uses an asynchronous callback to return the result. 1961 1962> **NOTE** 1963> This API can be called only after **bind** or **connect** is successfully called. 1964 1965**Required permissions**: ohos.permission.INTERNET 1966 1967**System capability**: SystemCapability.Communication.NetStack 1968 1969**Parameters** 1970 1971| Name | Type | Mandatory| Description | 1972| -------- | ------------------------------------------------------ | ---- | ---------- | 1973| callback | AsyncCallback\<[SocketStateBase](#socketstatebase)\> | Yes | Callback used to return the result. If the operation is successful, the status of the TCP socket is returned. If the operation fails, an error message is returned.| 1974 1975**Error codes** 1976 1977| ID| Error Message | 1978| ------- | ----------------------- | 1979| 201 | Permission denied. | 1980 1981**Example** 1982 1983```ts 1984import { socket } from '@kit.NetworkKit'; 1985import { BusinessError } from '@kit.BasicServicesKit'; 1986 1987let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1988let netAddress: socket.NetAddress = { 1989 address: '192.168.xx.xxx', 1990 port: 8080 1991} 1992let tcpconnectoptions: socket.TCPConnectOptions = { 1993 address: netAddress, 1994 timeout: 6000 1995} 1996tcp.connect(tcpconnectoptions, () => { 1997 console.log('connect success'); 1998 tcp.getState((err: BusinessError, data: socket.SocketStateBase) => { 1999 if (err) { 2000 console.log('getState fail'); 2001 return; 2002 } 2003 console.log('getState success:' + JSON.stringify(data)); 2004 }); 2005}); 2006``` 2007 2008### getState 2009 2010getState(): Promise\<SocketStateBase\> 2011 2012Obtains the status of the TCP socket connection. This API uses a promise to return the result. 2013 2014> **NOTE** 2015> This API can be called only after **bind** or **connect** is successfully called. 2016 2017**Required permissions**: ohos.permission.INTERNET 2018 2019**System capability**: SystemCapability.Communication.NetStack 2020 2021**Return value** 2022 2023| Type | Description | 2024| ----------------------------------------------- | ----------------------------------------- | 2025| Promise\<[SocketStateBase](#socketstatebase)\> | Promise used to return the result.| 2026 2027**Error codes** 2028 2029| ID| Error Message | 2030| ------- | ----------------------- | 2031| 201 | Permission denied. | 2032 2033**Example** 2034 2035```ts 2036import { socket } from '@kit.NetworkKit'; 2037import { BusinessError } from '@kit.BasicServicesKit'; 2038 2039let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 2040let netAddress: socket.NetAddress = { 2041 address: '192.168.xx.xxx', 2042 port: 8080 2043} 2044let tcpconnectoptions: socket.TCPConnectOptions = { 2045 address: netAddress, 2046 timeout: 6000 2047} 2048tcp.connect(tcpconnectoptions).then(() => { 2049 console.log('connect success'); 2050 tcp.getState().then(() => { 2051 console.log('getState success'); 2052 }).catch((err: BusinessError) => { 2053 console.log('getState fail'); 2054 }); 2055}).catch((err: BusinessError) => { 2056 console.log('connect fail'); 2057}); 2058``` 2059 2060### getSocketFd<sup>10+</sup> 2061 2062getSocketFd(callback: AsyncCallback\<number\>): void 2063 2064Obtains the file descriptor of the **TCPSocket** object. This API uses an asynchronous callback to return the result. 2065 2066> **NOTE** 2067> This API can be called only after **bind** or **connect** is successfully called. 2068 2069**System capability**: SystemCapability.Communication.NetStack 2070 2071**Parameters** 2072 2073| Name | Type | Mandatory| Description | 2074| -------- | ------------------------------------------------------ | ---- | ---------- | 2075| callback | AsyncCallback\<number\> | Yes | Callback used to return the result. If the operation is successful, the file descriptor of the socket is returned. Otherwise, **undefined** is returned.| 2076 2077**Example** 2078 2079```ts 2080import { socket } from '@kit.NetworkKit'; 2081import { BusinessError } from '@kit.BasicServicesKit'; 2082 2083let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 2084let bindAddr: socket.NetAddress = { 2085 address: '0.0.0.0' 2086} 2087tcp.bind(bindAddr) 2088let netAddress: socket.NetAddress = { 2089 address: '192.168.xx.xxx', 2090 port: 8080 2091} 2092let tcpconnectoptions: socket.TCPConnectOptions = { 2093 address: netAddress, 2094 timeout: 6000 2095} 2096tcp.connect(tcpconnectoptions) 2097tcp.getSocketFd((err: BusinessError, data: number) => { 2098 console.info("getSocketFd failed: " + err); 2099 console.info("tunenlfd: " + data); 2100}) 2101``` 2102### getSocketFd<sup>10+</sup> 2103 2104getSocketFd(): Promise\<number\> 2105 2106Obtains the file descriptor of the **TCPSocket** object. This API uses a promise to return the result. 2107 2108> **NOTE** 2109> This API can be called only after **bind** or **connect** is successfully called. 2110 2111**System capability**: SystemCapability.Communication.NetStack 2112 2113**Return value** 2114 2115| Type | Description | 2116| ----------------------------------------------- | ----------------------------------------- | 2117| Promise\<number\> | Promise used to return the result.| 2118 2119**Example** 2120 2121```ts 2122import { socket } from '@kit.NetworkKit'; 2123import { BusinessError } from '@kit.BasicServicesKit'; 2124 2125let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 2126let bindAddr: socket.NetAddress = { 2127 address: '0.0.0.0' 2128} 2129tcp.bind(bindAddr) 2130let netAddress: socket.NetAddress = { 2131 address: '192.168.xx.xxx', 2132 port: 8080 2133} 2134let tcpconnectoptions: socket.TCPConnectOptions = { 2135 address: netAddress, 2136 timeout: 6000 2137} 2138tcp.connect(tcpconnectoptions) 2139tcp.getSocketFd().then((data: number) => { 2140 console.info("tunenlfd: " + data); 2141}) 2142``` 2143 2144### setExtraOptions 2145 2146setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\<void\>): void 2147 2148Sets other properties of the TCP socket connection. This API uses an asynchronous callback to return the result. 2149 2150> **NOTE** 2151> This API can be called only after **bind** or **connect** is successfully called. 2152 2153**Required permissions**: ohos.permission.INTERNET 2154 2155**System capability**: SystemCapability.Communication.NetStack 2156 2157**Parameters** 2158 2159| Name | Type | Mandatory| Description | 2160| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | 2161| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCP socket connection. For details, see [TCPExtraOptions](#tcpextraoptions).| 2162| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error message is returned. | 2163 2164**Error codes** 2165 2166| ID| Error Message | 2167| ------- | ----------------------- | 2168| 401 | Parameter error. | 2169| 201 | Permission denied. | 2170 2171**Example** 2172 2173```ts 2174import { socket } from '@kit.NetworkKit'; 2175import { BusinessError } from '@kit.BasicServicesKit'; 2176 2177let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 2178let netAddress: socket.NetAddress = { 2179 address: '192.168.xx.xxx', 2180 port: 8080 2181} 2182let tcpconnectoptions: socket.TCPConnectOptions = { 2183 address: netAddress, 2184 timeout: 6000 2185} 2186 2187interface SocketLinger { 2188 on: boolean; 2189 linger: number; 2190} 2191 2192tcp.connect(tcpconnectoptions, () => { 2193 console.log('connect success'); 2194 let tcpExtraOptions: socket.TCPExtraOptions = { 2195 keepAlive: true, 2196 OOBInline: true, 2197 TCPNoDelay: true, 2198 socketLinger: { on: true, linger: 10 } as SocketLinger, 2199 receiveBufferSize: 1000, 2200 sendBufferSize: 1000, 2201 reuseAddress: true, 2202 socketTimeout: 3000 2203 } 2204 tcp.setExtraOptions(tcpExtraOptions, (err: BusinessError) => { 2205 if (err) { 2206 console.log('setExtraOptions fail'); 2207 return; 2208 } 2209 console.log('setExtraOptions success'); 2210 }); 2211}); 2212``` 2213 2214### setExtraOptions 2215 2216setExtraOptions(options: TCPExtraOptions): Promise\<void\> 2217 2218Sets other properties of the TCP socket connection. This API uses a promise to return the result. 2219 2220> **NOTE** 2221> This API can be called only after **bind** or **connect** is successfully called. 2222 2223**Required permissions**: ohos.permission.INTERNET 2224 2225**System capability**: SystemCapability.Communication.NetStack 2226 2227**Parameters** 2228 2229| Name | Type | Mandatory| Description | 2230| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | 2231| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCP socket connection. For details, see [TCPExtraOptions](#tcpextraoptions).| 2232 2233**Return value** 2234 2235| Type | Description | 2236| -------------- | --------------------------------------------------- | 2237| Promise\<void\> | Promise used to return the result.| 2238 2239**Error codes** 2240 2241| ID| Error Message | 2242| ------- | ----------------------- | 2243| 401 | Parameter error. | 2244| 201 | Permission denied. | 2245 2246**Example** 2247 2248```ts 2249import { socket } from '@kit.NetworkKit'; 2250import { BusinessError } from '@kit.BasicServicesKit'; 2251 2252let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 2253let netAddress: socket.NetAddress = { 2254 address: '192.168.xx.xxx', 2255 port: 8080 2256} 2257let tcpconnectoptions: socket.TCPConnectOptions = { 2258 address: netAddress, 2259 timeout: 6000 2260} 2261 2262interface SocketLinger { 2263 on: boolean; 2264 linger: number; 2265} 2266 2267tcp.connect(tcpconnectoptions, () => { 2268 console.log('connect success'); 2269 let tcpExtraOptions: socket.TCPExtraOptions = { 2270 keepAlive: true, 2271 OOBInline: true, 2272 TCPNoDelay: true, 2273 socketLinger: { on: true, linger: 10 } as SocketLinger, 2274 receiveBufferSize: 1000, 2275 sendBufferSize: 1000, 2276 reuseAddress: true, 2277 socketTimeout: 3000 2278 } 2279 tcp.setExtraOptions(tcpExtraOptions).then(() => { 2280 console.log('setExtraOptions success'); 2281 }).catch((err: BusinessError) => { 2282 console.log('setExtraOptions fail'); 2283 }); 2284}); 2285``` 2286 2287### getLocalAddress<sup>12+</sup> 2288 2289getLocalAddress(): Promise\<NetAddress\> 2290 2291Obtains the local socket address of a **TCPSocket** connection. This API uses a promise to return the result. 2292 2293> **NOTE** 2294> This API can be called only after **bind** is successfully called. 2295 2296**System capability**: SystemCapability.Communication.NetStack 2297 2298**Return value** 2299 2300| Type | Description | 2301| -------------- | --------------------------------------------------- | 2302| Promise\<[NetAddress](#netaddress)\> | Promise used to return the result.| 2303 2304**Error codes** 2305 2306| ID| Error Message | 2307| -------- | ------------------------------------------- | 2308| 2300002 | System internal error. | 2309| 2301009 | Bad file descriptor. | 2310| 2303188 | Socket operation on non-socket. | 2311 2312**Example** 2313 2314```ts 2315import { socket } from '@kit.NetworkKit'; 2316import { BusinessError } from '@kit.BasicServicesKit'; 2317 2318let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 2319let bindAddr: socket.NetAddress = { 2320 address: '192.168.xx.xxx', 2321 family: 1, 2322 port: 8080 2323} 2324tcp.bind(bindAddr).then(() => { 2325 tcp.getLocalAddress().then((localAddress: socket.NetAddress) => { 2326 console.info("SUCCESS! Address:" + JSON.stringify(localAddress)); 2327 }).catch((err: BusinessError) => { 2328 console.error("FAILED! Error:" + JSON.stringify(err)); 2329 }) 2330}).catch((err: BusinessError) => { 2331 console.error('bind fail'); 2332}); 2333``` 2334 2335### on('message') 2336 2337on(type: 'message', callback: Callback<SocketMessageInfo\>): void 2338 2339Subscribes to **message** events of the TCP socket connection. This API uses an asynchronous callback to return the result. 2340 2341**System capability**: SystemCapability.Communication.NetStack 2342 2343**Parameters** 2344 2345| Name | Type | Mandatory| Description | 2346| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 2347| type | string | Yes | Event type.<br/> **message**: message receiving event.| 2348| callback | Callback\<[SocketMessageInfo](#socketmessageinfo11)\> | Yes | Callback used to return the result. | 2349 2350**Example** 2351 2352```ts 2353import { socket } from '@kit.NetworkKit'; 2354import { BusinessError } from '@kit.BasicServicesKit'; 2355 2356let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 2357let messageView = ''; 2358tcp.on('message', (value: socket.SocketMessageInfo) => { 2359 for (let i: number = 0; i < value.message.byteLength; i++) { 2360 let uint8Array = new Uint8Array(value.message) 2361 let messages = uint8Array[i] 2362 let message = String.fromCharCode(messages); 2363 messageView += message; 2364 } 2365 console.log('on message message: ' + JSON.stringify(messageView)); 2366 console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo)); 2367}); 2368``` 2369 2370### off('message') 2371 2372off(type: 'message', callback?: Callback<SocketMessageInfo\>): void 2373 2374Unsubscribes from **message** events of the TCP socket connection. This API uses an asynchronous callback to return the result. 2375 2376**System capability**: SystemCapability.Communication.NetStack 2377 2378**Parameters** 2379 2380| Name | Type | Mandatory| Description | 2381| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 2382| type | string | Yes | Event type.<br/> **message**: message receiving event.| 2383| callback | Callback\<[SocketMessageInfo](#socketmessageinfo11)\> | No | Callback used to return the result. | 2384 2385**Example** 2386 2387```ts 2388import { socket } from '@kit.NetworkKit'; 2389import { BusinessError } from '@kit.BasicServicesKit'; 2390 2391let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 2392let messageView = ''; 2393let callback = (value: socket.SocketMessageInfo) => { 2394 for (let i: number = 0; i < value.message.byteLength; i++) { 2395 let uint8Array = new Uint8Array(value.message) 2396 let messages = uint8Array[i] 2397 let message = String.fromCharCode(messages); 2398 messageView += message; 2399 } 2400 console.log('on message message: ' + JSON.stringify(messageView)); 2401 console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo)); 2402} 2403tcp.on('message', callback); 2404// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 2405tcp.off('message', callback); 2406tcp.off('message'); 2407``` 2408 2409### on('connect' | 'close') 2410 2411on(type: 'connect' | 'close', callback: Callback\<void\>): void 2412 2413Subscribes to connection or close events of the TCP socket connection. This API uses an asynchronous callback to return the result. 2414 2415**System capability**: SystemCapability.Communication.NetStack 2416 2417**Parameters** 2418 2419| Name | Type | Mandatory| Description | 2420| -------- | ---------------- | ---- | ------------------------------------------------------------ | 2421| type | string | Yes | Event type.<br>- **connect**: connection event.<br>- **close**: close event.| 2422| callback | Callback\<void\> | Yes | Callback used to return the result. | 2423 2424**Example** 2425 2426```ts 2427import { socket } from '@kit.NetworkKit'; 2428import { BusinessError } from '@kit.BasicServicesKit'; 2429 2430let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 2431tcp.on('connect', () => { 2432 console.log("on connect success") 2433}); 2434tcp.on('close', () => { 2435 console.log("on close success") 2436}); 2437``` 2438 2439### off('connect' | 'close') 2440 2441off(type: 'connect' | 'close', callback?: Callback\<void\>): void 2442 2443Unsubscribes from connection or close events of the TCP socket connection. This API uses an asynchronous callback to return the result. 2444 2445**System capability**: SystemCapability.Communication.NetStack 2446 2447**Parameters** 2448 2449| Name | Type | Mandatory| Description | 2450| -------- | ---------------- | ---- | ------------------------------------------------------------ | 2451| type | string | Yes | Event type.<br>- **connect**: connection event.<br>- **close**: close event.| 2452| callback | Callback\<void\> | No | Callback used to return the result. | 2453 2454**Example** 2455 2456```ts 2457import { socket } from '@kit.NetworkKit'; 2458import { BusinessError } from '@kit.BasicServicesKit'; 2459 2460let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 2461let callback1 = () => { 2462 console.log("on connect success"); 2463} 2464tcp.on('connect', callback1); 2465// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 2466tcp.off('connect', callback1); 2467tcp.off('connect'); 2468let callback2 = () => { 2469 console.log("on close success"); 2470} 2471tcp.on('close', callback2); 2472// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 2473tcp.off('close', callback2); 2474tcp.off('close'); 2475``` 2476 2477### on('error') 2478 2479on(type: 'error', callback: ErrorCallback): void 2480 2481Subscribes to **error** events of the TCP socket connection. This API uses an asynchronous callback to return the result. 2482 2483**System capability**: SystemCapability.Communication.NetStack 2484 2485**Parameters** 2486 2487| Name | Type | Mandatory| Description | 2488| -------- | ------------- | ---- | ------------------------------------ | 2489| type | string | Yes | Event type.<br/> **error**: error event.| 2490| callback | ErrorCallback | Yes | Callback used to return the result. | 2491 2492**Example** 2493 2494```ts 2495import { socket } from '@kit.NetworkKit'; 2496import { BusinessError } from '@kit.BasicServicesKit'; 2497 2498let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 2499tcp.on('error', (err: BusinessError) => { 2500 console.log("on error, err:" + JSON.stringify(err)) 2501}); 2502``` 2503 2504### off('error') 2505 2506off(type: 'error', callback?: ErrorCallback): void 2507 2508Unsubscribes from **error** events of the TCP socket connection. This API uses an asynchronous callback to return the result. 2509 2510**System capability**: SystemCapability.Communication.NetStack 2511 2512**Parameters** 2513 2514| Name | Type | Mandatory| Description | 2515| -------- | ------------- | ---- | ------------------------------------ | 2516| type | string | Yes | Event type.<br/> **error**: error event.| 2517| callback | ErrorCallback | No | Callback used to return the result. | 2518 2519**Example** 2520 2521```ts 2522import { socket } from '@kit.NetworkKit'; 2523import { BusinessError } from '@kit.BasicServicesKit'; 2524 2525let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 2526let callback = (err: BusinessError) => { 2527 console.log("on error, err:" + JSON.stringify(err)); 2528} 2529tcp.on('error', callback); 2530// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 2531tcp.off('error', callback); 2532tcp.off('error'); 2533``` 2534 2535## TCPConnectOptions 2536 2537Defines TCP socket connection parameters. 2538 2539**System capability**: SystemCapability.Communication.NetStack 2540 2541| Name | Type | Mandatory| Description | 2542| ------- | ---------------------------------- | ---- | -------------------------- | 2543| address | [NetAddress](#netaddress) | Yes | Bound IP address and port number. | 2544| timeout | number | No | Timeout duration of the TCP socket connection, in ms.| 2545 2546## TCPSendOptions 2547 2548Defines the parameters for sending data over a TCP socket connection. 2549 2550**System capability**: SystemCapability.Communication.NetStack 2551 2552| Name | Type | Mandatory| Description | 2553| -------- | ------ | ---- | ------------------------------------------------------------ | 2554| data | string\| ArrayBuffer | Yes | Data to send. | 2555| 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**.| 2556 2557## TCPExtraOptions 2558 2559Defines other properties of the TCP socket connection. This API inherits from [ExtraOptionsBase](#extraoptionsbase7). 2560 2561**System capability**: SystemCapability.Communication.NetStack 2562 2563| Name | Type | Mandatory| Description | 2564| ----------------- | ------- | ---- | ------------------------------------------------------------ | 2565| keepAlive | boolean | No | Whether to keep the connection alive. The default value is **false**. | 2566| OOBInline | boolean | No | Whether to enable OOBInline. The default value is **false**. | 2567| TCPNoDelay | boolean | No | Whether to enable no-delay on the TCP socket connection. The default value is **false**. | 2568| socketLinger | \{on:boolean, linger:number\} | No | 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**.| 2569 2570## socket.constructTCPSocketServerInstance<sup>10+</sup> 2571 2572constructTCPSocketServerInstance(): TCPSocketServer 2573 2574Creates a **TCPSocketServer** object. 2575 2576**System capability**: SystemCapability.Communication.NetStack 2577 2578**Return value** 2579 2580| Type | Description | 2581| ---------------------------------- | ---------------------------- | 2582| [TCPSocketServer](#tcpsocketserver10) | **TCPSocketServer** object.| 2583 2584**Example** 2585 2586```ts 2587import { socket } from '@kit.NetworkKit'; 2588let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 2589``` 2590 2591## TCPSocketServer<sup>10+</sup> 2592 2593Defines a TCP socket server connection. Before calling TCPSocketServer APIs, you need to call [socket.constructTCPSocketServerInstance](#socketconstructtcpsocketserverinstance10) to create a **TCPSocketServer** object. 2594 2595### listen<sup>10+</sup> 2596 2597listen(address: NetAddress, callback: AsyncCallback\<void\>): void 2598 2599Binds the IP address and port number. The port number can be specified or randomly allocated by the system. The server listens to and accepts TCP socket connections established over the socket. Multiple threads are used to process client data concurrently. This API uses an asynchronous callback to return the result. 2600 2601> **NOTE**<br> 2602> The server uses this API to perform the **bind**, **listen**, and **accept** operations. If the **bind** operation fails, the system randomly allocates a port number. 2603 2604**Required permissions**: ohos.permission.INTERNET 2605 2606**System capability**: SystemCapability.Communication.NetStack 2607 2608**Parameters** 2609 2610| Name | Type | Mandatory| Description | 2611| -------- | ------------------------- | ---- | --------------------------------------------- | 2612| address | [NetAddress](#netaddress) | Yes | Destination address.| 2613| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error message is returned. | 2614 2615**Error codes** 2616 2617| ID| Error Message | 2618| -------- | ------------------------------------------- | 2619| 401 | Parameter error. | 2620| 201 | Permission denied. | 2621| 2300002 | System internal error. | 2622| 2303109 | Bad file number. | 2623| 2303111 | Resource temporarily unavailable. Try again.| 2624| 2303198 | Address already in use. | 2625| 2303199 | Cannot assign requested address. | 2626 2627**Example** 2628 2629```ts 2630import { socket } from '@kit.NetworkKit'; 2631import { BusinessError } from '@kit.BasicServicesKit'; 2632 2633let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 2634let listenAddr: socket.NetAddress = { 2635 address: '192.168.xx.xxx', 2636 port: 8080, 2637 family: 1 2638} 2639tcpServer.listen(listenAddr, (err: BusinessError) => { 2640 if (err) { 2641 console.log("listen fail"); 2642 return; 2643 } 2644 console.log("listen success"); 2645}) 2646``` 2647 2648### listen<sup>10+</sup> 2649 2650listen(address: NetAddress): Promise\<void\> 2651 2652Binds the IP address and port number. The port number can be specified or randomly allocated by the system. The server listens to and accepts TCP socket connections established over the socket. Multiple threads are used to process client data concurrently. This API uses a promise to return the result. 2653 2654> **NOTE**<br> 2655> The server uses this API to perform the **bind**, **listen**, and **accept** operations. If the **bind** operation fails, the system randomly allocates a port number. 2656 2657**Required permissions**: ohos.permission.INTERNET 2658 2659**System capability**: SystemCapability.Communication.NetStack 2660 2661**Parameters** 2662 2663| Name | Type | Mandatory| Description | 2664| ------- | ------------------------- | ---- | --------------------------------------------- | 2665| address | [NetAddress](#netaddress) | Yes | Destination address.| 2666 2667**Return value** 2668 2669| Type | Description | 2670| -------------- | ----------------------------------------------------------- | 2671| 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.| 2672 2673**Error codes** 2674 2675| ID| Error Message | 2676| -------- | ------------------------------------------- | 2677| 401 | Parameter error. | 2678| 201 | Permission denied. | 2679| 2300002 | System internal error. | 2680| 2303109 | Bad file number. | 2681| 2303111 | Resource temporarily unavailable. Try again.| 2682| 2303198 | Address already in use. | 2683| 2303199 | Cannot assign requested address. | 2684 2685**Example** 2686 2687```ts 2688import { socket } from '@kit.NetworkKit'; 2689import { BusinessError } from '@kit.BasicServicesKit'; 2690 2691let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 2692let listenAddr: socket.NetAddress = { 2693 address: '192.168.xx.xxx', 2694 port: 8080, 2695 family: 1 2696} 2697tcpServer.listen(listenAddr).then(() => { 2698 console.log('listen success'); 2699}).catch((err: BusinessError) => { 2700 console.log('listen fail'); 2701}); 2702``` 2703 2704### getState<sup>10+</sup> 2705 2706getState(callback: AsyncCallback\<SocketStateBase\>): void 2707 2708Obtains the status of a TCP socket server connection. This API uses an asynchronous callback to return the result. 2709 2710> **NOTE** 2711> This API can be called only after **listen** is successfully called. 2712 2713**Required permissions**: ohos.permission.INTERNET 2714 2715**System capability**: SystemCapability.Communication.NetStack 2716 2717**Parameters** 2718 2719| Name | Type | Mandatory| Description | 2720| -------- | -------------------------------------------------- | ---- | ---------- | 2721| callback | AsyncCallback\<[SocketStateBase](#socketstatebase)\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| 2722 2723**Error codes** 2724 2725| ID| Error Message | 2726| -------- | ------------------------------- | 2727| 401 | Parameter error. | 2728| 201 | Permission denied. | 2729| 2300002 | System internal error. | 2730| 2303188 | Socket operation on non-socket. | 2731 2732**Example** 2733 2734```ts 2735import { socket } from '@kit.NetworkKit'; 2736import { BusinessError } from '@kit.BasicServicesKit'; 2737 2738let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 2739let listenAddr: socket.NetAddress = { 2740 address: '192.168.xx.xxx', 2741 port: 8080, 2742 family: 1 2743} 2744tcpServer.listen(listenAddr, (err: BusinessError) => { 2745 if (err) { 2746 console.log("listen fail"); 2747 return; 2748 } 2749 console.log("listen success"); 2750}) 2751tcpServer.getState((err: BusinessError, data: socket.SocketStateBase) => { 2752 if (err) { 2753 console.log('getState fail'); 2754 return; 2755 } 2756 console.log('getState success:' + JSON.stringify(data)); 2757}) 2758``` 2759 2760### getState<sup>10+</sup> 2761 2762getState(): Promise\<SocketStateBase\> 2763 2764Obtains the status of a TCP socket server connection. This API uses a promise to return the result. 2765 2766> **NOTE** 2767> This API can be called only after **listen** is successfully called. 2768 2769**Required permissions**: ohos.permission.INTERNET 2770 2771**System capability**: SystemCapability.Communication.NetStack 2772 2773**Return value** 2774 2775| Type | Description | 2776| ------------------------------------------- | ----------------------------------------- | 2777| Promise\<[SocketStateBase](#socketstatebase)\> | Promise used to return the result.| 2778 2779**Error codes** 2780 2781| ID| Error Message | 2782| -------- | ------------------------------- | 2783| 201 | Permission denied. | 2784| 2300002 | System internal error. | 2785| 2303188 | Socket operation on non-socket. | 2786 2787**Example** 2788 2789```ts 2790import { socket } from '@kit.NetworkKit'; 2791import { BusinessError } from '@kit.BasicServicesKit'; 2792 2793let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 2794let listenAddr: socket.NetAddress = { 2795 address: '192.168.xx.xxx', 2796 port: 8080, 2797 family: 1 2798} 2799tcpServer.listen(listenAddr, (err: BusinessError) => { 2800 if (err) { 2801 console.log("listen fail"); 2802 return; 2803 } 2804 console.log("listen success"); 2805}) 2806tcpServer.getState().then((data: socket.SocketStateBase) => { 2807 console.log('getState success' + JSON.stringify(data)); 2808}).catch((err: BusinessError) => { 2809 console.log('getState fail'); 2810}); 2811``` 2812 2813### setExtraOptions<sup>10+</sup> 2814 2815setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\<void\>): void 2816 2817Sets other properties of a TCP socket server connection. This API uses an asynchronous callback to return the result. 2818 2819> **NOTE** 2820> This API can be called only after **listen** is successfully called. 2821 2822**Required permissions**: ohos.permission.INTERNET 2823 2824**System capability**: SystemCapability.Communication.NetStack 2825 2826**Parameters** 2827 2828| Name | Type | Mandatory| Description | 2829| -------- | ----------------------------------- | ---- | ------------------------------------------------------------ | 2830| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of a TCP socket server connection.| 2831| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error message is returned. | 2832 2833**Error codes** 2834 2835| ID| Error Message | 2836| -------- | ------------------------------- | 2837| 401 | Parameter error. | 2838| 201 | Permission denied. | 2839| 2300002 | System internal error. | 2840| 2303188 | Socket operation on non-socket. | 2841 2842**Example** 2843 2844```ts 2845import { socket } from '@kit.NetworkKit'; 2846import { BusinessError } from '@kit.BasicServicesKit'; 2847 2848let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 2849let listenAddr: socket.NetAddress = { 2850 address: '192.168.xx.xxx', 2851 port: 8080, 2852 family: 1 2853} 2854tcpServer.listen(listenAddr, (err: BusinessError) => { 2855 if (err) { 2856 console.log("listen fail"); 2857 return; 2858 } 2859 console.log("listen success"); 2860}) 2861 2862interface SocketLinger { 2863 on: boolean; 2864 linger: number; 2865} 2866 2867let tcpExtraOptions: socket.TCPExtraOptions = { 2868 keepAlive: true, 2869 OOBInline: true, 2870 TCPNoDelay: true, 2871 socketLinger: { on: true, linger: 10 } as SocketLinger, 2872 receiveBufferSize: 1000, 2873 sendBufferSize: 1000, 2874 reuseAddress: true, 2875 socketTimeout: 3000 2876} 2877tcpServer.setExtraOptions(tcpExtraOptions, (err: BusinessError) => { 2878 if (err) { 2879 console.log('setExtraOptions fail'); 2880 return; 2881 } 2882 console.log('setExtraOptions success'); 2883}); 2884``` 2885 2886### setExtraOptions<sup>10+</sup> 2887 2888setExtraOptions(options: TCPExtraOptions): Promise\<void\> 2889 2890Sets other properties of a TCP socket server connection. This API uses a promise to return the result. 2891 2892> **NOTE** 2893> This API can be called only after **listen** is successfully called. 2894 2895**Required permissions**: ohos.permission.INTERNET 2896 2897**System capability**: SystemCapability.Communication.NetStack 2898 2899**Parameters** 2900 2901| Name | Type | Mandatory| Description | 2902| ------- | ----------------------------------- | ---- | ------------------------------------------------------------ | 2903| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of a TCP socket server connection.| 2904 2905**Return value** 2906 2907| Type | Description | 2908| -------------- | --------------------------------------------------------- | 2909| 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.| 2910 2911**Error codes** 2912 2913| ID| Error Message | 2914| -------- | ------------------------------- | 2915| 401 | Parameter error. | 2916| 201 | Permission denied. | 2917| 2300002 | System internal error. | 2918| 2303188 | Socket operation on non-socket. | 2919 2920**Example** 2921 2922```ts 2923import { socket } from '@kit.NetworkKit'; 2924import { BusinessError } from '@kit.BasicServicesKit'; 2925 2926let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 2927let listenAddr: socket.NetAddress = { 2928 address: '192.168.xx.xxx', 2929 port: 8080, 2930 family: 1 2931} 2932 2933interface SocketLinger { 2934 on: boolean; 2935 linger: number; 2936} 2937 2938tcpServer.listen(listenAddr, (err: BusinessError) => { 2939 if (err) { 2940 console.log("listen fail"); 2941 return; 2942 } 2943 console.log("listen success"); 2944}) 2945 2946let tcpExtraOptions: socket.TCPExtraOptions = { 2947 keepAlive: true, 2948 OOBInline: true, 2949 TCPNoDelay: true, 2950 socketLinger: { on: true, linger: 10 } as SocketLinger, 2951 receiveBufferSize: 1000, 2952 sendBufferSize: 1000, 2953 reuseAddress: true, 2954 socketTimeout: 3000 2955} 2956tcpServer.setExtraOptions(tcpExtraOptions).then(() => { 2957 console.log('setExtraOptions success'); 2958}).catch((err: BusinessError) => { 2959 console.log('setExtraOptions fail'); 2960}); 2961``` 2962 2963### getLocalAddress<sup>12+</sup> 2964 2965getLocalAddress(): Promise\<NetAddress\> 2966 2967Obtains the local socket address of a **TCPSocketServer** connection. This API uses a promise to return the result. 2968 2969> **NOTE** 2970> This API can be called only after **listen** is successfully called. 2971 2972**System capability**: SystemCapability.Communication.NetStack 2973 2974**Return value** 2975 2976| Type | Description | 2977| -------------- | --------------------------------------------------- | 2978| Promise\<[NetAddress](#netaddress)\> | Promise used to return the result.| 2979 2980**Error codes** 2981 2982| ID| Error Message | 2983| -------- | ------------------------------------------- | 2984| 2300002 | System internal error. | 2985| 2301009 | Bad file descriptor. | 2986| 2303188 | Socket operation on non-socket. | 2987 2988**Example** 2989 2990```ts 2991import { socket } from '@kit.NetworkKit'; 2992import { BusinessError } from '@kit.BasicServicesKit'; 2993 2994let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 2995let listenAddr: socket.NetAddress = { 2996 address: '192.168.xx.xxx', 2997 port: 8080, 2998 family: 1 2999} 3000tcpServer.listen(listenAddr).then(() => { 3001 tcpServer.getLocalAddress().then((localAddress: socket.NetAddress) => { 3002 console.info("SUCCESS! Address:" + JSON.stringify(localAddress)); 3003 }).catch((err: BusinessError) => { 3004 console.error("FerrorAILED! Error:" + JSON.stringify(err)); 3005 }) 3006}).catch((err: BusinessError) => { 3007 console.error('listen fail'); 3008}); 3009``` 3010 3011### on('connect')<sup>10+</sup> 3012 3013on(type: 'connect', callback: Callback\<TCPSocketConnection\>): void 3014 3015Subscribes to **connect** events of a **TCPSocketServer** object. This API uses an asynchronous callback to return the result. 3016 3017> **NOTE** 3018> This API can be called only after **listen** is successfully called. 3019 3020**System capability**: SystemCapability.Communication.NetStack 3021 3022**Parameters** 3023 3024| Name | Type | Mandatory| Description | 3025| -------- | ------------------------------- | ---- | ------------------------------------- | 3026| type | string | Yes | Event type.<br/> **connect**: connection event.| 3027| callback | Callback\<[TCPSocketConnection](#tcpsocketconnection10)\> | Yes | Callback used to return the result. If the operation fails, an error message is returned. | 3028 3029**Error codes** 3030 3031| ID| Error Message | 3032| -------- | ---------------- | 3033| 401 | Parameter error. | 3034 3035**Example** 3036 3037```ts 3038import { socket } from '@kit.NetworkKit'; 3039 3040let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 3041 3042let listenAddr: socket.NetAddress = { 3043 address: '192.168.xx.xxx', 3044 port: 8080, 3045 family: 1 3046} 3047tcpServer.listen(listenAddr, (err: BusinessError) => { 3048 if (err) { 3049 console.log("listen fail"); 3050 return; 3051 } 3052 console.log("listen success"); 3053 tcpServer.on('connect', (data: socket.TCPSocketConnection) => { 3054 console.log(JSON.stringify(data)) 3055 }); 3056}) 3057``` 3058 3059### off('connect')<sup>10+</sup> 3060 3061off(type: 'connect', callback?: Callback\<TCPSocketConnection\>): void 3062 3063Unsubscribes from **connect** events of a **TCPSocketServer** object. This API uses an asynchronous callback to return the result. 3064 3065**System capability**: SystemCapability.Communication.NetStack 3066 3067**Parameters** 3068 3069| Name | Type | Mandatory| Description | 3070| -------- | ------------------------------- | ---- | ------------------------------------- | 3071| type | string | Yes | Event type.<br/> **connect**: connection event.| 3072| callback | Callback\<[TCPSocketConnection](#tcpsocketconnection10)\> | No | Callback used to return the result. If the operation fails, an error message is returned.| 3073 3074**Error codes** 3075 3076| ID| Error Message | 3077| -------- | ---------------- | 3078| 401 | Parameter error. | 3079 3080**Example** 3081 3082```ts 3083import { socket } from '@kit.NetworkKit'; 3084 3085let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 3086 3087let listenAddr: socket.NetAddress = { 3088 address: '192.168.xx.xxx', 3089 port: 8080, 3090 family: 1 3091} 3092tcpServer.listen(listenAddr, (err: BusinessError) => { 3093 if (err) { 3094 console.log("listen fail"); 3095 return; 3096 } 3097 console.log("listen success"); 3098 let callback = (data: socket.TCPSocketConnection) => { 3099 console.log('on connect message: ' + JSON.stringify(data)); 3100 } 3101 tcpServer.on('connect', callback); 3102 // You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 3103 tcpServer.off('connect', callback); 3104 tcpServer.off('connect'); 3105}) 3106``` 3107 3108### on('error')<sup>10+</sup> 3109 3110on(type: 'error', callback: ErrorCallback): void 3111 3112Subscribes to **error** events of a **TCPSocketServer** object. This API uses an asynchronous callback to return the result. 3113 3114> **NOTE** 3115> This API can be called only after **listen** is successfully called. 3116 3117**System capability**: SystemCapability.Communication.NetStack 3118 3119**Parameters** 3120 3121| Name | Type | Mandatory| Description | 3122| -------- | ------------- | ---- | ------------------------------------ | 3123| type | string | Yes | Event type.<br/> **error**: error event.| 3124| callback | ErrorCallback | Yes | Callback used to return the result. If the operation fails, an error message is returned.| 3125 3126**Error codes** 3127 3128| ID| Error Message | 3129| -------- | ---------------- | 3130| 401 | Parameter error. | 3131 3132**Example** 3133 3134```ts 3135import { socket } from '@kit.NetworkKit'; 3136import { BusinessError } from '@kit.BasicServicesKit'; 3137 3138let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 3139 3140let listenAddr: socket.NetAddress = { 3141 address: '192.168.xx.xxx', 3142 port: 8080, 3143 family: 1 3144} 3145tcpServer.listen(listenAddr, (err: BusinessError) => { 3146 if (err) { 3147 console.log("listen fail"); 3148 return; 3149 } 3150 console.log("listen success"); 3151 tcpServer.on('error', (err: BusinessError) => { 3152 console.log("on error, err:" + JSON.stringify(err)) 3153 }); 3154}) 3155``` 3156 3157### off('error')<sup>10+</sup> 3158 3159off(type: 'error', callback?: ErrorCallback): void 3160 3161Unsubscribes from **error** events of a **TCPSocketServer** object. This API uses an asynchronous callback to return the result. 3162 3163**System capability**: SystemCapability.Communication.NetStack 3164 3165**Parameters** 3166 3167| Name | Type | Mandatory| Description | 3168| -------- | ------------- | ---- | ------------------------------------ | 3169| type | string | Yes | Event type.<br/> **error**: error event.| 3170| callback | ErrorCallback | No | Callback used to return the result. If the operation fails, an error message is returned. | 3171 3172**Error codes** 3173 3174| ID| Error Message | 3175| -------- | ---------------- | 3176| 401 | Parameter error. | 3177 3178**Example** 3179 3180```ts 3181import { socket } from '@kit.NetworkKit'; 3182import { BusinessError } from '@kit.BasicServicesKit'; 3183 3184let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 3185 3186let listenAddr: socket.NetAddress = { 3187 address: '192.168.xx.xxx', 3188 port: 8080, 3189 family: 1 3190} 3191tcpServer.listen(listenAddr, (err: BusinessError) => { 3192 if (err) { 3193 console.log("listen fail"); 3194 return; 3195 } 3196 console.log("listen success"); 3197 let callback = (err: BusinessError) => { 3198 console.log("on error, err:" + JSON.stringify(err)); 3199 } 3200 tcpServer.on('error', callback); 3201 // You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 3202 tcpServer.off('error', callback); 3203 tcpServer.off('error'); 3204}) 3205``` 3206 3207## TCPSocketConnection<sup>10+</sup> 3208 3209Defines a **TCPSocketConnection** object, that is, the connection between the TCPSocket client and the server. Before calling TCPSocketConnection APIs, you need to obtain a **TCPSocketConnection** object. 3210 3211> **NOTE** 3212> The TCPSocket client can call related APIs through the **TCPSocketConnection** object only after a connection is successfully established between the TCPSocket client and the server. 3213 3214**System capability**: SystemCapability.Communication.NetStack 3215 3216### Attributes 3217 3218| Name | Type | Mandatory| Description | 3219| -------- | ------ | ---- | ----------------------------------------- | 3220| clientId | number | Yes | ID of the connection between the client and TCPSocketServer.| 3221 3222### send<sup>10+</sup> 3223 3224send(options: TCPSendOptions, callback: AsyncCallback\<void\>): void 3225 3226Sends data over a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result. 3227 3228> **NOTE** 3229> This API can be called only after a connection with the client is set up. 3230 3231**Required permissions**: ohos.permission.INTERNET 3232 3233**System capability**: SystemCapability.Communication.NetStack 3234 3235**Parameters** 3236 3237| Name | Type | Mandatory| Description | 3238| -------- | --------------------------------- | ---- | ------------------------------------------------------------ | 3239| options | [TCPSendOptions](#tcpsendoptions) | Yes | Defines the parameters for sending data over a TCP socket connection.| 3240| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error message is returned. | 3241 3242**Error codes** 3243 3244| ID| Error Message | 3245| -------- | ---------------------- | 3246| 401 | Parameter error. | 3247| 201 | Permission denied. | 3248| 2300002 | System internal error. | 3249 3250**Example** 3251 3252```ts 3253import { socket } from '@kit.NetworkKit'; 3254 3255let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 3256 3257tcpServer.on('connect', (client: socket.TCPSocketConnection) => { 3258 let tcpSendOption: socket.TCPSendOptions = { 3259 data: 'Hello, client!' 3260 } 3261 client.send(tcpSendOption, () => { 3262 console.log('send success'); 3263 }); 3264}); 3265``` 3266 3267### send<sup>10+</sup> 3268 3269send(options: TCPSendOptions): Promise\<void\> 3270 3271Sends data over a **TCPSocketConnection** object. This API uses a promise to return the result. 3272 3273> **NOTE** 3274> This API can be called only after a connection with the client is set up. 3275 3276**Required permissions**: ohos.permission.INTERNET 3277 3278**System capability**: SystemCapability.Communication.NetStack 3279 3280**Parameters** 3281 3282| Name | Type | Mandatory| Description | 3283| ------- | --------------------------------- | ---- | ------------------------------------------------------------ | 3284| options | [TCPSendOptions](#tcpsendoptions) | Yes | Defines the parameters for sending data over a TCP socket connection.| 3285 3286**Return value** 3287 3288| Type | Description | 3289| -------------- | ----------------------------------------------------------- | 3290| 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.| 3291 3292**Error codes** 3293 3294| ID| Error Message | 3295| -------- | ---------------------- | 3296| 401 | Parameter error. | 3297| 201 | Permission denied. | 3298| 2300002 | System internal error. | 3299 3300**Example** 3301 3302```ts 3303import { socket } from '@kit.NetworkKit'; 3304import { BusinessError } from '@kit.BasicServicesKit'; 3305 3306let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 3307 3308tcpServer.on('connect', (client: socket.TCPSocketConnection) => { 3309 let tcpSendOption: socket.TCPSendOptions = { 3310 data: 'Hello, client!' 3311 } 3312 client.send(tcpSendOption).then(() => { 3313 console.log('send success'); 3314 }).catch((err: BusinessError) => { 3315 console.log('send fail'); 3316 }); 3317}); 3318``` 3319 3320### close<sup>10+</sup> 3321 3322close(callback: AsyncCallback\<void\>): void 3323 3324Closes a TCP socket connection. This API uses an asynchronous callback to return the result. 3325 3326**Required permissions**: ohos.permission.INTERNET 3327 3328**System capability**: SystemCapability.Communication.NetStack 3329 3330**Parameters** 3331 3332| Name | Type | Mandatory| Description | 3333| -------- | --------------------- | ---- | ---------- | 3334| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| 3335 3336**Error codes** 3337 3338| ID| Error Message | 3339| -------- | ---------------------- | 3340| 401 | Parameter error. | 3341| 201 | Permission denied. | 3342| 2300002 | System internal error. | 3343 3344**Example** 3345 3346```ts 3347import { socket } from '@kit.NetworkKit'; 3348import { BusinessError } from '@kit.BasicServicesKit'; 3349 3350let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 3351 3352tcpServer.on('connect', (client: socket.TCPSocketConnection) => { 3353 client.close((err: BusinessError) => { 3354 if (err) { 3355 console.log('close fail'); 3356 return; 3357 } 3358 console.log('close success'); 3359 }); 3360}); 3361``` 3362 3363### close<sup>10+</sup> 3364 3365close(): Promise\<void\> 3366 3367Closes a TCP socket connection. This API uses a promise to return the result. 3368 3369**Required permissions**: ohos.permission.INTERNET 3370 3371**System capability**: SystemCapability.Communication.NetStack 3372 3373**Return value** 3374 3375| Type | Description | 3376| -------------- | ------------------------------------------- | 3377| 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.| 3378 3379**Error codes** 3380 3381| ID| Error Message | 3382| -------- | ---------------------- | 3383| 201 | Permission denied. | 3384| 2300002 | System internal error. | 3385 3386**Example** 3387 3388```ts 3389import { socket } from '@kit.NetworkKit'; 3390 3391let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 3392tcpServer.on('connect', (client: socket.TCPSocketConnection) => { 3393 client.close().then(() => { 3394 console.log('close success'); 3395 }).catch((err: BusinessError) => { 3396 console.log('close fail'); 3397 }); 3398}); 3399``` 3400 3401### getRemoteAddress<sup>10+</sup> 3402 3403getRemoteAddress(callback: AsyncCallback\<NetAddress\>): void 3404 3405Obtains the remote address of a socket connection. This API uses an asynchronous callback to return the result. 3406 3407> **NOTE** 3408> This API can be called only after a connection with the client is set up. 3409 3410**Required permissions**: ohos.permission.INTERNET 3411 3412**System capability**: SystemCapability.Communication.NetStack 3413 3414**Parameters** 3415 3416| Name | Type | Mandatory| Description | 3417| -------- | ---------------------------------------- | ---- | ---------- | 3418| callback | AsyncCallback\<[NetAddress](#netaddress)\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| 3419 3420**Error codes** 3421 3422| ID| Error Message | 3423| -------- | ------------------------------- | 3424| 401 | Parameter error. | 3425| 201 | Permission denied. | 3426| 2300002 | System internal error. | 3427| 2303188 | Socket operation on non-socket. | 3428 3429**Example** 3430 3431```ts 3432import { socket } from '@kit.NetworkKit'; 3433import { BusinessError } from '@kit.BasicServicesKit'; 3434 3435let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 3436tcpServer.on('connect', (client: socket.TCPSocketConnection) => { 3437 client.getRemoteAddress((err: BusinessError, data: socket.NetAddress) => { 3438 if (err) { 3439 console.log('getRemoteAddress fail'); 3440 return; 3441 } 3442 console.log('getRemoteAddress success:' + JSON.stringify(data)); 3443 }); 3444}); 3445``` 3446 3447### getRemoteAddress<sup>10+</sup> 3448 3449getRemoteAddress(): Promise\<NetAddress\> 3450 3451Obtains the remote address of a socket connection. This API uses a promise to return the result. 3452 3453> **NOTE** 3454> This API can be called only after a connection with the client is set up. 3455 3456**Required permissions**: ohos.permission.INTERNET 3457 3458**System capability**: SystemCapability.Communication.NetStack 3459 3460**Return value** 3461 3462| Type | Description | 3463| --------------------------------- | ------------------------------------------ | 3464| Promise\<[NetAddress](#netaddress)\> | Promise used to return the result.| 3465 3466**Error codes** 3467 3468| ID| Error Message | 3469| -------- | ------------------------------- | 3470| 201 | Permission denied. | 3471| 2300002 | System internal error. | 3472| 2303188 | Socket operation on non-socket. | 3473 3474**Example** 3475 3476```ts 3477import { socket } from '@kit.NetworkKit'; 3478import { BusinessError } from '@kit.BasicServicesKit'; 3479 3480let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 3481tcpServer.on('connect', (client: socket.TCPSocketConnection) => { 3482 client.getRemoteAddress().then(() => { 3483 console.log('getRemoteAddress success'); 3484 }).catch((err: BusinessError) => { 3485 console.log('getRemoteAddress fail'); 3486 }); 3487}); 3488``` 3489 3490### getLocalAddress<sup>12+</sup> 3491 3492getLocalAddress(): Promise\<NetAddress\> 3493 3494Obtains the local socket address of a **TCPSocketConnection** connection. This API uses a promise to return the result. 3495 3496**System capability**: SystemCapability.Communication.NetStack 3497 3498**Return value** 3499 3500| Type | Description | 3501| -------------- | --------------------------------------------------- | 3502| Promise\<[NetAddress](#netaddress)\> | Promise used to return the result.| 3503 3504**Error codes** 3505 3506| ID| Error Message | 3507| -------- | ------------------------------------------- | 3508| 2300002 | System internal error. | 3509| 2301009 | Bad file descriptor. | 3510| 2303188 | Socket operation on non-socket. | 3511 3512**Example** 3513 3514```ts 3515import { socket } from '@kit.NetworkKit'; 3516import { BusinessError } from '@kit.BasicServicesKit'; 3517 3518let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 3519let listenAddr: socket.NetAddress = { 3520 address: "192.168.xx.xx", 3521 port: 8080, 3522 family: 1 3523} 3524tcpServer.listen(listenAddr, (err: BusinessError) => { 3525 let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 3526 let netAddress: socket.NetAddress = { 3527 address: "192.168.xx.xx", 3528 port: 8080 3529 } 3530 let options: socket.TCPConnectOptions = { 3531 address: netAddress, 3532 timeout: 6000 3533 } 3534 tcp.connect(options, (err: BusinessError) => { 3535 if (err) { 3536 console.error('connect fail'); 3537 return; 3538 } 3539 console.info('connect success!'); 3540 }) 3541 tcpServer.on('connect', (client: socket.TCPSocketConnection) => { 3542 client.getLocalAddress().then((localAddress: socket.NetAddress) => { 3543 console.info("Family IP Port: " + JSON.stringify(localAddress)); 3544 }).catch((err: BusinessError) => { 3545 console.error('Error:' + JSON.stringify(err)); 3546 }); 3547 }) 3548}) 3549``` 3550 3551### on('message')<sup>10+</sup> 3552 3553on(type: 'message', callback: Callback<SocketMessageInfo\>): void 3554 3555Subscribes to **message** events of a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result. 3556 3557**System capability**: SystemCapability.Communication.NetStack 3558 3559**Parameters** 3560 3561| Name | Type | Mandatory| Description | 3562| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 3563| type | string | Yes | Event type.<br/> **message**: message receiving event.| 3564| callback | Callback\<[SocketMessageInfo](#socketmessageinfo11)\> | Yes | Callback used to return the result. If the operation fails, an error message is returned. | 3565 3566**Error codes** 3567 3568| ID| Error Message | 3569| -------- | ---------------- | 3570| 401 | Parameter error. | 3571 3572**Example** 3573 3574```ts 3575import { socket } from '@kit.NetworkKit'; 3576import { BusinessError } from '@kit.BasicServicesKit'; 3577 3578let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 3579 3580tcpServer.on('connect', (client: socket.TCPSocketConnection) => { 3581 client.on('message', (value: socket.SocketMessageInfo) => { 3582 let messageView = ''; 3583 for (let i: number = 0; i < value.message.byteLength; i++) { 3584 let uint8Array = new Uint8Array(value.message) 3585 let messages = uint8Array[i] 3586 let message = String.fromCharCode(messages); 3587 messageView += message; 3588 } 3589 console.log('on message message: ' + JSON.stringify(messageView)); 3590 console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo)); 3591 }); 3592}); 3593``` 3594 3595### off('message')<sup>10+</sup> 3596 3597off(type: 'message', callback?: Callback<SocketMessageInfo\>): void 3598 3599Unsubscribes from **message** events of a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result. 3600 3601**System capability**: SystemCapability.Communication.NetStack 3602 3603**Parameters** 3604 3605| Name | Type | Mandatory| Description | 3606| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 3607| type | string | Yes | Event type.<br/> **message**: message receiving event.| 3608| callback | Callback\<[SocketMessageInfo](#socketmessageinfo11)\> | No | Callback used to return the result. If the operation fails, an error message is returned. | 3609 3610**Error codes** 3611 3612| ID| Error Message | 3613| -------- | ---------------- | 3614| 401 | Parameter error. | 3615 3616**Example** 3617 3618```ts 3619import { socket } from '@kit.NetworkKit'; 3620import { BusinessError } from '@kit.BasicServicesKit'; 3621 3622let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 3623let callback = (value: socket.SocketMessageInfo) => { 3624 let messageView = ''; 3625 for (let i: number = 0; i < value.message.byteLength; i++) { 3626 let uint8Array = new Uint8Array(value.message) 3627 let messages = uint8Array[i] 3628 let message = String.fromCharCode(messages); 3629 messageView += message; 3630 } 3631 console.log('on message message: ' + JSON.stringify(messageView)); 3632 console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo)); 3633} 3634tcpServer.on('connect', (client: socket.TCPSocketConnection) => { 3635 client.on('message', callback); 3636 // You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 3637 client.off('message', callback); 3638 client.off('message'); 3639}); 3640``` 3641 3642### on('close')<sup>10+</sup> 3643 3644on(type: 'close', callback: Callback\<void\>): void 3645 3646Subscribes to **close** events of a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result. 3647 3648**System capability**: SystemCapability.Communication.NetStack 3649 3650**Parameters** 3651 3652| Name | Type | Mandatory| Description | 3653| -------- | ---------------- | ---- | ----------------------------------- | 3654| type | string | Yes | Event type.<br/> **close**: close event.| 3655| callback | Callback\<void\> | Yes | Callback used to return the result. If the operation fails, an error message is returned. | 3656 3657**Error codes** 3658 3659| ID| Error Message | 3660| -------- | ---------------- | 3661| 401 | Parameter error. | 3662 3663**Example** 3664 3665```ts 3666import { socket } from '@kit.NetworkKit'; 3667import { BusinessError } from '@kit.BasicServicesKit'; 3668 3669let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 3670tcpServer.on('connect', (client: socket.TCPSocketConnection) => { 3671 client.on('close', () => { 3672 console.log("on close success") 3673 }); 3674}); 3675``` 3676 3677### off('close')<sup>10+</sup> 3678 3679off(type: 'close', callback?: Callback\<void\>): void 3680 3681Unsubscribes from **close** events of a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result. 3682 3683**System capability**: SystemCapability.Communication.NetStack 3684 3685**Parameters** 3686 3687| Name | Type | Mandatory| Description | 3688| -------- | ---------------- | ---- | ----------------------------------- | 3689| type | string | Yes | Event type.<br/> **close**: close event.| 3690| callback | Callback\<void\> | No | Callback used to return the result. If the operation fails, an error message is returned. | 3691 3692**Error codes** 3693 3694| ID| Error Message | 3695| -------- | ---------------- | 3696| 401 | Parameter error. | 3697 3698**Example** 3699 3700```ts 3701import { socket } from '@kit.NetworkKit'; 3702 3703let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 3704let callback = () => { 3705 console.log("on close success"); 3706} 3707tcpServer.on('connect', (client: socket.TCPSocketConnection) => { 3708 client.on('close', callback); 3709 // You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 3710 client.off('close', callback); 3711 client.off('close'); 3712}); 3713``` 3714 3715### on('error')<sup>10+</sup> 3716 3717on(type: 'error', callback: ErrorCallback): void 3718 3719Subscribes to **error** events of a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result. 3720 3721**System capability**: SystemCapability.Communication.NetStack 3722 3723**Parameters** 3724 3725| Name | Type | Mandatory| Description | 3726| -------- | ------------- | ---- | ------------------------------------ | 3727| type | string | Yes | Event type.<br/> **error**: error event.| 3728| callback | ErrorCallback | Yes | Callback used to return the result. If the operation fails, an error message is returned. | 3729 3730**Error codes** 3731 3732| ID| Error Message | 3733| -------- | ---------------- | 3734| 401 | Parameter error. | 3735 3736**Example** 3737 3738```ts 3739import { socket } from '@kit.NetworkKit'; 3740import { BusinessError } from '@kit.BasicServicesKit'; 3741 3742let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 3743tcpServer.on('connect', (client: socket.TCPSocketConnection) => { 3744 client.on('error', (err: BusinessError) => { 3745 console.log("on error, err:" + JSON.stringify(err)) 3746 }); 3747}); 3748``` 3749 3750### off('error')<sup>10+</sup> 3751 3752off(type: 'error', callback?: ErrorCallback): void 3753 3754Unsubscribes from **error** events of a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result. 3755 3756**System capability**: SystemCapability.Communication.NetStack 3757 3758**Parameters** 3759 3760| Name | Type | Mandatory| Description | 3761| -------- | ------------- | ---- | ------------------------------------ | 3762| type | string | Yes | Event type.<br/> **error**: error event.| 3763| callback | ErrorCallback | No | Callback used to return the result. If the operation fails, an error message is returned. | 3764 3765**Error codes** 3766 3767| ID| Error Message | 3768| -------- | ---------------- | 3769| 401 | Parameter error. | 3770 3771**Example** 3772 3773```ts 3774import { socket } from '@kit.NetworkKit'; 3775import { BusinessError } from '@kit.BasicServicesKit'; 3776 3777let callback = (err: BusinessError) => { 3778 console.log("on error, err:" + JSON.stringify(err)); 3779} 3780let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 3781tcpServer.on('connect', (client: socket.TCPSocketConnection) => { 3782 client.on('error', callback); 3783 // You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 3784 client.off('error', callback); 3785 client.off('error'); 3786}); 3787``` 3788 3789## Description of TCP Error Codes 3790 3791The TCP error code mapping is in the format of 2301000 + Linux kernel error code. 3792 3793For details about error codes, see [Socket Error Codes](errorcode-net-socket.md). 3794 3795## socket.constructLocalSocketInstance<sup>11+</sup> 3796 3797constructLocalSocketInstance(): LocalSocket 3798 3799Creates a **LocalSocket** object. 3800 3801**System capability**: SystemCapability.Communication.NetStack 3802 3803**Return value** 3804 3805| Type | Description | 3806| :--------------------------------- | :---------------------- | 3807| [LocalSocket](#localsocket11) | **LocalSocket** object.| 3808 3809**Example** 3810 3811```ts 3812import { socket } from '@kit.NetworkKit'; 3813let client: socket.LocalSocket = socket.constructLocalSocketInstance(); 3814``` 3815 3816## LocalSocket<sup>11+</sup> 3817 3818Defines a **LocalSocket** object. Before calling LocalSocket APIs, you need to call [socket.constructLocalSocketInstance](#socketconstructlocalsocketinstance11) to create a **LocalSocket** object. 3819 3820### bind<sup>11+</sup> 3821 3822bind(address: LocalAddress): Promise\<void\>; 3823 3824Binds the address of a local socket file. This API uses a promise to return the result. 3825 3826> **NOTE** 3827> This API explicitly binds the client to a local socket file based on the specified address. 3828> It is not mandatory in local socket communication. 3829 3830**System capability**: SystemCapability.Communication.NetStack 3831 3832**Parameters** 3833 3834| Name | Type | Mandatory| Description | 3835| -------- | ---------------------------------- | ---- | ------------------------------------------------------ | 3836| address | [LocalAddress](#localaddress11) | Yes | Destination address. For details, see [LocalAddress](#localaddress11).| 3837 3838**Error codes** 3839 3840| ID| Error Message | 3841| ------- | -------------------------- | 3842| 401 | Parameter error. | 3843| 2301013 | Insufficient permissions. | 3844| 2301022 | Invalid argument. | 3845| 2301098 | Address already in use. | 3846 3847**Example** 3848 3849```ts 3850import { socket } from '@kit.NetworkKit'; 3851 3852let client: socket.LocalSocket = socket.constructLocalSocketInstance() 3853let sandboxPath: string = getContext().filesDir + '/testSocket' 3854let address : socket.LocalAddress = { 3855 address: sandboxPath 3856} 3857client.bind(address).then(() => { 3858 console.log('bind success') 3859}).catch((err: Object) => { 3860 console.error('failed to bind: ' + JSON.stringify(err)) 3861}) 3862``` 3863 3864### connect<sup>11+</sup> 3865 3866connect(options: LocalConnectOptions): Promise\<void\> 3867 3868Connects to the specified socket file. This API uses a promise to return the result. 3869 3870> **NOTE** 3871> This API allows you to connect to the TCP server without first executing **localsocket.bind**. 3872 3873**System capability**: SystemCapability.Communication.NetStack 3874 3875**Parameters** 3876 3877| Name | Type | Mandatory| Description | 3878| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | 3879| options | [LocalConnectOptions](#localconnectoptions11) | Yes | Local socket connection parameters. For details, see [LocalConnectOptions](#localconnectoptions11).| 3880 3881**Return value** 3882 3883| Type | Description | 3884| :-------------- | :---------------------------------------- | 3885| Promise\<void\> | Promise used to return the result.| 3886 3887**Error codes** 3888 3889| ID| Error Message | 3890| ------- | ----------------------- | 3891| 401 | Parameter error. | 3892| 2301013 | Insufficient permissions. | 3893| 2301022 | Invalid argument. | 3894| 2301111 | Connection refused. | 3895| 2301099 | Cannot assign requested address. | 3896 3897**Example** 3898 3899```ts 3900import { socket } from '@kit.NetworkKit'; 3901 3902let client: socket.LocalSocket = socket.constructLocalSocketInstance(); 3903let sandboxPath: string = getContext().filesDir + '/testSocket' 3904let localAddress : socket.LocalAddress = { 3905 address: sandboxPath 3906} 3907let connectOpt: socket.LocalConnectOptions = { 3908 address: localAddress, 3909 timeout: 6000 3910} 3911client.connect(connectOpt).then(() => { 3912 console.log('connect success') 3913}).catch((err: Object) => { 3914 console.error('connect fail: ' + JSON.stringify(err)); 3915}); 3916``` 3917 3918### send<sup>11+</sup> 3919 3920send(options: LocalSendOptions): Promise\<void\> 3921 3922Sends data over a local socket connection. This API uses a promise to return the result. 3923 3924> **NOTE** 3925> This API can be called only after **connect** is successfully called. 3926 3927**System capability**: SystemCapability.Communication.NetStack 3928 3929**Parameters** 3930 3931| Name | Type | Mandatory| Description | 3932| ------- | --------------------------------------- | ---- | ------------------------------------------------------------ | 3933| options | [LocalSendOptions](#localsendoptions11) | Yes | Parameters for sending data over a local socket connection. For details, see [LocalSendOptions](#localsendoptions11).| 3934 3935**Return value** 3936 3937| Type | Description | 3938| :-------------- | :------------------------------------------ | 3939| Promise\<void\> | Promise used to return the result.| 3940 3941**Error codes** 3942 3943| ID| Error Message | 3944| ------- | ----------------------- | 3945| 401 | Parameter error. | 3946| 2301011 | Operation would block. | 3947 3948**Example** 3949 3950```ts 3951import { socket } from '@kit.NetworkKit'; 3952 3953let client: socket.LocalSocket = socket.constructLocalSocketInstance() 3954let sandboxPath: string = getContext().filesDir + '/testSocket' 3955let localAddress : socket.LocalAddress = { 3956 address: sandboxPath 3957} 3958let connectOpt: socket.LocalConnectOptions = { 3959 address: localAddress, 3960 timeout: 6000 3961} 3962client.connect(connectOpt).then(() => { 3963 console.log('connect success') 3964}).catch((err: Object) => { 3965 console.error('connect failed: ' + JSON.stringify(err)) 3966}) 3967let sendOpt: socket.LocalSendOptions = { 3968 data: 'Hello world!' 3969} 3970client.send(sendOpt).then(() => { 3971 console.log('send success') 3972}).catch((err: Object) => { 3973 console.error('send fail: ' + JSON.stringify(err)) 3974}) 3975``` 3976 3977### close<sup>11+</sup> 3978 3979close(): Promise\<void\> 3980 3981Closes a local socket connection. This API uses a promise to return the result. 3982 3983**System capability**: SystemCapability.Communication.NetStack 3984 3985**Return value** 3986 3987| Type | Description | 3988| :-------------- | :----------------------------------------- | 3989| Promise\<void\> | Promise used to return the result.| 3990 3991**Error codes** 3992 3993| ID| Error Message | 3994| ------- | ----------------------- | 3995| 2301009 | Bad file descriptor. | 3996 3997**Example** 3998 3999```ts 4000import { socket } from '@kit.NetworkKit'; 4001 4002let client: socket.LocalSocket = socket.constructLocalSocketInstance(); 4003 4004client.close().then(() => { 4005 console.log('close success'); 4006}).catch((err: Object) => { 4007 console.error('close fail: ' + JSON.stringify(err)); 4008}); 4009``` 4010 4011### getState<sup>11+</sup> 4012 4013getState(): Promise\<SocketStateBase\> 4014 4015Obtains the local socket connection status. This API uses a promise to return the result. 4016 4017> **NOTE** 4018> This API can be called only after **bind** or **connect** is successfully called. 4019 4020**System capability**: SystemCapability.Communication.NetStack 4021 4022**Return value** 4023 4024| Type | Description | 4025| :------------------------------------------- | :--------------------------------------- | 4026| Promise\<[SocketStateBase](#socketstatebase)\> | Promise used to return the result.| 4027 4028**Example** 4029 4030```ts 4031import { socket } from '@kit.NetworkKit'; 4032 4033let client: socket.LocalSocket = socket.constructLocalSocketInstance(); 4034let sandboxPath: string = getContext().filesDir + '/testSocket' 4035let localAddress : socket.LocalAddress = { 4036 address: sandboxPath 4037} 4038let connectOpt: socket.LocalConnectOptions = { 4039 address: localAddress, 4040 timeout: 6000 4041} 4042client.connect(connectOpt).then(() => { 4043 console.log('connect success'); 4044 client.getState().then(() => { 4045 console.log('getState success'); 4046 }).catch((err: Object) => { 4047 console.error('getState fail: ' + JSON.stringify(err)) 4048 }); 4049}).catch((err: Object) => { 4050 console.error('connect fail: ' + JSON.stringify(err)); 4051}); 4052``` 4053 4054### getSocketFd<sup>11+</sup> 4055 4056getSocketFd(): Promise\<number\> 4057 4058Obtains the file descriptor of the **LocalSocket** object. This API uses a promise to return the result. 4059 4060> **NOTE** 4061> This API can be called only after **bind** or **connect** is successfully called. 4062> The file descriptor is allocated by the system kernel to uniquely identify the local socket in use. 4063 4064**System capability**: SystemCapability.Communication.NetStack 4065 4066**Return value** 4067 4068| Type | Description | 4069| :---------------- | :-------------------------------- | 4070| Promise\<number\> | Promise used to return the result.| 4071 4072**Example** 4073 4074```ts 4075import { socket } from '@kit.NetworkKit'; 4076 4077let client: socket.LocalSocket = socket.constructLocalSocketInstance(); 4078let sandboxPath: string = getContext().filesDir + '/testSocket' 4079let localAddress : socket.LocalAddress = { 4080 address: sandboxPath 4081} 4082let connectOpt: socket.LocalConnectOptions = { 4083 address: localAddress, 4084 timeout: 6000 4085} 4086client.connect(connectOpt).then(() => { 4087 console.log('connect ok') 4088}).catch((err: Object) => { 4089 console.error('connect fail: ' + JSON.stringify(err)) 4090}) 4091client.getSocketFd().then((data: number) => { 4092 console.info("fd: " + data); 4093}).catch((err: Object) => { 4094 console.error("getSocketFd faile: " + JSON.stringify(err)); 4095}) 4096``` 4097 4098### setExtraOptions<sup>11+</sup> 4099 4100setExtraOptions(options: ExtraOptionsBase): Promise\<void\> 4101 4102Sets other properties of the local socket connection. This API uses a promise to return the result. 4103 4104> **NOTE** 4105> This API can be called only after **bind** or **connect** is successfully called. 4106 4107**System capability**: SystemCapability.Communication.NetStack 4108 4109**Parameters** 4110 4111| Name | Type | Mandatory| Description | 4112| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | 4113| options | [ExtraOptionsBase](#extraoptionsbase7) | Yes | Other properties of the local socket connection. For details, see [ExtraOptionsBase](#extraoptionsbase7).| 4114 4115**Return value** 4116 4117| Type | Description | 4118| :-------------- | :-------------------------------------------- | 4119| Promise\<void\> | Promise used to return the result.| 4120 4121**Error codes** 4122 4123| ID| Error Message | 4124| ------- | ----------------------- | 4125| 401 | Parameter error. | 4126| 2301009 | Bad file descriptor. | 4127 4128**Example** 4129 4130```ts 4131import { socket } from '@kit.NetworkKit'; 4132 4133let client: socket.LocalSocket = socket.constructLocalSocketInstance(); 4134let sandboxPath: string = getContext().filesDir + '/testSocket' 4135let localAddress : socket.LocalAddress = { 4136 address: sandboxPath 4137} 4138let connectOpt: socket.LocalConnectOptions = { 4139 address: localAddress, 4140 timeout: 6000 4141} 4142client.connect(connectOpt).then(() => { 4143 console.log('connect success'); 4144 let options: socket.ExtraOptionsBase = { 4145 receiveBufferSize: 8000, 4146 sendBufferSize: 8000, 4147 socketTimeout: 3000 4148 } 4149 client.setExtraOptions(options).then(() => { 4150 console.log('setExtraOptions success'); 4151 }).catch((err: Object) => { 4152 console.error('setExtraOptions fail: ' + JSON.stringify(err)); 4153 }); 4154}).catch((err: Object) => { 4155 console.error('connect fail: ' + JSON.stringify(err)); 4156}); 4157``` 4158 4159### getExtraOptions<sup>11+</sup> 4160 4161getExtraOptions(): Promise\<ExtraOptionsBase\>; 4162 4163Obtains other properties of the local socket connection. This API uses a promise to return the result. 4164 4165> **NOTE** 4166> This API can be called only after **bind** or **connect** is successfully called. 4167 4168**System capability**: SystemCapability.Communication.NetStack 4169 4170**Return value** 4171 4172| Type | Description | 4173| :-------------------------- | :---------------------------------------- | 4174| Promise\<[ExtraOptionsBase](#extraoptionsbase7)\> | Promise used to return the result.| 4175 4176**Error codes** 4177 4178| ID| Error Message | 4179| ------- | ----------------------- | 4180| 2301009 | Bad file descriptor. | 4181 4182**Example** 4183 4184```ts 4185import { socket } from '@kit.NetworkKit'; 4186 4187let client: socket.LocalSocket = socket.constructLocalSocketInstance(); 4188let sandboxPath: string = getContext().filesDir + '/testSocket' 4189let localAddress : socket.LocalAddress = { 4190 address: sandboxPath 4191} 4192let connectOpt: socket.LocalConnectOptions = { 4193 address: localAddress, 4194 timeout: 6000 4195} 4196client.connect(connectOpt).then(() => { 4197 console.log('connect success'); 4198 client.getExtraOptions().then((options : socket.ExtraOptionsBase) => { 4199 console.log('options: ' + JSON.stringify(options)); 4200 }).catch((err: Object) => { 4201 console.error('setExtraOptions fail: ' + JSON.stringify(err)); 4202 }); 4203}).catch((err: Object) => { 4204 console.error('connect fail: ' + JSON.stringify(err)); 4205}); 4206``` 4207 4208### getLocalAddress<sup>12+</sup> 4209 4210getLocalAddress(): Promise\<string\> 4211 4212Obtains the local socket address of a **LocalSocket** connection. This API uses a promise to return the result. 4213 4214> **NOTE** 4215> This API can be called only after **bind** is successfully called. 4216 4217**System capability**: SystemCapability.Communication.NetStack 4218 4219**Return value** 4220 4221| Type | Description | 4222| -------------- | --------------------------------------------------- | 4223| Promise\<string\> | Promise used to return the result.| 4224 4225**Error codes** 4226 4227| ID| Error Message | 4228| -------- | ------------------------------------------- | 4229| 2300002 | System internal error. | 4230| 2301009 | Bad file descriptor. | 4231| 2303188 | Socket operation on non-socket. | 4232 4233**Example** 4234 4235```ts 4236let client: socket.LocalSocket = socket.constructLocalSocketInstance(); 4237let sandboxPath: string = getContext().filesDir + '/testSocket'; 4238let address : socket.LocalAddress = { 4239 address: sandboxPath 4240} 4241client.bind(address).then(() => { 4242 console.error('bind success'); 4243 client.getLocalAddress().then((localPath: string) => { 4244 console.info("SUCCESS " + JSON.stringify(localPath)); 4245 }).catch((err: BusinessError) => { 4246 console.error("FAIL " + JSON.stringify(err)); 4247 }) 4248}).catch((err: Object) => { 4249 console.info('failed to bind: ' + JSON.stringify(err)); 4250}) 4251``` 4252 4253### on('message')<sup>11+</sup> 4254 4255on(type: 'message', callback: Callback\<LocalSocketMessageInfo\>): void 4256 4257Subscribes to **message** events of a **LocalSocket** object. This API uses an asynchronous callback to return the result. 4258 4259**System capability**: SystemCapability.Communication.NetStack 4260 4261**Parameters** 4262 4263| Name | Type | Mandatory| Description | 4264| -------- | ----------------------------------------------- | ---- | ----------------------------------- | 4265| type | string | Yes | Event type.<br/> **message**: message receiving event.| 4266| callback | Callback\<[LocalSocketMessageInfo](#localsocketmessageinfo11)\> | Yes | Callback used to return the result.| 4267 4268**Error codes** 4269 4270| ID| Error Message | 4271| ------- | ----------------------- | 4272| 401 | Parameter error. | 4273 4274**Example** 4275 4276```ts 4277import { socket } from '@kit.NetworkKit'; 4278 4279let client: socket.LocalSocket = socket.constructLocalSocketInstance(); 4280client.on('message', (value: socket.LocalSocketMessageInfo) => { 4281 const uintArray = new Uint8Array(value.message) 4282 let messageView = ''; 4283 for (let i = 0; i < uintArray.length; i++) { 4284 messageView += String.fromCharCode(uintArray[i]); 4285 } 4286 console.log('total: ' + JSON.stringify(value)); 4287 console.log('message infomation: ' + messageView); 4288}); 4289``` 4290 4291### off('message')<sup>11+</sup> 4292 4293off(type: 'message', callback?: Callback\<LocalSocketMessageInfo\>): void 4294 4295Unsubscribes from **message** events of a **LocalSocket** object. This API uses an asynchronous callback to return the result. 4296 4297**System capability**: SystemCapability.Communication.NetStack 4298 4299**Parameters** 4300 4301| Name | Type | Mandatory| Description | 4302| -------- | ------------------------------------------------ | ---- | ----------------------------------- | 4303| type | string | Yes | Event type.<br/> **message**: message receiving event.| 4304| callback | Callback\<[LocalSocketMessageInfo](#localsocketmessageinfo11)\> | No | Callback passed to the **on** function.| 4305 4306**Error codes** 4307 4308| ID| Error Message | 4309| ------- | ----------------------- | 4310| 401 | Parameter error. | 4311 4312**Example** 4313 4314```ts 4315import { socket } from '@kit.NetworkKit'; 4316 4317let client: socket.LocalSocket = socket.constructLocalSocketInstance(); 4318let messageView = ''; 4319let callback = (value: socket.LocalSocketMessageInfo) => { 4320 const uintArray = new Uint8Array(value.message) 4321 let messageView = ''; 4322 for (let i = 0; i < uintArray.length; i++) { 4323 messageView += String.fromCharCode(uintArray[i]); 4324 } 4325 console.log('total: ' + JSON.stringify(value)); 4326 console.log('message infomation: ' + messageView); 4327} 4328client.on('message', callback); 4329client.off('message'); 4330``` 4331 4332### on('connect')<sup>11+</sup> 4333 4334on(type: 'connect', callback: Callback\<void\>): void; 4335 4336Subscribes to **connect** events of a **LocalSocket** object. This API uses an asynchronous callback to return the result. 4337 4338**System capability**: SystemCapability.Communication.NetStack 4339 4340**Parameters** 4341 4342| Name | Type | Mandatory| Description | 4343| -------- | ---------------- | ---- | --------------------------------------------------------- | 4344| type | string | Yes | Event type.<br/> | 4345| callback | Callback\<void\> | Yes | Callback used to return the result. | 4346 4347**Error codes** 4348 4349| ID| Error Message | 4350| ------- | ----------------------- | 4351| 401 | Parameter error. | 4352 4353**Example** 4354 4355```ts 4356import { socket } from '@kit.NetworkKit'; 4357 4358let client: socket.LocalSocket = socket.constructLocalSocketInstance(); 4359client.on('connect', () => { 4360 console.log("on connect success") 4361}); 4362``` 4363 4364### off('connect')<sup>11+</sup> 4365 4366off(type: 'connect', callback?: Callback\<void\>): void; 4367 4368Unsubscribes from **connect** events of a **LocalSocket** object. This API uses an asynchronous callback to return the result. 4369 4370**System capability**: SystemCapability.Communication.NetStack 4371 4372**Parameters** 4373 4374| Name | Type | Mandatory| Description | 4375| -------- | ---------------- | ---- | --------------------------------------------------------- | 4376| type | string | Yes | Event type.<br/> | 4377| callback | Callback\<void\> | No | Callback passed to the **on** function. | 4378 4379**Error codes** 4380 4381| ID| Error Message | 4382| ------- | ----------------------- | 4383| 401 | Parameter error. | 4384 4385**Example** 4386 4387```ts 4388import { socket } from '@kit.NetworkKit'; 4389 4390let client: socket.LocalSocket = socket.constructLocalSocketInstance(); 4391let callback = () => { 4392 console.log("on connect success"); 4393} 4394client.on('connect', callback); 4395// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 4396client.off('connect', callback); 4397client.off('connect'); 4398``` 4399 4400### on('close')<sup>11+</sup> 4401 4402on(type: 'close', callback: Callback\<void\>): void; 4403 4404Subscribes to **close** events of a **LocalSocket** object. This API uses an asynchronous callback to return the result. 4405 4406**System capability**: SystemCapability.Communication.NetStack 4407 4408**Parameters** 4409 4410| Name | Type | Mandatory| Description | 4411| -------- | ---------------- | ---- | ------------------------ | 4412| type | string | Yes | Event type.| 4413| callback | Callback\<void\> | Yes | Callback used to return the result.| 4414 4415**Error codes** 4416 4417| ID| Error Message | 4418| ------- | ----------------------- | 4419| 401 | Parameter error. | 4420 4421**Example** 4422 4423```ts 4424import { socket } from '@kit.NetworkKit'; 4425 4426let client: socket.LocalSocket = socket.constructLocalSocketInstance(); 4427let callback = () => { 4428 console.log("on close success"); 4429} 4430client.on('close', callback); 4431``` 4432 4433### off('close')<sup>11+</sup> 4434 4435off(type: 'close', callback?: Callback\<void\>): void; 4436 4437Subscribes to **close** events of a **LocalSocket** object. This API uses an asynchronous callback to return the result. 4438 4439**System capability**: SystemCapability.Communication.NetStack 4440 4441**Parameters** 4442 4443| Name | Type | Mandatory| Description | 4444| -------- | ---------------- | ---- | ------------------------ | 4445| type | string | Yes | Event type.| 4446| callback | Callback\<void\> | No | Callback passed to the **on** function.| 4447 4448**Error codes** 4449 4450| ID| Error Message | 4451| ------- | ----------------------- | 4452| 401 | Parameter error. | 4453 4454**Example** 4455 4456```ts 4457import { socket } from '@kit.NetworkKit'; 4458 4459let client: socket.LocalSocket = socket.constructLocalSocketInstance(); 4460let callback = () => { 4461 console.log("on close success"); 4462} 4463client.on('close', callback); 4464// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 4465client.off('close', callback); 4466client.off('close'); 4467``` 4468 4469### on('error')<sup>11+</sup> 4470 4471on(type: 'error', callback: ErrorCallback): void 4472 4473Subscribes to **error** events of a **LocalSocket** object. This API uses an asynchronous callback to return the result. 4474 4475**System capability**: SystemCapability.Communication.NetStack 4476 4477**Parameters** 4478 4479| Name | Type | Mandatory| Description | 4480| -------- | ------------- | ---- | ---------------------------- | 4481| type | string | Yes | Event type. | 4482| callback | ErrorCallback | Yes | Callback used to return the result.| 4483 4484**Error codes** 4485 4486| ID| Error Message | 4487| ------- | ----------------------- | 4488| 401 | Parameter error. | 4489 4490**Example** 4491 4492```ts 4493import { socket } from '@kit.NetworkKit'; 4494 4495let client: socket.LocalSocket = socket.constructLocalSocketInstance(); 4496client.on('error', (err: Object) => { 4497 console.log("on error, err:" + JSON.stringify(err)) 4498}); 4499``` 4500 4501### off('error')<sup>11+</sup> 4502 4503off(type: 'error', callback?: ErrorCallback): void; 4504 4505Unsubscribes from **error** events of a **LocalSocket** object. This API uses an asynchronous callback to return the result. 4506 4507**System capability**: SystemCapability.Communication.NetStack 4508 4509**Parameters** 4510 4511| Name | Type | Mandatory| Description | 4512| -------- | ------------- | ---- | ----------------------------- | 4513| type | string | Yes | Event type.| 4514| callback | ErrorCallback | No | Callback passed to the **on** function.| 4515 4516**Error codes** 4517 4518| ID| Error Message | 4519| ------- | ----------------------- | 4520| 401 | Parameter error. | 4521 4522**Example** 4523 4524```ts 4525import { socket } from '@kit.NetworkKit'; 4526 4527let client: socket.LocalSocket = socket.constructLocalSocketInstance(); 4528let callback = (err: Object) => { 4529 console.log("on error, err:" + JSON.stringify(err)); 4530} 4531client.on('error', callback); 4532// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 4533client.off('error', callback); 4534client.off('error'); 4535``` 4536 4537## LocalSocketMessageInfo<sup>11+</sup> 4538 4539Defines the data received by the client over a local socket connection. 4540 4541**System capability**: SystemCapability.Communication.NetStack 4542 4543| Name | Type | Mandatory| Description | 4544| ------- | --------------- | --- | ------------------ | 4545| message | ArrayBuffer | Yes | Data received. | 4546| address | string | Yes | Local socket connection address.| 4547| size | number | Yes | Data length. | 4548 4549## LocalAddress<sup>11+</sup> 4550 4551Defines the address of a local socket file. When the address is passed for binding, a socket file is created at this address. 4552 4553**System capability**: SystemCapability.Communication.NetStack 4554 4555| Name | Type | Mandatory| Description | 4556| ------- | ---------- | --- | ------------------ | 4557| address | string | Yes | Address of the local socket file. | 4558 4559## LocalConnectOptions<sup>11+</sup> 4560 4561Defines local socket connection parameters. 4562 4563**System capability**: SystemCapability.Communication.NetStack 4564 4565| Name | Type | Mandatory| Description | 4566| ------- | ---------- | --- | ------------------------------ | 4567| address | [LocalAddress](#localaddress11) | Yes | Address of the local socket file. | 4568| timeout | number | No | Timeout duration of the local socket connection, in ms. | 4569 4570## LocalSendOptions<sup>11+</sup> 4571 4572Defines the parameters for sending data over a local socket connection. 4573 4574**System capability**: SystemCapability.Communication.NetStack 4575 4576| Name | Type | Mandatory| Description | 4577| ------- | ---------- | --- | ------------------- | 4578| data | string \| ArrayBuffer | Yes | Data to be transmitted.| 4579| encoding | string | No | Encoding format of the string. | 4580 4581## ExtraOptionsBase<sup>7+</sup> 4582 4583Defines other properties of the local socket connection. 4584 4585**System capability**: SystemCapability.Communication.NetStack 4586 4587| Name | Type | Mandatory| Description | 4588| ----------------- | ------- | ---- | ----------------------------- | 4589| receiveBufferSize | number | No | Size of the receive buffer, in bytes. | 4590| sendBufferSize | number | No | Size of the send buffer, in bytes. | 4591| reuseAddress | boolean | No | Whether to reuse addresses. | 4592| socketTimeout | number | No | Timeout duration of the local socket connection, in ms. | 4593 4594## socket.constructLocalSocketServerInstance<sup>11+</sup> 4595 4596constructLocalSocketServerInstance(): LocalSocketServer 4597 4598Creates a **LocalSocketServer** object. 4599 4600**System capability**: SystemCapability.Communication.NetStack 4601 4602**Return value** 4603 4604| Type | Description | 4605| :---------------------------------- | :---------------------------- | 4606| [LocalSocketServer](#localsocketserver11) | **LocalSocketServer** object.| 4607 4608**Example** 4609 4610```ts 4611import { socket } from '@kit.NetworkKit'; 4612let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance(); 4613``` 4614 4615## LocalSocketServer<sup>11+</sup> 4616 4617Defines a local socket server connection. Before calling LocalSocketServer APIs, you need to call [socket.constructLocalSocketServerInstance](#socketconstructlocalsocketserverinstance11) to create a **LocalSocketServer** object. 4618 4619### listen<sup>11+</sup> 4620 4621listen(address: LocalAddress): Promise\<void\> 4622 4623Binds the address of the local socket file. The server listens to and accepts local socket connections established over the socket. Multiple threads are used to process client data concurrently. This API uses a promise to return the result. 4624 4625> **NOTE** 4626> The server uses this API to complete the **bind**, **listen**, and **accept** operations. If the address of the local socket file is passed for binding, a socket file is automatically created when this API is called. 4627 4628**System capability**: SystemCapability.Communication.NetStack 4629 4630**Parameters** 4631 4632| Name | Type | Mandatory| Description | 4633| ------- | ------------------------- | ---- | --------------------------------------------- | 4634| address | [LocalAddress](#localaddress11) | Yes | Destination address.| 4635 4636**Return value** 4637 4638| Type | Description | 4639| :-------------- | :---------------------------------------------------- | 4640| 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.| 4641 4642**Error codes** 4643 4644| ID| Error Message | 4645| -------- | --------------------------- | 4646| 401 | Parameter error. | 4647| 2303109 | Bad file number. | 4648| 2301013 | Insufficient permissions. | 4649| 2301022 | Invalid argument. | 4650| 2301098 | Address already in use. | 4651 4652**Example** 4653 4654```ts 4655import { socket } from '@kit.NetworkKit'; 4656 4657let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance(); 4658let sandboxPath: string = getContext().filesDir + '/testSocket' 4659let addr: socket.LocalAddress = { 4660 address: sandboxPath 4661} 4662server.listen(addr).then(() => { 4663 console.log('listen success'); 4664}).catch((err: Object) => { 4665 console.error('listen fail: ' + JSON.stringify(err)); 4666}); 4667``` 4668 4669### getState<sup>11+</sup> 4670 4671getState(): Promise\<SocketStateBase\> 4672 4673Obtains the status of a local socket server connection. This API uses a promise to return the result. 4674 4675> **NOTE** 4676> This API can be called only after **listen** is successfully called. 4677 4678**System capability**: SystemCapability.Communication.NetStack 4679 4680**Return value** 4681 4682| Type | Description | 4683| :------------------------------------------- | :--------------------------------------------- | 4684| Promise\<[SocketStateBase](#socketstatebase)\> | Promise used to return the result.| 4685 4686**Example** 4687 4688```ts 4689import { socket } from '@kit.NetworkKit'; 4690 4691let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance(); 4692let sandboxPath: string = getContext().filesDir + '/testSocket' 4693let listenAddr: socket.LocalAddress = { 4694 address: sandboxPath 4695} 4696server.listen(listenAddr).then(() => { 4697 console.log("listen success"); 4698}).catch((err: Object) => { 4699 console.error("listen fail: " + JSON.stringify(err)); 4700}) 4701server.getState().then((data: socket.SocketStateBase) => { 4702 console.log('getState success: ' + JSON.stringify(data)); 4703}).catch((err: Object) => { 4704 console.error('getState fail: ' + JSON.stringify(err)); 4705}); 4706``` 4707 4708### setExtraOptions<sup>11+</sup> 4709 4710setExtraOptions(options: ExtraOptionsBase): Promise\<void\> 4711 4712Sets other properties of the local socket server connection. This API uses a promise to return the result. 4713 4714> **NOTE** 4715> This API can be called only after **listen** is successfully called. 4716 4717**System capability**: SystemCapability.Communication.NetStack 4718 4719**Parameters** 4720 4721| Name | Type | Mandatory| Description | 4722| ------- | --------------------------------------- | ---- | ------------------------------ | 4723| options | [ExtraOptionsBase](#extraoptionsbase7) | Yes | Other properties of a local socket server connection.| 4724 4725**Return value** 4726 4727| Type | Description | 4728| :-------------- | :---------------------------------------------- | 4729| 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.| 4730 4731**Error codes** 4732 4733| ID| Error Message | 4734| -------- | ------------------------------- | 4735| 401 | Parameter error. | 4736| 2301009 | Bad file descriptor. | 4737 4738**Example** 4739 4740```ts 4741import { socket } from '@kit.NetworkKit'; 4742 4743let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance(); 4744let sandboxPath: string = getContext().filesDir + '/testSocket' 4745let listenAddr: socket.NetAddress = { 4746 address: sandboxPath 4747} 4748server.listen(listenAddr).then(() => { 4749 console.log("listen success"); 4750}).catch((err: Object) => { 4751 console.error("listen fail: " + JSON.stringify(err)); 4752}) 4753 4754let options: socket.ExtraOptionsBase = { 4755 receiveBufferSize: 6000, 4756 sendBufferSize: 6000, 4757 socketTimeout: 3000 4758} 4759server.setExtraOptions(options).then(() => { 4760 console.log('setExtraOptions success'); 4761}).catch((err: Object) => { 4762 console.error('setExtraOptions fail: ' + JSON.stringify(err)); 4763}); 4764``` 4765 4766### getExtraOptions<sup>11+</sup> 4767 4768getExtraOptions(): Promise\<ExtraOptionsBase\>; 4769 4770Obtains other properties of a local socket server connection. This API uses a promise to return the result. 4771 4772> **NOTE** 4773> This API can be called only after **listen** is successfully called. 4774 4775**System capability**: SystemCapability.Communication.NetStack 4776 4777**Return value** 4778 4779| Type | Description | 4780| :-------------------------- | :-------------------------- | 4781| Promise\<[ExtraOptionsBase](#extraoptionsbase7)\> | Promise used to return the result.| 4782 4783**Error codes** 4784 4785| ID| Error Message | 4786| -------- | -------------------- | 4787| 401 | Parameter error. | 4788 4789**Example** 4790 4791```ts 4792import { socket } from '@kit.NetworkKit'; 4793 4794let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance(); 4795let sandboxPath: string = getContext().filesDir + '/testSocket' 4796let listenAddr: socket.LocalAddress = { 4797 address: sandboxPath 4798} 4799server.listen(listenAddr).then(() => { 4800 console.log("listen success"); 4801}).catch((err: Object) => { 4802 console.error("listen fail: " + JSON.stringify(err)); 4803}) 4804server.getExtraOptions().then((options: socket.ExtraOptionsBase) => { 4805 console.log('options: ' + JSON.stringify(options)); 4806}).catch((err: Object) => { 4807 console.error('getExtraOptions fail: ' + JSON.stringify(err)); 4808}); 4809``` 4810 4811### getLocalAddress<sup>12+</sup> 4812 4813getLocalAddress(): Promise\<string\> 4814 4815Obtains the local socket address of a **LocalSocketServer** connection. This API uses a promise to return the result. 4816 4817> **NOTE** 4818> This API can be called only after **listen** is successfully called. 4819 4820**System capability**: SystemCapability.Communication.NetStack 4821 4822**Return value** 4823 4824| Type | Description | 4825| -------------- | --------------------------------------------------- | 4826| Promise\<string\> | Promise used to return the result.| 4827 4828**Error codes** 4829 4830| ID| Error Message | 4831| -------- | ------------------------------------------- | 4832| 2300002 | System internal error. | 4833| 2301009 | Bad file descriptor. | 4834| 2303188 | Socket operation on non-socket. | 4835 4836**Example** 4837 4838```ts 4839let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance(); 4840let sandboxPath: string = getContext().filesDir + '/testSocket'; 4841let listenAddr: socket.LocalAddress = { 4842 address: sandboxPath 4843} 4844server.listen(listenAddr).then(() => { 4845 console.info("listen success"); 4846 server.getLocalAddress().then((localPath: string) => { 4847 console.info("SUCCESS " + JSON.stringify(localPath)); 4848 }).catch((err: BusinessError) => { 4849 console.error("FAIL " + JSON.stringify(err)); 4850 }) 4851}).catch((err: Object) => { 4852 console.error("listen fail: " + JSON.stringify(err)); 4853}) 4854 4855``` 4856 4857### on('connect')<sup>11+</sup> 4858 4859on(type: 'connect', callback: Callback\<LocalSocketConnection\>): void 4860 4861Subscribes to **connect** events of a **LocalSocketServer** object. This API uses an asynchronous callback to return the result. 4862 4863> **NOTE** 4864> This API can be called only after **listen** is successfully called. 4865 4866**System capability**: SystemCapability.Communication.NetStack 4867 4868**Parameters** 4869 4870| Name | Type | Mandatory| Description | 4871| -------- | ------------------------------- | ---- | ------------------------------------- | 4872| type | string | Yes | Event type.<br/> **connect**: connection event.| 4873| callback | Callback\<[LocalSocketConnection](#localsocketconnection11)\> | Yes | Callback used to return the result.| 4874 4875**Error codes** 4876 4877| ID| Error Message | 4878| -------- | ---------------- | 4879| 401 | Parameter error. | 4880 4881**Example** 4882 4883```ts 4884import { socket } from '@kit.NetworkKit'; 4885 4886let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance(); 4887server.on('connect', (connection: socket.LocalSocketConnection) => { 4888 if (connection) { 4889 console.log('accept a client') 4890 } 4891}); 4892``` 4893 4894### off('connect')<sup>11+</sup> 4895 4896off(type: 'connect', callback?: Callback\<LocalSocketConnection\>): void 4897 4898Unsubscribes from **connect** events of a **LocalSocketServer** object. This API uses an asynchronous callback to return the result. 4899 4900**System capability**: SystemCapability.Communication.NetStack 4901 4902**Parameters** 4903 4904| Name | Type | Mandatory| Description | 4905| -------- | ------------------------------- | ---- | ------------------------------------- | 4906| type | string | Yes | Event type.<br/> **connect**: connection event.| 4907| callback | Callback\<[LocalSocketConnection](#localsocketconnection11)\> | No | Callback passed to the **on** function.| 4908 4909**Error codes** 4910 4911| ID| Error Message | 4912| -------- | ---------------- | 4913| 401 | Parameter error. | 4914 4915**Example** 4916 4917```ts 4918import { socket } from '@kit.NetworkKit'; 4919 4920let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance(); 4921let callback = (connection: socket.LocalSocketConnection) => { 4922 if (connection) { 4923 console.log('accept a client') 4924 } 4925} 4926server.on('connect', callback); 4927// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 4928server.off('connect', callback); 4929server.off('connect'); 4930``` 4931 4932### on('error')<sup>11+</sup> 4933 4934on(type: 'error', callback: ErrorCallback): void 4935 4936Subscribes to **error** events of a **LocalSocketServer** object. This API uses an asynchronous callback to return the result. 4937 4938> **NOTE** 4939> This API can be called only after **listen** is successfully called. 4940 4941**System capability**: SystemCapability.Communication.NetStack 4942 4943**Parameters** 4944 4945| Name | Type | Mandatory| Description | 4946| -------- | ------------- | ---- | ------------------------------------ | 4947| type | string | Yes | Event type.<br/> **error**: error event.| 4948| callback | ErrorCallback | Yes | Callback used to return the result.| 4949 4950**Error codes** 4951 4952| ID| Error Message | 4953| -------- | ---------------- | 4954| 401 | Parameter error. | 4955 4956**Example** 4957 4958```ts 4959import { socket } from '@kit.NetworkKit'; 4960 4961let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance(); 4962server.on('error', (err: Object) => { 4963 console.error("on error, err:" + JSON.stringify(err)) 4964}); 4965``` 4966 4967### off('error')<sup>11+</sup> 4968 4969off(type: 'error', callback?: ErrorCallback): void 4970 4971Unsubscribes from **error** events of a **LocalSocketServer** object. This API uses an asynchronous callback to return the result. 4972 4973**System capability**: SystemCapability.Communication.NetStack 4974 4975**Parameters** 4976 4977| Name | Type | Mandatory| Description | 4978| -------- | ------------- | ---- | ------------------------------------ | 4979| type | string | Yes | Event type.<br/> **error**: error event.| 4980| callback | ErrorCallback | No | Callback passed to the **on** function. | 4981 4982**Error codes** 4983 4984| ID| Error Message | 4985| -------- | ---------------- | 4986| 401 | Parameter error. | 4987 4988**Example** 4989 4990```ts 4991import { socket } from '@kit.NetworkKit'; 4992 4993let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance(); 4994let callback = (err: Object) => { 4995 console.error("on error, err:" + JSON.stringify(err)); 4996} 4997server.on('error', callback); 4998// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 4999server.off('error', callback); 5000server.off('error'); 5001``` 5002 5003 5004## LocalSocketConnection<sup>11+</sup> 5005 5006Defines a local socket connection, that is, the session between the local socket client and the server. Before calling LocalSocketConnection APIs, you need to obtain a **LocalSocketConnection** object. 5007 5008> **NOTE** 5009> The LocalSocketConnection client can call related APIs through the **LocalSocketConnection** object only after a connection is successfully established between the local socket client and the server. 5010 5011**System capability**: SystemCapability.Communication.NetStack 5012 5013### Attributes 5014 5015| Name | Type | Mandatory| Description | 5016| -------- | ------ | ---- | ---------------------------- | 5017| clientId | number | Yes | ID of the session between the client and the server.| 5018 5019### send<sup>11+</sup> 5020 5021send(options: LocalSendOptions): Promise\<void\> 5022 5023Sends data through a local socket connection. This API uses a promise to return the result. 5024 5025> **NOTE** 5026> This API can be used only after the server obtains a **LocalSocketConnection** object through the **callback** of the **connect** event. 5027 5028**System capability**: SystemCapability.Communication.NetStack 5029 5030**Parameters** 5031 5032| Name | Type | Mandatory| Description | 5033| ------- | --------------------------------- | ---- | -------------------------------------- | 5034| options | [LocalSendOptions](#localsendoptions11) | Yes | Defines the parameters for sending data over a local socket connection.| 5035 5036**Return value** 5037 5038| Type | Description | 5039| :-------------- | :---------------------------------------------- | 5040| 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.| 5041 5042**Error codes** 5043 5044| ID| Error Message | 5045| -------- | ---------------------- | 5046| 401 | Parameter error. | 5047| 2301011 | Operation would block. | 5048 5049**Example** 5050 5051```ts 5052import { socket } from '@kit.NetworkKit'; 5053 5054let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance(); 5055 5056server.on('connect', (connection: socket.LocalSocketConnection) => { 5057 let sendOptions: socket.LocalSendOptions = { 5058 data: 'Hello, client!' 5059 } 5060 connection.send(sendOptions).then(() => { 5061 console.log('send success'); 5062 }).catch((err: Object) => { 5063 console.error('send fail: ' + JSON.stringify(err)); 5064 }); 5065}); 5066``` 5067 5068### close<sup>11+</sup> 5069 5070close(): Promise\<void\> 5071 5072Closes a local socket connection. This API uses a promise to return the result. 5073 5074**System capability**: SystemCapability.Communication.NetStack 5075 5076**Return value** 5077 5078| Type | Description | 5079| :-------------- | :------------------------------------------- | 5080| 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.| 5081 5082**Error codes** 5083 5084| ID| Error Message | 5085| -------- | -------------------- | 5086| 2301009 | Bad file descriptor. | 5087 5088**Example** 5089 5090```ts 5091import { socket } from '@kit.NetworkKit'; 5092 5093let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance(); 5094server.on('connect', (connection: socket.LocalSocketConnection) => { 5095 connection.close().then(() => { 5096 console.log('close success'); 5097 }).catch((err: Object) => { 5098 console.error('close fail: ' + JSON.stringify(err)); 5099 }); 5100}); 5101``` 5102 5103### getLocalAddress<sup>12+</sup> 5104 5105getLocalAddress(): Promise\<string\> 5106 5107Obtains the local socket address of a **LocalSocketConnection** connection. This API uses a promise to return the result. 5108 5109**System capability**: SystemCapability.Communication.NetStack 5110 5111**Return value** 5112 5113| Type | Description | 5114| -------------- | --------------------------------------------------- | 5115| Promise\<string\> | Promise used to return the result.| 5116 5117**Error codes** 5118 5119| ID| Error Message | 5120| -------- | ------------------------------------------- | 5121| 2300002 | System internal error. | 5122| 2301009 | Bad file descriptor. | 5123| 2303188 | Socket operation on non-socket. | 5124 5125**Example** 5126 5127```ts 5128let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance(); 5129let sandboxPath: string = getContext().filesDir + '/testSocket'; 5130let localAddr: socket.LocalAddress = { 5131 address: sandboxPath 5132} 5133server.listen(localAddr).then(() => { 5134 console.info('listen success'); 5135 let client: socket.LocalSocket = socket.constructLocalSocketInstance(); 5136 let connectOpt: socket.LocalConnectOptions = { 5137 address: localAddr, 5138 timeout: 6000 5139 } 5140 client.connect(connectOpt).then(() => { 5141 server.getLocalAddress().then((localPath: string) => { 5142 console.info("success, localPath is" + JSON.stringify(localPath)); 5143 }).catch((err: BusinessError) => { 5144 console.error("FAIL " + JSON.stringify(err)); 5145 }) 5146 }).catch((err: Object) => { 5147 console.error('connect fail: ' + JSON.stringify(err)); 5148 }); 5149}); 5150``` 5151 5152### on('message')<sup>11+</sup> 5153 5154on(type: 'message', callback: Callback\<LocalSocketMessageInfo\>): void; 5155 5156Subscribes to **message** events of a **LocalSocketConnection** object. This API uses an asynchronous callback to return the result. 5157 5158**System capability**: SystemCapability.Communication.NetStack 5159 5160**Parameters** 5161 5162| Name | Type | Mandatory| Description | 5163| -------- | ----------------------------------------------- | ---- | --------------------------------------- | 5164| type | string | Yes | Event type.<br/> **message**: message receiving event. | 5165| callback | Callback\<[LocalSocketMessageInfo](#localsocketmessageinfo11)\> | Yes | Callback used to return the result.| 5166 5167**Error codes** 5168 5169| ID| Error Message | 5170| -------- | ---------------- | 5171| 401 | Parameter error. | 5172 5173**Example** 5174 5175```ts 5176import { socket } from '@kit.NetworkKit'; 5177 5178let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance(); 5179let sandboxPath: string = getContext().filesDir + '/testSocket' 5180let listenAddr: socket.LocalAddress = { 5181 address: sandboxPath 5182} 5183server.listen(listenAddr).then(() => { 5184 console.log("listen success"); 5185}).catch((err: Object) => { 5186 console.error("listen fail: " + JSON.stringify(err)); 5187}); 5188server.on('connect', (connection: socket.LocalSocketConnection) => { 5189 connection.on('message', (value: socket.LocalSocketMessageInfo) => { 5190 const uintArray = new Uint8Array(value.message); 5191 let messageView = ''; 5192 for (let i = 0; i < uintArray.length; i++) { 5193 messageView += String.fromCharCode(uintArray[i]); 5194 } 5195 console.log('total: ' + JSON.stringify(value)); 5196 console.log('message infomation: ' + messageView); 5197 }); 5198}); 5199``` 5200 5201### off('message')<sup>11+</sup> 5202 5203off(type: 'message', callback?: Callback\<LocalSocketMessageInfo\>): void 5204 5205Unsubscribes from **message** events of a **LocalSocketConnection** object. This API uses an asynchronous callback to return the result. 5206 5207**System capability**: SystemCapability.Communication.NetStack 5208 5209**Parameters** 5210 5211| Name | Type | Mandatory| Description | 5212| -------- | ----------------------------------------------- | ---- | ----------------------------------- | 5213| type | string | Yes | Event type.<br/> **message**: message receiving event.| 5214| callback | Callback\<[LocalSocketMessageInfo](#localsocketmessageinfo11)\> | No | Callback passed to the **on** function.| 5215 5216**Error codes** 5217 5218| ID| Error Message | 5219| -------- | ---------------- | 5220| 401 | Parameter error. | 5221 5222**Example** 5223 5224```ts 5225import { socket } from '@kit.NetworkKit'; 5226 5227let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance(); 5228let callback = (value: socket.LocalSocketMessageInfo) => { 5229 const uintArray = new Uint8Array(value.message) 5230 let messageView = ''; 5231 for (let i = 0; i < uintArray.length; i++) { 5232 messageView += String.fromCharCode(uintArray[i]); 5233 } 5234 console.log('total: ' + JSON.stringify(value)); 5235 console.log('message infomation: ' + messageView); 5236} 5237server.on('connect', (connection: socket.LocalSocketConnection) => { 5238 connection.on('message', callback); 5239 // You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 5240 connection.off('message', callback); 5241 connection.off('message'); 5242}); 5243``` 5244 5245### on('close')<sup>11+</sup> 5246 5247on(type: 'close', callback: Callback\<void\>): void 5248 5249Unsubscribes from **close** events of a **LocalSocketConnection** object. This API uses an asynchronous callback to return the result. 5250 5251**System capability**: SystemCapability.Communication.NetStack 5252 5253**Parameters** 5254 5255| Name | Type | Mandatory| Description | 5256| -------- | ---------------- | ---- | ----------------------------------- | 5257| type | string | Yes | Event type.<br/> **close**: close event.| 5258| callback | Callback\<void\> | Yes | Callback used to return the result.| 5259 5260**Error codes** 5261 5262| ID| Error Message | 5263| -------- | ---------------- | 5264| 401 | Parameter error. | 5265 5266**Example** 5267 5268```ts 5269import { socket } from '@kit.NetworkKit'; 5270 5271let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance(); 5272server.on('connect', (connection: socket.LocalSocketConnection) => { 5273 connection.on('close', () => { 5274 console.log("on close success") 5275 }); 5276}); 5277``` 5278 5279### off('close')<sup>11+</sup> 5280 5281off(type: 'close', callback?: Callback\<void\>): void 5282 5283Unsubscribes from **close** events of a **LocalSocketConnection** object. This API uses an asynchronous callback to return the result. 5284 5285**System capability**: SystemCapability.Communication.NetStack 5286 5287**Parameters** 5288 5289| Name | Type | Mandatory| Description | 5290| -------- | ---------------- | ---- | ----------------------------------- | 5291| type | string | Yes | Event type.<br/> **close**: close event.| 5292| callback | Callback\<void\> | No | Callback passed to the **on** function.| 5293 5294**Error codes** 5295 5296| ID| Error Message | 5297| -------- | ---------------- | 5298| 401 | Parameter error. | 5299 5300**Example** 5301 5302```ts 5303import { socket } from '@kit.NetworkKit'; 5304 5305let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance(); 5306let callback = () => { 5307 console.log("on close success"); 5308} 5309server.on('connect', (connection: socket.LocalSocketConnection) => { 5310 connection.on('close', callback); 5311 // You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 5312 connection.off('close', callback); 5313 connection.off('close'); 5314}); 5315``` 5316 5317### on('error')<sup>11+</sup> 5318 5319on(type: 'error', callback: ErrorCallback): void 5320 5321Subscribes to **error** events of a **LocalSocketConnection** object. This API uses an asynchronous callback to return the result. 5322 5323**System capability**: SystemCapability.Communication.NetStack 5324 5325**Parameters** 5326 5327| Name | Type | Mandatory| Description | 5328| -------- | ------------- | ---- | ------------------------------------ | 5329| type | string | Yes | Event type.<br/> **error**: error event.| 5330| callback | ErrorCallback | Yes | Callback used to return the result.| 5331 5332**Error codes** 5333 5334| ID| Error Message | 5335| -------- | ---------------- | 5336| 401 | Parameter error. | 5337 5338**Example** 5339 5340```ts 5341import { socket } from '@kit.NetworkKit'; 5342 5343let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance(); 5344server.on('connect', (connection: socket.LocalSocketConnection) => { 5345 connection.on('error', (err: Object) => { 5346 console.error("on error, err:" + JSON.stringify(err)) 5347 }); 5348}); 5349``` 5350 5351### off('error')<sup>11+</sup> 5352 5353off(type: 'error', callback?: ErrorCallback): void 5354 5355Unsubscribes from **error** events of a **LocalSocketConnection** object. This API uses an asynchronous callback to return the result. 5356 5357**System capability**: SystemCapability.Communication.NetStack 5358 5359**Parameters** 5360 5361| Name | Type | Mandatory| Description | 5362| -------- | ------------- | ---- | ------------------------------------ | 5363| type | string | Yes | Event type.<br/> **error**: error event.| 5364| callback | ErrorCallback | No | Callback passed to the **on** function. | 5365 5366**Error codes** 5367 5368| ID| Error Message | 5369| -------- | ---------------- | 5370| 401 | Parameter error. | 5371 5372**Example** 5373 5374```ts 5375import { socket } from '@kit.NetworkKit'; 5376 5377let callback = (err: Object) => { 5378 console.error("on error, err: " + JSON.stringify(err)); 5379} 5380let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance(); 5381server.on('connect', (connection: socket.LocalSocketConnection) => { 5382 connection.on('error', callback); 5383 // You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 5384 connection.off('error', callback); 5385 connection.off('error'); 5386}); 5387``` 5388 5389## Description of LocalSocket Error Codes 5390 5391The LocalSocket error code mapping is in the format of 2301000 + Linux kernel error code. 5392 5393For details about error codes, see [Socket Error Codes](errorcode-net-socket.md). 5394 5395## socket.constructTLSSocketInstance<sup>9+</sup> 5396 5397constructTLSSocketInstance(): TLSSocket 5398 5399Creates a **TLSSocket** object. 5400 5401**System capability**: SystemCapability.Communication.NetStack 5402 5403**Return value** 5404 5405| Type | Description | 5406| --------------------------------- | ---------------------- | 5407| [TLSSocket](#tlssocket9) | **TLSSocket** object.| 5408 5409**Example** 5410 5411```ts 5412import { socket } from '@kit.NetworkKit'; 5413 5414let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 5415``` 5416 5417## socket.constructTLSSocketInstance<sup>12+</sup> 5418 5419constructTLSSocketInstance(tcpSocket: TCPSocket): TLSSocket 5420 5421Upgrades a **TCPSocket** connection to a **TLSSocket** connection. 5422 5423> **NOTE** 5424> Before calling **constructTLSSocketInstance**, ensure that a **TCPSocket** connection has been established and no data is transmitted. After a successful upgrade, you do not need to call the **close** API for the **TCPSocket** object. 5425 5426**System capability**: SystemCapability.Communication.NetStack 5427 5428**Parameters** 5429 5430| Name | Type| Mandatory| Description | 5431|-----------|----| ---- |------------------------| 5432| tcpSocket | [TCPSocket](#tcpsocket) | Yes | **TCPSocket** connection to be upgraded.| 5433 5434**Return value** 5435 5436| Type | Description | 5437| --------------------------------- | ---------------------- | 5438| [TLSSocket](#tlssocket9) | **TLSSocket** object.| 5439 5440**Error codes** 5441 5442| ID | Error Message | 5443|---------|----------------------------------| 5444| 401 | Parameter error. | 5445| 2300002 | System internal error. | 5446| 2303601 | Invalid socket FD. | 5447| 2303602 | Socket is not connected. | 5448 5449**Example** 5450 5451```ts 5452import { socket } from '@kit.NetworkKit'; 5453import { BusinessError } from '@kit.BasicServicesKit'; 5454 5455let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 5456let tcpconnectoptions: socket.TCPConnectOptions = { 5457 address: { 5458 address: '192.168.xx.xxx', 5459 port: 8080 5460 }, 5461 timeout: 6000 5462} 5463tcp.connect(tcpconnectoptions, (err: BusinessError) => { 5464 if (err) { 5465 console.log('connect fail'); 5466 return; 5467 } 5468 console.log('connect success'); 5469 5470 // Ensure that a TCPSocket connection has been established before upgrading it to a TLSSocket connection. 5471 let tls: socket.TLSSocket = socket.constructTLSSocketInstance(tcp); 5472}) 5473``` 5474 5475## TLSSocket<sup>9+</sup> 5476 5477Defines a TLS socket connection. Before calling TLSSocket APIs, you need to call [socket.constructTLSSocketInstance](#socketconstructtlssocketinstance9) to create a **TLSSocket** object. 5478 5479### bind<sup>9+</sup> 5480 5481bind(address: NetAddress, callback: AsyncCallback\<void\>): void 5482 5483Binds the IP address and port number. This API uses an asynchronous callback to return the result. 5484 5485> **NOTE** 5486> If the **TLSSocket** object is upgraded from a **TCPSocket** object, you do not need to execute the **bind** API. 5487 5488**Required permissions**: ohos.permission.INTERNET 5489 5490**System capability**: SystemCapability.Communication.NetStack 5491 5492**Parameters** 5493 5494| Name | Type | Mandatory| Description | 5495| -------- | ---------------------------------- | ---- | ------------------------------------------------------ | 5496| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| 5497| 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.| 5498 5499**Error codes** 5500 5501| ID| Error Message | 5502| ------- | ----------------------- | 5503| 401 | Parameter error. | 5504| 201 | Permission denied. | 5505| 2303198 | Address already in use. | 5506| 2300002 | System internal error. | 5507 5508**Example** 5509 5510```ts 5511import { socket } from '@kit.NetworkKit'; 5512import { BusinessError } from '@kit.BasicServicesKit'; 5513 5514let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 5515let bindAddr: socket.NetAddress = { 5516 address: '192.168.xx.xxx', 5517 port: 8080 5518} 5519tls.bind(bindAddr, (err: BusinessError) => { 5520 if (err) { 5521 console.log('bind fail'); 5522 return; 5523 } 5524 console.log('bind success'); 5525}); 5526``` 5527 5528### bind<sup>9+</sup> 5529 5530bind(address: NetAddress): Promise\<void\> 5531 5532Binds the IP address and port number. This API uses a promise to return the result. 5533 5534> **NOTE** 5535> If the **TLSSocket** object is upgraded from a **TCPSocket** object, you do not need to execute the **bind** API. 5536 5537**Required permissions**: ohos.permission.INTERNET 5538 5539**System capability**: SystemCapability.Communication.NetStack 5540 5541**Parameters** 5542 5543| Name | Type | Mandatory| Description | 5544| ------- | ---------------------------------- | ---- | ------------------------------------------------------ | 5545| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| 5546 5547**Return value** 5548 5549| Type | Description | 5550| -------------- | ------------------------------------------------------- | 5551| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.| 5552 5553**Error codes** 5554 5555| ID| Error Message | 5556| ------- | ----------------------- | 5557| 401 | Parameter error. | 5558| 201 | Permission denied. | 5559| 2303198 | Address already in use. | 5560| 2300002 | System internal error. | 5561 5562**Example** 5563 5564```ts 5565import { socket } from '@kit.NetworkKit'; 5566import { BusinessError } from '@kit.BasicServicesKit'; 5567 5568let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 5569let bindAddr: socket.NetAddress = { 5570 address: '192.168.xx.xxx', 5571 port: 8080 5572} 5573tls.bind(bindAddr).then(() => { 5574 console.log('bind success'); 5575}).catch((err: BusinessError) => { 5576 console.log('bind fail'); 5577}); 5578``` 5579 5580### getState<sup>9+</sup> 5581 5582getState(callback: AsyncCallback\<SocketStateBase\>): void 5583 5584Obtains the status of the TLS socket connection. This API uses an asynchronous callback to return the result. 5585 5586**System capability**: SystemCapability.Communication.NetStack 5587 5588**Parameters** 5589 5590| Name | Type | Mandatory| Description | 5591| -------- | ------------------------------------------------------ | ---- | ---------- | 5592| callback | AsyncCallback\<[SocketStateBase](#socketstatebase)\> | Yes | Callback used to return the result. If the operation is successful, the status of the TLS socket connection is returned. If the operation fails, an error message is returned.| 5593 5594**Error codes** 5595 5596| ID| Error Message | 5597| ------- | ------------------------------ | 5598| 2303188 | Socket operation on non-socket.| 5599| 2300002 | System internal error. | 5600 5601**Example** 5602 5603```ts 5604import { socket } from '@kit.NetworkKit'; 5605import { BusinessError } from '@kit.BasicServicesKit'; 5606 5607let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 5608let bindAddr: socket.NetAddress = { 5609 address: '192.168.xx.xxx', 5610 port: 8080 5611} 5612tls.bind(bindAddr, (err: BusinessError) => { 5613 if (err) { 5614 console.log('bind fail'); 5615 return; 5616 } 5617 console.log('bind success'); 5618}); 5619tls.getState((err: BusinessError, data: socket.SocketStateBase) => { 5620 if (err) { 5621 console.log('getState fail'); 5622 return; 5623 } 5624 console.log('getState success:' + JSON.stringify(data)); 5625}); 5626``` 5627 5628### getState<sup>9+</sup> 5629 5630getState(): Promise\<SocketStateBase\> 5631 5632Obtains the status of the TLS socket connection. This API uses a promise to return the result. 5633 5634**System capability**: SystemCapability.Communication.NetStack 5635 5636**Return value** 5637 5638| Type | Description | 5639| ----------------------------------------------- | ----------------------------------------- | 5640| Promise\<[SocketStateBase](#socketstatebase)\> | Promise used to return the result. If the operation fails, an error message is returned.| 5641 5642**Error codes** 5643 5644| ID| Error Message | 5645| ------- | ------------------------------ | 5646| 2303188 | Socket operation on non-socket.| 5647| 2300002 | System internal error. | 5648 5649**Example** 5650 5651```ts 5652import { socket } from '@kit.NetworkKit'; 5653import { BusinessError } from '@kit.BasicServicesKit'; 5654 5655let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 5656let bindAddr: socket.NetAddress = { 5657 address: '192.168.xx.xxx', 5658 port: 8080 5659} 5660tls.bind(bindAddr, (err: BusinessError) => { 5661 if (err) { 5662 console.log('bind fail'); 5663 return; 5664 } 5665 console.log('bind success'); 5666}); 5667tls.getState().then(() => { 5668 console.log('getState success'); 5669}).catch((err: BusinessError) => { 5670 console.log('getState fail'); 5671}); 5672``` 5673 5674### setExtraOptions<sup>9+</sup> 5675 5676setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\<void\>): void 5677 5678Sets other properties of the TCP socket connection after **bind** is successfully called. This API uses an asynchronous callback to return the result. 5679 5680**System capability**: SystemCapability.Communication.NetStack 5681 5682**Parameters** 5683 5684| Name | Type | Mandatory| Description | 5685| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | 5686| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCP socket connection. For details, see [TCPExtraOptions](#tcpextraoptions).| 5687| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation is successful, the result of setting other properties of the TCP socket connection is returned. If the operation fails, an error message is returned.| 5688 5689**Error codes** 5690 5691| ID| Error Message | 5692| ------- | ----------------------------- | 5693| 401 | Parameter error. | 5694| 2303188 | Socket operation on non-socket.| 5695| 2300002 | System internal error. | 5696 5697**Example** 5698 5699```ts 5700import { socket } from '@kit.NetworkKit'; 5701import { BusinessError } from '@kit.BasicServicesKit'; 5702 5703let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 5704let bindAddr: socket.NetAddress = { 5705 address: '192.168.xx.xxx', 5706 port: 8080 5707} 5708tls.bind(bindAddr, (err: BusinessError) => { 5709 if (err) { 5710 console.log('bind fail'); 5711 return; 5712 } 5713 console.log('bind success'); 5714}); 5715 5716interface SocketLinger { 5717 on: boolean; 5718 linger: number; 5719} 5720 5721let tcpExtraOptions: socket.TCPExtraOptions = { 5722 keepAlive: true, 5723 OOBInline: true, 5724 TCPNoDelay: true, 5725 socketLinger: { on: true, linger: 10 } as SocketLinger, 5726 receiveBufferSize: 1000, 5727 sendBufferSize: 1000, 5728 reuseAddress: true, 5729 socketTimeout: 3000 5730} 5731tls.setExtraOptions(tcpExtraOptions, (err: BusinessError) => { 5732 if (err) { 5733 console.log('setExtraOptions fail'); 5734 return; 5735 } 5736 console.log('setExtraOptions success'); 5737}); 5738``` 5739 5740### setExtraOptions<sup>9+</sup> 5741 5742setExtraOptions(options: TCPExtraOptions): Promise\<void\> 5743 5744Sets other properties of the TCP socket connection after **bind** is successfully called. This API uses a promise to return the result. 5745 5746**System capability**: SystemCapability.Communication.NetStack 5747 5748**Parameters** 5749 5750| Name | Type | Mandatory| Description | 5751| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | 5752| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCP socket connection. For details, see [TCPExtraOptions](#tcpextraoptions).| 5753 5754**Return value** 5755 5756| Type | Description | 5757| -------------- | --------------------------------------------------- | 5758| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.| 5759 5760**Error codes** 5761 5762| ID| Error Message | 5763| ------- | ------------------------------ | 5764| 401 | Parameter error. | 5765| 2303188 | Socket operation on non-socket.| 5766| 2300002 | System internal error. | 5767 5768**Example** 5769 5770```ts 5771import { socket } from '@kit.NetworkKit'; 5772import { BusinessError } from '@kit.BasicServicesKit'; 5773 5774let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 5775let bindAddr: socket.NetAddress = { 5776 address: '192.168.xx.xxx', 5777 port: 8080 5778} 5779tls.bind(bindAddr, (err: BusinessError) => { 5780 if (err) { 5781 console.log('bind fail'); 5782 return; 5783 } 5784 console.log('bind success'); 5785}); 5786 5787interface SocketLinger { 5788 on: boolean; 5789 linger: number; 5790} 5791 5792let tcpExtraOptions: socket.TCPExtraOptions = { 5793 keepAlive: true, 5794 OOBInline: true, 5795 TCPNoDelay: true, 5796 socketLinger: { on: true, linger: 10 } as SocketLinger, 5797 receiveBufferSize: 1000, 5798 sendBufferSize: 1000, 5799 reuseAddress: true, 5800 socketTimeout: 3000 5801} 5802tls.setExtraOptions(tcpExtraOptions).then(() => { 5803 console.log('setExtraOptions success'); 5804}).catch((err: BusinessError) => { 5805 console.log('setExtraOptions fail'); 5806}); 5807``` 5808 5809### on('message')<sup>9+</sup> 5810 5811on(type: 'message', callback: Callback\<SocketMessageInfo\>): void; 5812 5813Subscribes to **message** events of the TLS socket connection. This API uses an asynchronous callback to return the result. 5814 5815**System capability**: SystemCapability.Communication.NetStack 5816 5817**Parameters** 5818 5819| Name | Type | Mandatory| Description | 5820| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 5821| type | string | Yes | Event type.<br/> **message**: message receiving event.| 5822| callback | Callback\<[SocketMessageInfo](#socketmessageinfo11)\> | Yes | Callback used to return the result. The TLSSocket connection subscribes to the function triggered by a type of message receiving event and returns the TLSSocket connection information.| 5823 5824**Error codes** 5825 5826| ID| Error Message | 5827| ------- | ------------------------------ | 5828| 401 | Parameter error. | 5829 5830**Example** 5831 5832```ts 5833import { socket } from '@kit.NetworkKit'; 5834import { BusinessError } from '@kit.BasicServicesKit'; 5835 5836let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 5837let messageView = ''; 5838tls.on('message', (value: socket.SocketMessageInfo) => { 5839 for (let i: number = 0; i < value.message.byteLength; i++) { 5840 let uint8Array = new Uint8Array(value.message) 5841 let messages = uint8Array[i] 5842 let message = String.fromCharCode(messages); 5843 messageView += message; 5844 } 5845 console.log('on message message: ' + JSON.stringify(messageView)); 5846 console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo)); 5847}); 5848``` 5849 5850### off('message')<sup>9+</sup> 5851 5852off(type: 'message', callback?: Callback\<SocketMessageInfo\>): void 5853 5854Unsubscribes from **message** events of a **TLSSocket** object. This API uses an asynchronous callback to return the result. 5855 5856**System capability**: SystemCapability.Communication.NetStack 5857 5858**Parameters** 5859 5860| Name | Type | Mandatory| Description | 5861| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 5862| type | string | Yes | Event type.<br/> **message**: message receiving event.| 5863| callback | Callback\<[SocketMessageInfo](#socketmessageinfo11)\> | No | Callback used to return the result. | 5864 5865**Error codes** 5866 5867| ID| Error Message | 5868| ------- | ------------------------------ | 5869| 401 | Parameter error. | 5870 5871**Example** 5872 5873```ts 5874import { socket } from '@kit.NetworkKit'; 5875import { BusinessError } from '@kit.BasicServicesKit'; 5876 5877let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 5878let messageView = ''; 5879let callback = (value: socket.SocketMessageInfo) => { 5880 for (let i: number = 0; i < value.message.byteLength; i++) { 5881 let uint8Array = new Uint8Array(value.message) 5882 let messages = uint8Array[i] 5883 let message = String.fromCharCode(messages); 5884 messageView += message; 5885 } 5886 console.log('on message message: ' + JSON.stringify(messageView)); 5887 console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo)); 5888} 5889tls.on('message', callback); 5890// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 5891tls.off('message', callback); 5892``` 5893### on('connect' | 'close')<sup>9+</sup> 5894 5895on(type: 'connect' | 'close', callback: Callback\<void\>): void 5896 5897Subscribes to **connect** or **close** events of the TLS socket connection. This API uses an asynchronous callback to return the result. 5898 5899**System capability**: SystemCapability.Communication.NetStack 5900 5901**Parameters** 5902 5903| Name | Type | Mandatory| Description | 5904| -------- | ---------------- | ---- | ------------------------------------------------------------ | 5905| type | string | Yes | Event type.<br>- **connect**: connection event.<br>- **close**: close event.| 5906| callback | Callback\<void\> | Yes | Callback used to return the result. | 5907 5908**Error codes** 5909 5910| ID| Error Message | 5911| ------- | ------------------------------ | 5912| 401 | Parameter error. | 5913 5914**Example** 5915 5916```ts 5917import { socket } from '@kit.NetworkKit'; 5918import { BusinessError } from '@kit.BasicServicesKit'; 5919 5920let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 5921tls.on('connect', () => { 5922 console.log("on connect success") 5923}); 5924tls.on('close', () => { 5925 console.log("on close success") 5926}); 5927``` 5928 5929### off('connect' | 'close')<sup>9+</sup> 5930 5931off(type: 'connect' | 'close', callback?: Callback\<void\>): void 5932 5933Unsubscribes from **connect** or **close** events of a **TLSSocket** object. This API uses an asynchronous callback to return the result. 5934 5935**System capability**: SystemCapability.Communication.NetStack 5936 5937**Parameters** 5938 5939| Name | Type | Mandatory| Description | 5940| -------- | ---------------- | ---- | ------------------------------------------------------------ | 5941| type | string | Yes | Event type.<br>- **connect**: connection event.<br>- **close**: close event.| 5942| callback | Callback\<void\> | No | Callback used to return the result. | 5943 5944**Error codes** 5945 5946| ID| Error Message | 5947| ------- | ------------------------------ | 5948| 401 | Parameter error. | 5949 5950**Example** 5951 5952```ts 5953import { socket } from '@kit.NetworkKit'; 5954import { BusinessError } from '@kit.BasicServicesKit'; 5955 5956let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 5957let callback1 = () => { 5958 console.log("on connect success"); 5959} 5960tls.on('connect', callback1); 5961// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 5962tls.off('connect', callback1); 5963tls.off('connect'); 5964let callback2 = () => { 5965 console.log("on close success"); 5966} 5967tls.on('close', callback2); 5968// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 5969tls.off('close', callback2); 5970``` 5971 5972### on('error')<sup>9+</sup> 5973 5974on(type: 'error', callback: ErrorCallback): void 5975 5976Subscribes to **error** events of the TLS socket connection. This API uses an asynchronous callback to return the result. 5977 5978**System capability**: SystemCapability.Communication.NetStack 5979 5980**Parameters** 5981 5982| Name | Type | Mandatory| Description | 5983| -------- | ------------- | ---- | ------------------------------------ | 5984| type | string | Yes | Event type.<br/> **error**: error event.| 5985| callback | ErrorCallback | Yes | Callback used to return the result. | 5986 5987**Error codes** 5988 5989| ID| Error Message | 5990| ------- | ------------------------------ | 5991| 401 | Parameter error. | 5992 5993**Example** 5994 5995```ts 5996import { socket } from '@kit.NetworkKit'; 5997import { BusinessError } from '@kit.BasicServicesKit'; 5998 5999let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 6000tls.on('error', (err: BusinessError) => { 6001 console.log("on error, err:" + JSON.stringify(err)) 6002}); 6003``` 6004 6005### off('error')<sup>9+</sup> 6006 6007off(type: 'error', callback?: ErrorCallback): void 6008 6009Unsubscribes from **error** events of a **TLSSocket** object. This API uses an asynchronous callback to return the result. 6010 6011**System capability**: SystemCapability.Communication.NetStack 6012 6013**Parameters** 6014 6015| Name | Type | Mandatory| Description | 6016| -------- | ------------- | ---- | ------------------------------------ | 6017| type | string | Yes | Event type.<br/> **error**: error event.| 6018| callback | ErrorCallback | No | Callback used to return the result. | 6019 6020**Error codes** 6021 6022| ID| Error Message | 6023| ------- | ------------------------------ | 6024| 401 | Parameter error. | 6025 6026**Example** 6027 6028```ts 6029import { socket } from '@kit.NetworkKit'; 6030import { BusinessError } from '@kit.BasicServicesKit'; 6031 6032let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 6033let callback = (err: BusinessError) => { 6034 console.log("on error, err:" + JSON.stringify(err)); 6035} 6036tls.on('error', callback); 6037// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 6038tls.off('error', callback); 6039``` 6040 6041### connect<sup>9+</sup> 6042 6043connect(options: TLSConnectOptions, callback: AsyncCallback\<void\>): void 6044 6045Sets up a TLS socket connection, and creates and initializes a TLS session after **bind** is successfully called. 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. Note that **ca** in **secureOptions** of the **options** parameter is mandatory. You need to enter the CA certificate of the server for certificate authentication. The certificate content starts with "-----BEGIN CERTIFICATE-----" and ends with "-----END CERTIFICATE-----". 6046 6047**System capability**: SystemCapability.Communication.NetStack 6048 6049**Parameters** 6050 6051| Name | Type | Mandatory| Description| 6052| -------- | ---------------------------------------| ----| --------------- | 6053| options | [TLSConnectOptions](#tlsconnectoptions9) | Yes | Parameters required for the TLS socket connection.| 6054| 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.| 6055 6056**Error codes** 6057 6058| ID| Error Message | 6059| ------- | -------------------------------------------- | 6060| 401 | Parameter error. | 6061| 2303104 | Interrupted system call. | 6062| 2303109 | Bad file number. | 6063| 2303111 | Resource temporarily unavailable. Try again. | 6064| 2303188 | Socket operation on non-socket. | 6065| 2303191 | Incorrect socket protocol type. | 6066| 2303198 | Address already in use. | 6067| 2303199 | Cannot assign requested address. | 6068| 2303210 | Connection timed out. | 6069| 2303501 | SSL is null. | 6070| 2303502 | An error occurred when reading data on the TLS socket.| 6071| 2303503 | An error occurred when writing data on the TLS socket.| 6072| 2303505 | An error occurred in the TLS system call. | 6073| 2303506 | Failed to close the TLS connection. | 6074| 2300002 | System internal error. | 6075 6076**Example** 6077 6078```ts 6079import { socket } from '@kit.NetworkKit'; 6080import { BusinessError } from '@kit.BasicServicesKit'; 6081 6082let tlsTwoWay: socket.TLSSocket = socket.constructTLSSocketInstance(); // Two way authentication 6083let bindAddr: socket.NetAddress = { 6084 address: '0.0.0.0', 6085} 6086tlsTwoWay.bind(bindAddr, (err: BusinessError) => { 6087 if (err) { 6088 console.log('bind fail'); 6089 return; 6090 } 6091 console.log('bind success'); 6092}); 6093let twoWayNetAddr: socket.NetAddress = { 6094 address: '192.168.xx.xxx', 6095 port: 8080 6096} 6097let twoWaySecureOptions: socket.TLSSecureOptions = { 6098 key: "xxxx", 6099 cert: "xxxx", 6100 ca: ["xxxx"], 6101 password: "xxxx", 6102 protocols: socket.Protocol.TLSv12, 6103 useRemoteCipherPrefer: true, 6104 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 6105 cipherSuite: "AES256-SHA256" 6106} 6107let tlsConnectOptions: socket.TLSConnectOptions = { 6108 address: twoWayNetAddr, 6109 secureOptions: twoWaySecureOptions, 6110 ALPNProtocols: ["spdy/1", "http/1.1"] 6111} 6112 6113tlsTwoWay.connect(tlsConnectOptions, (err: BusinessError) => { 6114 console.error("connect callback error" + err); 6115}); 6116 6117let tlsOneWay: socket.TLSSocket = socket.constructTLSSocketInstance(); // One way authentication 6118tlsOneWay.bind(bindAddr, (err: BusinessError) => { 6119 if (err) { 6120 console.log('bind fail'); 6121 return; 6122 } 6123 console.log('bind success'); 6124}); 6125let oneWayNetAddr: socket.NetAddress = { 6126 address: '192.168.xx.xxx', 6127 port: 8080 6128} 6129let oneWaySecureOptions: socket.TLSSecureOptions = { 6130 ca: ["xxxx", "xxxx"], 6131 cipherSuite: "AES256-SHA256" 6132} 6133let tlsOneWayConnectOptions: socket.TLSConnectOptions = { 6134 address: oneWayNetAddr, 6135 secureOptions: oneWaySecureOptions 6136} 6137tlsOneWay.connect(tlsOneWayConnectOptions, (err: BusinessError) => { 6138 console.error("connect callback error" + err); 6139}); 6140``` 6141 6142### connect<sup>9+</sup> 6143 6144connect(options: TLSConnectOptions): Promise\<void\> 6145 6146Sets up a TLS socket connection, and creates and initializes a TLS session after **bind** is successfully called. 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. Note that **ca** in **secureOptions** of the **options** parameter is mandatory. You need to enter the CA certificate of the server for certificate authentication. The certificate content starts with "-----BEGIN CERTIFICATE-----" and ends with "-----END CERTIFICATE-----". 6147 6148**System capability**: SystemCapability.Communication.NetStack 6149 6150**Parameters** 6151 6152| Name | Type | Mandatory| Description| 6153| -------- | --------------------------------------| ----| --------------- | 6154| options | [TLSConnectOptions](#tlsconnectoptions9) | Yes | Parameters required for the connection.| 6155 6156**Return value** 6157 6158| Type | Description | 6159| ------------------------------------------- | ----------------------------- | 6160| 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.| 6161 6162**Error codes** 6163 6164| ID| Error Message | 6165| ------- | -------------------------------------------- | 6166| 401 | Parameter error. | 6167| 2303104 | Interrupted system call. | 6168| 2303109 | Bad file number. | 6169| 2303111 | Resource temporarily unavailable. Try again. | 6170| 2303188 | Socket operation on non-socket. | 6171| 2303191 | Incorrect socket protocol type. | 6172| 2303198 | Address already in use. | 6173| 2303199 | Cannot assign requested address. | 6174| 2303210 | Connection timed out. | 6175| 2303501 | SSL is null. | 6176| 2303502 | An error occurred when reading data on the TLS socket.| 6177| 2303503 | An error occurred when writing data on the TLS socket.| 6178| 2303505 | An error occurred in the TLS system call. | 6179| 2303506 | Failed to close the TLS connection. | 6180| 2300002 | System internal error. | 6181 6182**Example** 6183 6184```ts 6185import { socket } from '@kit.NetworkKit'; 6186import { BusinessError } from '@kit.BasicServicesKit'; 6187 6188let tlsTwoWay: socket.TLSSocket = socket.constructTLSSocketInstance(); // Two way authentication 6189let bindAddr: socket.NetAddress = { 6190 address: '0.0.0.0', 6191} 6192tlsTwoWay.bind(bindAddr, (err: BusinessError) => { 6193 if (err) { 6194 console.log('bind fail'); 6195 return; 6196 } 6197 console.log('bind success'); 6198}); 6199let twoWayNetAddr: socket.NetAddress = { 6200 address: '192.168.xx.xxx', 6201 port: 8080 6202} 6203let twoWaySecureOptions: socket.TLSSecureOptions = { 6204 key: "xxxx", 6205 cert: "xxxx", 6206 ca: ["xxxx"], 6207 password: "xxxx", 6208 protocols: socket.Protocol.TLSv12, 6209 useRemoteCipherPrefer: true, 6210 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 6211 cipherSuite: "AES256-SHA256" 6212} 6213let tlsConnectOptions: socket.TLSConnectOptions = { 6214 address: twoWayNetAddr, 6215 secureOptions: twoWaySecureOptions, 6216 ALPNProtocols: ["spdy/1", "http/1.1"] 6217} 6218 6219tlsTwoWay.connect(tlsConnectOptions).then(() => { 6220 console.log("connect successfully"); 6221}).catch((err: BusinessError) => { 6222 console.log("connect failed " + JSON.stringify(err)); 6223}); 6224 6225let tlsOneWay: socket.TLSSocket = socket.constructTLSSocketInstance(); // One way authentication 6226tlsOneWay.bind(bindAddr, (err: BusinessError) => { 6227 if (err) { 6228 console.log('bind fail'); 6229 return; 6230 } 6231 console.log('bind success'); 6232}); 6233let oneWayNetAddr: socket.NetAddress = { 6234 address: '192.168.xx.xxx', 6235 port: 8080 6236} 6237let oneWaySecureOptions: socket.TLSSecureOptions = { 6238 ca: ["xxxx", "xxxx"], 6239 cipherSuite: "AES256-SHA256" 6240} 6241let tlsOneWayConnectOptions: socket.TLSConnectOptions = { 6242 address: oneWayNetAddr, 6243 secureOptions: oneWaySecureOptions 6244} 6245tlsOneWay.connect(tlsOneWayConnectOptions).then(() => { 6246 console.log("connect successfully"); 6247}).catch((err: BusinessError) => { 6248 console.log("connect failed " + JSON.stringify(err)); 6249}); 6250``` 6251 6252### getRemoteAddress<sup>9+</sup> 6253 6254getRemoteAddress(callback: AsyncCallback\<NetAddress\>): void 6255 6256Obtains the remote address of a TLS socket connection. This API uses an asynchronous callback to return the result. 6257 6258**System capability**: SystemCapability.Communication.NetStack 6259 6260**Parameters** 6261 6262| Name | Type | Mandatory| Description | 6263| -------- | ------------------------------------------------- | ---- | ---------- | 6264| 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.| 6265 6266**Error codes** 6267 6268| ID| Error Message | 6269| ------- | ----------------------------- | 6270| 2303188 | Socket operation on non-socket.| 6271| 2300002 | System internal error. | 6272 6273**Example** 6274 6275```ts 6276import { socket } from '@kit.NetworkKit'; 6277import { BusinessError } from '@kit.BasicServicesKit'; 6278 6279let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 6280tls.getRemoteAddress((err: BusinessError, data: socket.NetAddress) => { 6281 if (err) { 6282 console.log('getRemoteAddress fail'); 6283 return; 6284 } 6285 console.log('getRemoteAddress success:' + JSON.stringify(data)); 6286}); 6287``` 6288 6289### getRemoteAddress<sup>9+</sup> 6290 6291getRemoteAddress(): Promise\<NetAddress\> 6292 6293Obtains the remote address of a TLS socket connection. This API uses a promise to return the result. 6294 6295**System capability**: SystemCapability.Communication.NetStack 6296 6297**Return value** 6298 6299| Type | Description | 6300| ------------------------------------------ | ------------------------------------------ | 6301| Promise\<[NetAddress](#netaddress)\> | Promise used to return the result. If the operation fails, an error message is returned.| 6302 6303**Error codes** 6304 6305| ID| Error Message | 6306| ------- | ------------------------------ | 6307| 2303188 | Socket operation on non-socket.| 6308| 2300002 | System internal error. | 6309 6310**Example** 6311 6312```ts 6313import { socket } from '@kit.NetworkKit'; 6314import { BusinessError } from '@kit.BasicServicesKit'; 6315 6316let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 6317tls.getRemoteAddress().then(() => { 6318 console.log('getRemoteAddress success'); 6319}).catch((err: BusinessError) => { 6320 console.log('getRemoteAddress fail'); 6321}); 6322``` 6323 6324### getCertificate<sup>9+</sup> 6325 6326getCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)\>): void 6327 6328Obtains the local digital certificate after a TLS socket connection is established. This API is applicable to two-way authentication. It uses an asynchronous callback to return the result. 6329 6330**System capability**: SystemCapability.Communication.NetStack 6331 6332**Parameters** 6333 6334| Name | Type | Mandatory| Description| 6335| -------- | ----------------------------------------| ---- | ---------------| 6336| 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.| 6337 6338**Error codes** 6339 6340| ID| Error Message | 6341| ------- | ------------------------------ | 6342| 2303501 | SSL is null. | 6343| 2303504 | An error occurred when verifying the X.509 certificate.| 6344| 2300002 | System internal error. | 6345 6346**Example** 6347 6348```ts 6349import { socket } from '@kit.NetworkKit'; 6350import { BusinessError } from '@kit.BasicServicesKit'; 6351 6352let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 6353tls.getCertificate((err: BusinessError, data: socket.X509CertRawData) => { 6354 if (err) { 6355 console.log("getCertificate callback error = " + err); 6356 } else { 6357 console.log("getCertificate callback = " + data); 6358 } 6359}); 6360``` 6361 6362### getCertificate<sup>9+</sup> 6363 6364getCertificate():Promise\<[X509CertRawData](#x509certrawdata9)\> 6365 6366Obtains the local digital certificate after a TLS socket connection is established. This API is applicable to two-way authentication. It uses a promise to return the result. 6367 6368**System capability**: SystemCapability.Communication.NetStack 6369 6370**Return value** 6371 6372| Type | Description | 6373| -------------- | -------------------- | 6374| Promise\<[X509CertRawData](#x509certrawdata9)\> | Promise used to return the result. If the operation fails, an error message is returned.| 6375 6376**Error codes** 6377 6378| ID| Error Message | 6379| ------- | ------------------------------ | 6380| 2303501 | SSL is null. | 6381| 2303504 | An error occurred when verifying the X.509 certificate.| 6382| 2300002 | System internal error. | 6383 6384**Example** 6385 6386```ts 6387import { socket } from '@kit.NetworkKit'; 6388import { BusinessError } from '@kit.BasicServicesKit'; 6389import { util } from '@kit.ArkTS'; 6390 6391let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 6392tls.getCertificate().then((data: socket.X509CertRawData) => { 6393 const decoder = util.TextDecoder.create(); 6394 const str = decoder.decodeWithStream(data.data); 6395 console.log("getCertificate: " + str); 6396}).catch((err: BusinessError) => { 6397 console.error("failed" + err); 6398}); 6399``` 6400 6401### getRemoteCertificate<sup>9+</sup> 6402 6403getRemoteCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)\>): void 6404 6405Obtains the digital certificate of the server after a TLS socket connection is established. This API uses an asynchronous callback to return the result. 6406 6407**System capability**: SystemCapability.Communication.NetStack 6408 6409**Parameters** 6410 6411| Name | Type | Mandatory | Description | 6412| -------- | ----------------------------------------| ---- | ---------------| 6413| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| 6414 6415**Error codes** 6416 6417| ID| Error Message | 6418| ------- | ------------------------------ | 6419| 2303501 | SSL is null. | 6420| 2300002 | System internal error. | 6421 6422**Example** 6423 6424```ts 6425import { socket } from '@kit.NetworkKit'; 6426import { BusinessError } from '@kit.BasicServicesKit'; 6427import { util } from '@kit.ArkTS'; 6428 6429let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 6430tls.getRemoteCertificate((err: BusinessError, data: socket.X509CertRawData) => { 6431 if (err) { 6432 console.log("getRemoteCertificate callback error = " + err); 6433 } else { 6434 const decoder = util.TextDecoder.create(); 6435 const str = decoder.decodeWithStream(data.data); 6436 console.log("getRemoteCertificate callback = " + str); 6437 } 6438}); 6439``` 6440 6441### getRemoteCertificate<sup>9+</sup> 6442 6443getRemoteCertificate():Promise\<[X509CertRawData](#x509certrawdata9)\> 6444 6445Obtains the digital certificate of the server after a TLS socket connection is established. This API uses a promise to return the result. 6446 6447**System capability**: SystemCapability.Communication.NetStack 6448 6449**Return value** 6450 6451| Type | Description | 6452| -------------- | -------------------- | 6453| Promise\<[X509CertRawData](#x509certrawdata9)\> | Promise used to return the result. If the operation fails, an error message is returned.| 6454 6455**Error codes** 6456 6457| ID| Error Message | 6458| ------- | ------------------------------ | 6459| 2303501 | SSL is null. | 6460| 2300002 | System internal error. | 6461 6462**Example** 6463 6464```ts 6465import { socket } from '@kit.NetworkKit'; 6466import { BusinessError } from '@kit.BasicServicesKit'; 6467import { util } from '@kit.ArkTS'; 6468 6469let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 6470tls.getRemoteCertificate().then((data: socket.X509CertRawData) => { 6471 const decoder = util.TextDecoder.create(); 6472 const str = decoder.decodeWithStream(data.data); 6473 console.log("getRemoteCertificate:" + str); 6474}).catch((err: BusinessError) => { 6475 console.error("failed" + err); 6476}); 6477``` 6478 6479### getProtocol<sup>9+</sup> 6480 6481getProtocol(callback: AsyncCallback\<string\>): void 6482 6483Obtains the communication protocol version after a TLS socket connection is established. This API uses an asynchronous callback to return the result. 6484 6485**System capability**: SystemCapability.Communication.NetStack 6486 6487**Parameters** 6488 6489| Name | Type | Mandatory| Description | 6490| -------- | ----------------------------------------| ---- | ---------------| 6491| callback | AsyncCallback\<string\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| 6492 6493**Error codes** 6494 6495| ID| Error Message | 6496| ------- | ----------------------------- | 6497| 2303501 | SSL is null. | 6498| 2303505 | An error occurred in the TLS system call. | 6499| 2300002 | System internal error. | 6500 6501**Example** 6502 6503```ts 6504import { socket } from '@kit.NetworkKit'; 6505import { BusinessError } from '@kit.BasicServicesKit'; 6506 6507let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 6508tls.getProtocol((err: BusinessError, data: string) => { 6509 if (err) { 6510 console.log("getProtocol callback error = " + err); 6511 } else { 6512 console.log("getProtocol callback = " + data); 6513 } 6514}); 6515``` 6516 6517### getProtocol<sup>9+</sup> 6518 6519getProtocol():Promise\<string\> 6520 6521Obtains the communication protocol version after a TLS socket connection is established. This API uses a promise to return the result. 6522 6523**System capability**: SystemCapability.Communication.NetStack 6524 6525**Return value** 6526 6527| Type | Description | 6528| -------------- | -------------------- | 6529| Promise\<string\> | Promise used to return the result. If the operation fails, an error message is returned.| 6530 6531**Error codes** 6532 6533| ID| Error Message | 6534| ------- | ------------------------------ | 6535| 2303501 | SSL is null. | 6536| 2303505 | An error occurred in the TLS system call. | 6537| 2300002 | System internal error. | 6538 6539**Example** 6540 6541```ts 6542import { socket } from '@kit.NetworkKit'; 6543import { BusinessError } from '@kit.BasicServicesKit'; 6544 6545let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 6546tls.getProtocol().then((data: string) => { 6547 console.log(data); 6548}).catch((err: BusinessError) => { 6549 console.error("failed" + err); 6550}); 6551``` 6552 6553### getCipherSuite<sup>9+</sup> 6554 6555getCipherSuite(callback: AsyncCallback\<Array\<string\>\>): void 6556 6557Obtains the cipher suite negotiated by both communication parties after a TLS socket connection is established. This API uses an asynchronous callback to return the result. 6558 6559**System capability**: SystemCapability.Communication.NetStack 6560 6561**Parameters** 6562 6563| Name | Type | Mandatory| Description| 6564| -------- | ----------------------------------------| ---- | ---------------| 6565| callback | AsyncCallback\<Array\<string\>\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| 6566 6567**Error codes** 6568 6569| ID| Error Message | 6570| ------- | ------------------------------ | 6571| 2303501 | SSL is null. | 6572| 2303502 | An error occurred when reading data on the TLS socket.| 6573| 2303505 | An error occurred in the TLS system call. | 6574| 2300002 | System internal error. | 6575 6576**Example** 6577 6578```ts 6579import { socket } from '@kit.NetworkKit'; 6580import { BusinessError } from '@kit.BasicServicesKit'; 6581 6582let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 6583tls.getCipherSuite((err: BusinessError, data: Array<string>) => { 6584 if (err) { 6585 console.log("getCipherSuite callback error = " + err); 6586 } else { 6587 console.log("getCipherSuite callback = " + data); 6588 } 6589}); 6590``` 6591 6592### getCipherSuite<sup>9+</sup> 6593 6594getCipherSuite(): Promise\<Array\<string\>\> 6595 6596Obtains the cipher suite negotiated by both communication parties after a TLS socket connection is established. This API uses a promise to return the result. 6597 6598**System capability**: SystemCapability.Communication.NetStack 6599 6600**Return value** 6601 6602| Type | Description | 6603| ---------------------- | --------------------- | 6604| Promise\<Array\<string\>\> | Promise used to return the result. If the operation fails, an error message is returned.| 6605 6606**Error codes** 6607 6608| ID| Error Message | 6609| ------- | ------------------------------ | 6610| 2303501 | SSL is null. | 6611| 2303502 | An error occurred when reading data on the TLS socket.| 6612| 2303505 | An error occurred in the TLS system call. | 6613| 2300002 | System internal error. | 6614 6615**Example** 6616 6617```ts 6618import { socket } from '@kit.NetworkKit'; 6619import { BusinessError } from '@kit.BasicServicesKit'; 6620 6621let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 6622tls.getCipherSuite().then((data: Array<string>) => { 6623 console.log('getCipherSuite success:' + JSON.stringify(data)); 6624}).catch((err: BusinessError) => { 6625 console.error("failed" + err); 6626}); 6627``` 6628 6629### getSignatureAlgorithms<sup>9+</sup> 6630 6631getSignatureAlgorithms(callback: AsyncCallback\<Array\<string\>\>): void 6632 6633Obtains the signing algorithm negotiated by both communication parties after a TLS socket connection is established. This API is applicable to two-way authentication. It uses an asynchronous callback to return the result. 6634 6635**System capability**: SystemCapability.Communication.NetStack 6636 6637**Parameters** 6638 6639| Name | Type | Mandatory| Description | 6640| -------- | -------------------------------------| ---- | ---------------| 6641| callback | AsyncCallback\<Array\<string\>\> | Yes | Callback used to return the result. | 6642 6643**Error codes** 6644 6645| ID| Error Message | 6646| ------- | ------------------------------ | 6647| 2303501 | SSL is null. | 6648| 2300002 | System internal error. | 6649 6650**Example** 6651 6652```ts 6653import { socket } from '@kit.NetworkKit'; 6654import { BusinessError } from '@kit.BasicServicesKit'; 6655 6656let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 6657tls.getSignatureAlgorithms((err: BusinessError, data: Array<string>) => { 6658 if (err) { 6659 console.log("getSignatureAlgorithms callback error = " + err); 6660 } else { 6661 console.log("getSignatureAlgorithms callback = " + data); 6662 } 6663}); 6664``` 6665 6666### getSignatureAlgorithms<sup>9+</sup> 6667 6668getSignatureAlgorithms(): Promise\<Array\<string\>\> 6669 6670Obtains the signing algorithm negotiated by both communication parties after a TLS socket connection is established. This API is applicable to two-way authentication. It uses a promise to return the result. 6671 6672**System capability**: SystemCapability.Communication.NetStack 6673 6674**Return value** 6675 6676| Type | Description | 6677| ---------------------- | -------------------- | 6678| Promise\<Array\<string\>\> | Promise used to return the result.| 6679 6680**Error codes** 6681 6682| ID| Error Message | 6683| ------- | ------------------------------ | 6684| 2303501 | SSL is null. | 6685| 2300002 | System internal error. | 6686 6687**Example** 6688 6689```ts 6690import { socket } from '@kit.NetworkKit'; 6691import { BusinessError } from '@kit.BasicServicesKit'; 6692 6693let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 6694tls.getSignatureAlgorithms().then((data: Array<string>) => { 6695 console.log("getSignatureAlgorithms success" + data); 6696}).catch((err: BusinessError) => { 6697 console.error("failed" + err); 6698}); 6699``` 6700 6701### getLocalAddress<sup>12+</sup> 6702 6703getLocalAddress(): Promise\<NetAddress\> 6704 6705Obtains the local socket address of a **TLSSocket** connection. This API uses a promise to return the result. 6706 6707> **NOTE** 6708> Call this API only after the **TLSSocketServer** connection is successfully established. 6709 6710**System capability**: SystemCapability.Communication.NetStack 6711 6712**Return value** 6713 6714| Type | Description | 6715| -------------- | --------------------------------------------------- | 6716| Promise\<[NetAddress](#netaddress)\> | Promise used to return the result.| 6717 6718**Error codes** 6719 6720| ID| Error Message | 6721| -------- | ------------------------------------------- | 6722| 2300002 | System internal error. | 6723| 2301009 | Bad file descriptor. | 6724| 2303188 | Socket operation on non-socket. | 6725 6726**Example** 6727 6728```ts 6729import { socket } from '@kit.NetworkKit'; 6730import { BusinessError } from '@kit.BasicServicesKit'; 6731 6732let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 6733tls.getLocalAddress().then((localAddress: socket.NetAddress) => { 6734 console.info("Get success: " + JSON.stringify(localAddress)); 6735}).catch((err: BusinessError) => { 6736 console.error("Get failed, error: " + JSON.stringify(err)); 6737}) 6738``` 6739 6740### send<sup>9+</sup> 6741 6742send(data: string \| ArrayBuffer, callback: AsyncCallback\<void\>): void 6743 6744Sends a message to the server after a TLS socket connection is established. This API uses an asynchronous callback to return the result. 6745 6746**System capability**: SystemCapability.Communication.NetStack 6747 6748**Parameters** 6749 6750| Name | Type | Mandatory| Description | 6751| -------- | -----------------------------| ---- | ---------------| 6752| data | string \| ArrayBuffer | Yes | Data content of the message to send. | 6753| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| 6754 6755**Error codes** 6756 6757| ID| Error Message | 6758| ------- | -------------------------------------------- | 6759| 401 | Parameter error. | 6760| 2303501 | SSL is null. | 6761| 2303503 | An error occurred when writing data on the TLS socket.| 6762| 2303505 | An error occurred in the TLS system call. | 6763| 2303506 | Failed to close the TLS connection. | 6764| 2300002 | System internal error. | 6765 6766**Example** 6767 6768```ts 6769import { socket } from '@kit.NetworkKit'; 6770import { BusinessError } from '@kit.BasicServicesKit'; 6771 6772let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 6773tls.send("xxxx", (err: BusinessError) => { 6774 if (err) { 6775 console.log("send callback error = " + err); 6776 } else { 6777 console.log("send success"); 6778 } 6779}); 6780``` 6781 6782### send<sup>9+</sup> 6783 6784send(data: string \| ArrayBuffer): Promise\<void\> 6785 6786Sends a message to the server after a TLS socket connection is established. This API uses a promise to return the result. 6787 6788**System capability**: SystemCapability.Communication.NetStack 6789 6790**Parameters** 6791 6792| Name | Type | Mandatory| Description | 6793| -------- | -----------------------------| ---- | ---------------| 6794| data | string \| ArrayBuffer | Yes | Data content of the message to send. | 6795 6796**Error codes** 6797 6798| ID| Error Message | 6799| ------- | -------------------------------------------- | 6800| 401 | Parameter error. | 6801| 2303501 | SSL is null. | 6802| 2303503 | An error occurred when writing data on the TLS socket.| 6803| 2303505 | An error occurred in the TLS system call. | 6804| 2303506 | Failed to close the TLS connection. | 6805| 2300002 | System internal error. | 6806 6807**Return value** 6808 6809| Type | Description | 6810| -------------- | -------------------- | 6811| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.| 6812 6813**Example** 6814 6815```ts 6816import { socket } from '@kit.NetworkKit'; 6817import { BusinessError } from '@kit.BasicServicesKit'; 6818 6819let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 6820tls.send("xxxx").then(() => { 6821 console.log("send success"); 6822}).catch((err: BusinessError) => { 6823 console.error("failed" + err); 6824}); 6825``` 6826 6827### close<sup>9+</sup> 6828 6829close(callback: AsyncCallback\<void\>): void 6830 6831Closes a TLS socket connection. This API uses an asynchronous callback to return the result. 6832 6833**System capability**: SystemCapability.Communication.NetStack 6834 6835**Parameters** 6836 6837| Name | Type | Mandatory| Description | 6838| -------- | -----------------------------| ---- | ---------------| 6839| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| 6840 6841**Error codes** 6842 6843| ID| Error Message | 6844| ------- | -------------------------------------------- | 6845| 401 | Parameter error. | 6846| 2303501 | SSL is null. | 6847| 2303505 | An error occurred in the TLS system call. | 6848| 2303506 | Failed to close the TLS connection. | 6849| 2300002 | System internal error. | 6850 6851**Example** 6852 6853```ts 6854import { socket } from '@kit.NetworkKit'; 6855import { BusinessError } from '@kit.BasicServicesKit'; 6856 6857let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 6858tls.close((err: BusinessError) => { 6859 if (err) { 6860 console.log("close callback error = " + err); 6861 } else { 6862 console.log("close success"); 6863 } 6864}); 6865``` 6866 6867### close<sup>9+</sup> 6868 6869close(): Promise\<void\> 6870 6871Closes a TLS socket connection. This API uses a promise to return the result. 6872 6873**System capability**: SystemCapability.Communication.NetStack 6874 6875**Return value** 6876 6877| Type | Description | 6878| -------------- | -------------------- | 6879| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.| 6880 6881**Error codes** 6882 6883| ID| Error Message | 6884| ------- | -------------------------------------------- | 6885| 401 | Parameter error. | 6886| 2303501 | SSL is null. | 6887| 2303505 | An error occurred in the TLS system call. | 6888| 2303506 | Failed to close the TLS connection. | 6889| 2300002 | System internal error. | 6890 6891**Example** 6892 6893```ts 6894import { socket } from '@kit.NetworkKit'; 6895import { BusinessError } from '@kit.BasicServicesKit'; 6896 6897let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 6898tls.close().then(() => { 6899 console.log("close success"); 6900}).catch((err: BusinessError) => { 6901 console.error("failed" + err); 6902}); 6903``` 6904 6905## TLSConnectOptions<sup>9+</sup> 6906 6907Defines TLS connection options. 6908 6909**System capability**: SystemCapability.Communication.NetStack 6910 6911| Name | Type | Mandatory| Description | 6912| -------------- | ------------------------------------- | --- |-------------- | 6913| address | [NetAddress](#netaddress) | Yes | Gateway address. | 6914| secureOptions | [TLSSecureOptions](#tlssecureoptions9) | Yes| TLS security options.| 6915| ALPNProtocols | Array\<string\> | No| ALPN protocol. The value range is ["spdy/1", "http/1.1"]. The default value is **[]**. | 6916| skipRemoteValidation<sup>12+</sup> | boolean | No| Whether to perform certificate authentication on the server. The default value is **false**. | 6917 6918## TLSSecureOptions<sup>9+</sup> 6919 6920TLS security options. 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. 6921 6922**System capability**: SystemCapability.Communication.NetStack 6923 6924| Name | Type | Mandatory| Description | 6925| --------------------- | ------------------------------------------------------ | --- |----------------------------------- | 6926| ca | string \| Array\<string\> | No| CA certificate of the server, which is used to authenticate the digital certificate of the server. The default value is the preset CA certificate<sup>12+</sup>.| 6927| cert | string | No| Digital certificate of the local client. | 6928| key | string | No| Private key of the local digital certificate. | 6929| password | string | No| Password for reading the private key. | 6930| protocols | [Protocol](#protocol9) \|Array\<[Protocol](#protocol9)\> | No| TLS protocol version. The default value is **TLSv1.2**. | 6931| useRemoteCipherPrefer | boolean | No| Whether to use the remote cipher suite preferentially. | 6932| signatureAlgorithms | string | No| Signing algorithm used during communication. The default value is **""**. | 6933| cipherSuite | string | No| Cipher suite used during communication. The default value is **""**. | 6934 6935## Protocol<sup>9+</sup> 6936 6937Enumerates TLS protocol versions. 6938 6939**System capability**: SystemCapability.Communication.NetStack 6940 6941| Name | Value | Description | 6942| --------- | --------- |------------------ | 6943| TLSv12 | "TLSv1.2" | TLSv1.2.| 6944| TLSv13 | "TLSv1.3" | TLSv1.3.| 6945 6946## X509CertRawData<sup>9+</sup> 6947 6948Defines the certificate raw data. 6949 6950**System capability**: SystemCapability.Communication.NetStack 6951 6952## socket.constructTLSSocketServerInstance<sup>10+</sup> 6953 6954constructTLSSocketServerInstance(): TLSSocketServer 6955 6956Creates a **TLSSocketServer** object. 6957 6958**System capability**: SystemCapability.Communication.NetStack 6959 6960**Return value** 6961 6962| Type | Description | 6963| ------------------------------------ | ---------------------------- | 6964| [TLSSocketServer](#tlssocketserver10) | **TLSSocketServer** object.| 6965 6966**Example** 6967 6968```ts 6969import { socket } from '@kit.NetworkKit'; 6970import { BusinessError } from '@kit.BasicServicesKit'; 6971 6972let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 6973``` 6974 6975## TLSSocketServer<sup>10+</sup> 6976 6977Defines a TLS socket server connection. Before calling TLSSocketServer APIs, you need to call [socket.constructTLSSocketServerInstance](#socketconstructtlssocketserverinstance10) to create a **TLSSocketServer** object. 6978 6979### listen<sup>10+</sup> 6980 6981listen(options: TLSConnectOptions, callback: AsyncCallback\<void\>): void 6982 6983Listens to client connections after **bind** is successfully called. This API uses an asynchronous callback to return the result. After a connection is established, a TLS session will be created and initialized and a certificate key will be loaded and verified. 6984 6985**NOTE**<br>If the IP address is set to **0.0.0.0**, listening works for all IP addresses of the local host. 6986 6987**Required permissions**: ohos.permission.INTERNET 6988 6989**System capability**: SystemCapability.Communication.NetStack 6990 6991**Parameters** 6992 6993| Name | Type | Mandatory| Description | 6994| -------- | ---------------------------------------- | ---- | ------------------------------------------------ | 6995| options | [TLSConnectOptions](#tlsconnectoptions9) | Yes | Parameters required for the connection. | 6996| 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.| 6997 6998**Error codes** 6999 7000| ID| Error Message | 7001| -------- | ------------------------------------------- | 7002| 401 | Parameter error. | 7003| 201 | Permission denied. | 7004| 2300002 | System internal error. | 7005| 2303109 | Bad file number. | 7006| 2303111 | Resource temporarily unavailable. Try again.| 7007| 2303198 | Address already in use. | 7008| 2303199 | Cannot assign requested address. | 7009| 2303501 | SSL is null. | 7010| 2303502 | An error occurred when reading data on the TLS socket.| 7011| 2303503 | An error occurred when writing data on the TLS socket.| 7012| 2303505 | An error occurred in the TLS system call. | 7013| 2303506 | Failed to close the TLS connection. | 7014 7015**Example** 7016 7017```ts 7018import { socket } from '@kit.NetworkKit'; 7019import { BusinessError } from '@kit.BasicServicesKit'; 7020 7021let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 7022let netAddress: socket.NetAddress = { 7023 address: '192.168.xx.xxx', 7024 port: 8080 7025} 7026let tlsSecureOptions: socket.TLSSecureOptions = { 7027 key: "xxxx", 7028 cert: "xxxx", 7029 ca: ["xxxx"], 7030 password: "xxxx", 7031 protocols: socket.Protocol.TLSv12, 7032 useRemoteCipherPrefer: true, 7033 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 7034 cipherSuite: "AES256-SHA256" 7035} 7036let tlsConnectOptions: socket.TLSConnectOptions = { 7037 address: netAddress, 7038 secureOptions: tlsSecureOptions, 7039 ALPNProtocols: ["spdy/1", "http/1.1"], 7040 skipRemoteValidation: false 7041} 7042tlsServer.listen(tlsConnectOptions, (err: BusinessError) => { 7043 console.log("listen callback error" + err); 7044}); 7045``` 7046 7047### listen<sup>10+</sup> 7048 7049listen(options: TLSConnectOptions): Promise\<void\> 7050 7051Listens to client connections after **bind** is successfully called. This API uses a promise to return the result. After a connection is established, a TLS session will be created and initialized and a certificate key will be loaded and verified. 7052 7053**Required permissions**: ohos.permission.INTERNET 7054 7055**System capability**: SystemCapability.Communication.NetStack 7056 7057**Parameters** 7058 7059| Name | Type | Mandatory| Description | 7060| ------- | ---------------------------------------- | ---- | ------------------ | 7061| options | [TLSConnectOptions](#tlsconnectoptions9) | Yes | Parameters required for the connection.| 7062 7063**Return value** 7064 7065| Type | Description | 7066| --------------- | --------------------------------------------------------- | 7067| 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.| 7068 7069**Error codes** 7070 7071| ID| Error Message | 7072| -------- | ------------------------------------------- | 7073| 401 | Parameter error. | 7074| 201 | Permission denied. | 7075| 2300002 | System internal error. | 7076| 2303109 | Bad file number. | 7077| 2303111 | Resource temporarily unavailable. Try again.| 7078| 2303198 | Address already in use. | 7079| 2303199 | Cannot assign requested address. | 7080| 2303501 | SSL is null. | 7081| 2303502 | An error occurred when reading data on the TLS socket.| 7082| 2303503 | An error occurred when writing data on the TLS socket.| 7083| 2303505 | An error occurred in the TLS system call. | 7084| 2303506 | Failed to close the TLS connection. | 7085 7086**Example** 7087 7088```ts 7089import { socket } from '@kit.NetworkKit'; 7090import { BusinessError } from '@kit.BasicServicesKit'; 7091 7092let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 7093let netAddress: socket.NetAddress = { 7094 address: '192.168.xx.xxx', 7095 port: 8080 7096} 7097let tlsSecureOptions: socket.TLSSecureOptions = { 7098 key: "xxxx", 7099 cert: "xxxx", 7100 ca: ["xxxx"], 7101 password: "xxxx", 7102 protocols: socket.Protocol.TLSv12, 7103 useRemoteCipherPrefer: true, 7104 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 7105 cipherSuite: "AES256-SHA256" 7106} 7107let tlsConnectOptions: socket.TLSConnectOptions = { 7108 address: netAddress, 7109 secureOptions: tlsSecureOptions, 7110 ALPNProtocols: ["spdy/1", "http/1.1"], 7111 skipRemoteValidation: false 7112} 7113tlsServer.listen(tlsConnectOptions).then(() => { 7114 console.log("listen callback success"); 7115}).catch((err: BusinessError) => { 7116 console.log("failed: " + JSON.stringify(err)); 7117}); 7118``` 7119 7120### getState<sup>10+</sup> 7121 7122getState(callback: AsyncCallback\<SocketStateBase\>): void 7123 7124Obtains the status of the TLS socket server connection upon successful listening. This API uses an asynchronous callback to return the result. 7125 7126> **NOTE** 7127> This API can be called only after **listen** is successfully called. 7128 7129**System capability**: SystemCapability.Communication.NetStack 7130 7131**Parameters** 7132 7133| Name | Type | Mandatory| Description | 7134| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | 7135| callback | AsyncCallback\<[SocketStateBase](#socketstatebase)\> | Yes | Callback used to return the result. If the operation is successful, the status of the TLS socket server connection is returned. If the operation fails, an error message is returned.| 7136 7137**Error codes** 7138 7139| ID| Error Message | 7140| -------- | ------------------------------- | 7141| 401 | Parameter error. | 7142| 2303188 | Socket operation on non-socket. | 7143| 2300002 | System internal error. | 7144 7145**Example** 7146 7147```ts 7148import { socket } from '@kit.NetworkKit'; 7149import { BusinessError } from '@kit.BasicServicesKit'; 7150 7151let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 7152let netAddress: socket.NetAddress = { 7153 address: '192.168.xx.xxx', 7154 port: 8080 7155} 7156let tlsSecureOptions: socket.TLSSecureOptions = { 7157 key: "xxxx", 7158 cert: "xxxx", 7159 ca: ["xxxx"], 7160 password: "xxxx", 7161 protocols: socket.Protocol.TLSv12, 7162 useRemoteCipherPrefer: true, 7163 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 7164 cipherSuite: "AES256-SHA256" 7165} 7166let tlsConnectOptions: socket.TLSConnectOptions = { 7167 address: netAddress, 7168 secureOptions: tlsSecureOptions, 7169 ALPNProtocols: ["spdy/1", "http/1.1"] 7170} 7171tlsServer.listen(tlsConnectOptions).then(() => { 7172 console.log("listen callback success"); 7173}).catch((err: BusinessError) => { 7174 console.log("failed: " + JSON.stringify(err)); 7175}); 7176tlsServer.getState((err: BusinessError, data: socket.SocketStateBase) => { 7177 if (err) { 7178 console.log('getState fail'); 7179 return; 7180 } 7181 console.log('getState success:' + JSON.stringify(data)); 7182}); 7183``` 7184 7185### getState<sup>10+</sup> 7186 7187getState(): Promise\<SocketStateBase\> 7188 7189Obtains the status of the TLS socket server connection upon successful listening. This API uses a promise to return the result. 7190 7191> **NOTE** 7192> This API can be called only after **listen** is successfully called. 7193 7194**System capability**: SystemCapability.Communication.NetStack 7195 7196**Return value** 7197 7198| Type | Description | 7199| --------------------------------------------- | ----------------------------------------------------------- | 7200| Promise\<[SocketStateBase](#socketstatebase)\> | Promise used to return the result. If the operation fails, an error message is returned.| 7201 7202**Error codes** 7203 7204| ID| Error Message | 7205| -------- | ------------------------------- | 7206| 2303188 | Socket operation on non-socket. | 7207| 2300002 | System internal error. | 7208 7209**Example** 7210 7211```ts 7212import { socket } from '@kit.NetworkKit'; 7213import { BusinessError } from '@kit.BasicServicesKit'; 7214 7215let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 7216let netAddress: socket.NetAddress = { 7217 address: '192.168.xx.xxx', 7218 port: 8080 7219} 7220let tlsSecureOptions: socket.TLSSecureOptions = { 7221 key: "xxxx", 7222 cert: "xxxx", 7223 ca: ["xxxx"], 7224 password: "xxxx", 7225 protocols: socket.Protocol.TLSv12, 7226 useRemoteCipherPrefer: true, 7227 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 7228 cipherSuite: "AES256-SHA256" 7229} 7230let tlsConnectOptions: socket.TLSConnectOptions = { 7231 address: netAddress, 7232 secureOptions: tlsSecureOptions, 7233 ALPNProtocols: ["spdy/1", "http/1.1"] 7234} 7235tlsServer.listen(tlsConnectOptions).then(() => { 7236 console.log("listen callback success"); 7237}).catch((err: BusinessError) => { 7238 console.log("failed: " + JSON.stringify(err)); 7239}); 7240tlsServer.getState().then(() => { 7241 console.log('getState success'); 7242}).catch((err: BusinessError) => { 7243 console.log('getState fail'); 7244}); 7245``` 7246 7247### setExtraOptions<sup>10+</sup> 7248 7249setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\<void\>): void 7250 7251Sets other properties of the TLS socket server connection upon successful listening. This API uses an asynchronous callback to return the result. 7252 7253> **NOTE** 7254> This API can be called only after **listen** is successfully called. 7255 7256**System capability**: SystemCapability.Communication.NetStack 7257 7258**Parameters** 7259 7260| Name | Type | Mandatory| Description | 7261| -------- | ------------------------------------ | ---- | ------------------------------------------------ | 7262| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TLS socket server connection. | 7263| 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.| 7264 7265**Error codes** 7266 7267| ID| Error Message | 7268| -------- | ------------------------------- | 7269| 401 | Parameter error. | 7270| 2303188 | Socket operation on non-socket. | 7271| 2300002 | System internal error. | 7272 7273**Example** 7274 7275```ts 7276import { socket } from '@kit.NetworkKit'; 7277import { BusinessError } from '@kit.BasicServicesKit'; 7278 7279let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 7280let netAddress: socket.NetAddress = { 7281 address: '192.168.xx.xxx', 7282 port: 8080 7283} 7284let tlsSecureOptions: socket.TLSSecureOptions = { 7285 key: "xxxx", 7286 cert: "xxxx", 7287 ca: ["xxxx"], 7288 password: "xxxx", 7289 protocols: socket.Protocol.TLSv12, 7290 useRemoteCipherPrefer: true, 7291 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 7292 cipherSuite: "AES256-SHA256" 7293} 7294let tlsConnectOptions: socket.TLSConnectOptions = { 7295 address: netAddress, 7296 secureOptions: tlsSecureOptions, 7297 ALPNProtocols: ["spdy/1", "http/1.1"] 7298} 7299tlsServer.listen(tlsConnectOptions).then(() => { 7300 console.log("listen callback success"); 7301}).catch((err: BusinessError) => { 7302 console.log("failed: " + JSON.stringify(err)); 7303}); 7304 7305interface SocketLinger { 7306 on: boolean; 7307 linger: number; 7308} 7309 7310let tcpExtraOptions: socket.TCPExtraOptions = { 7311 keepAlive: true, 7312 OOBInline: true, 7313 TCPNoDelay: true, 7314 socketLinger: { on: true, linger: 10 } as SocketLinger, 7315 receiveBufferSize: 1000, 7316 sendBufferSize: 1000, 7317 reuseAddress: true, 7318 socketTimeout: 3000 7319} 7320tlsServer.setExtraOptions(tcpExtraOptions, (err: BusinessError) => { 7321 if (err) { 7322 console.log('setExtraOptions fail'); 7323 return; 7324 } 7325 console.log('setExtraOptions success'); 7326}); 7327``` 7328 7329### setExtraOptions<sup>10+</sup> 7330 7331setExtraOptions(options: TCPExtraOptions): Promise\<void\> 7332 7333Sets other properties of the TLS socket server connection upon successful listening. This API uses a promise to return the result. 7334 7335> **NOTE** 7336> This API can be called only after **listen** is successfully called. 7337 7338**System capability**: SystemCapability.Communication.NetStack 7339 7340**Parameters** 7341 7342| Name | Type | Mandatory| Description | 7343| ------- | ------------------------------------ | ---- | ------------------------------- | 7344| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TLS socket server connection.| 7345 7346**Return value** 7347 7348| Type | Description | 7349| -------------- | -------------------------------------------------------- | 7350| 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.| 7351 7352**Error codes** 7353 7354| ID| Error Message | 7355| -------- | ------------------------------- | 7356| 401 | Parameter error. | 7357| 2303188 | Socket operation on non-socket. | 7358| 2300002 | System internal error. | 7359 7360**Example** 7361 7362```ts 7363import { socket } from '@kit.NetworkKit'; 7364import { BusinessError } from '@kit.BasicServicesKit'; 7365 7366let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 7367let netAddress: socket.NetAddress = { 7368 address: '192.168.xx.xxx', 7369 port: 8080 7370} 7371let tlsSecureOptions: socket.TLSSecureOptions = { 7372 key: "xxxx", 7373 cert: "xxxx", 7374 ca: ["xxxx"], 7375 password: "xxxx", 7376 protocols: socket.Protocol.TLSv12, 7377 useRemoteCipherPrefer: true, 7378 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 7379 cipherSuite: "AES256-SHA256" 7380} 7381let tlsConnectOptions: socket.TLSConnectOptions = { 7382 address: netAddress, 7383 secureOptions: tlsSecureOptions, 7384 ALPNProtocols: ["spdy/1", "http/1.1"] 7385} 7386tlsServer.listen(tlsConnectOptions).then(() => { 7387 console.log("listen callback success"); 7388}).catch((err: BusinessError) => { 7389 console.log("failed: " + JSON.stringify(err)); 7390}); 7391 7392interface SocketLinger { 7393 on: boolean; 7394 linger: number; 7395} 7396 7397let tcpExtraOptions: socket.TCPExtraOptions = { 7398 keepAlive: true, 7399 OOBInline: true, 7400 TCPNoDelay: true, 7401 socketLinger: { on: true, linger: 10 } as SocketLinger, 7402 receiveBufferSize: 1000, 7403 sendBufferSize: 1000, 7404 reuseAddress: true, 7405 socketTimeout: 3000 7406} 7407tlsServer.setExtraOptions(tcpExtraOptions).then(() => { 7408 console.log('setExtraOptions success'); 7409}).catch((err: BusinessError) => { 7410 console.log('setExtraOptions fail'); 7411}); 7412``` 7413 7414### getCertificate<sup>10+</sup> 7415 7416getCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)\>): void 7417 7418Obtains the local digital certificate after a TLS socket server connection is established. This API uses an asynchronous callback to return the result. 7419 7420> **NOTE** 7421> This API can be called only after **listen** is successfully called. 7422 7423**System capability**: SystemCapability.Communication.NetStack 7424 7425**Parameters** 7426 7427| Name | Type | Mandatory| Description | 7428| -------- | ----------------------------------------------------- | ---- | -------------------------------------------------------- | 7429| 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.| 7430 7431**Error codes** 7432 7433| ID| Error Message | 7434| -------- | ---------------------- | 7435| 401 | Parameter error. | 7436| 2303501 | SSL is null. | 7437| 2303504 | An error occurred when verifying the X.509 certificate. | 7438| 2300002 | System internal error. | 7439 7440**Example** 7441 7442```ts 7443import { socket } from '@kit.NetworkKit'; 7444import { BusinessError } from '@kit.BasicServicesKit'; 7445import { util } from '@kit.ArkTS'; 7446 7447let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 7448let netAddress: socket.NetAddress = { 7449 address: '192.168.xx.xxx', 7450 port: 8080 7451} 7452let tlsSecureOptions: socket.TLSSecureOptions = { 7453 key: "xxxx", 7454 cert: "xxxx", 7455 ca: ["xxxx"], 7456 password: "xxxx", 7457 protocols: socket.Protocol.TLSv12, 7458 useRemoteCipherPrefer: true, 7459 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 7460 cipherSuite: "AES256-SHA256" 7461} 7462let tlsConnectOptions: socket.TLSConnectOptions = { 7463 address: netAddress, 7464 secureOptions: tlsSecureOptions, 7465 ALPNProtocols: ["spdy/1", "http/1.1"] 7466} 7467tlsServer.listen(tlsConnectOptions).then(() => { 7468 console.log("listen callback success"); 7469}).catch((err: BusinessError) => { 7470 console.log("failed: " + JSON.stringify(err)); 7471}); 7472tlsServer.getCertificate((err: BusinessError, data: socket.X509CertRawData) => { 7473 if (err) { 7474 console.log("getCertificate callback error = " + err); 7475 } else { 7476 const decoder = util.TextDecoder.create(); 7477 const str = decoder.decodeWithStream(data.data); 7478 console.log("getCertificate callback: " + str); 7479 } 7480}); 7481``` 7482 7483### getCertificate<sup>10+</sup> 7484 7485getCertificate():Promise\<[X509CertRawData](#x509certrawdata9)\> 7486 7487Obtains the local digital certificate after a TLS socket server connection is established. This API uses a promise to return the result. 7488 7489> **NOTE** 7490> This API can be called only after **listen** is successfully called. 7491 7492**System capability**: SystemCapability.Communication.NetStack 7493 7494**Return value** 7495 7496| Type | Description | 7497| ----------------------------------------------- | ------------------------------------------------------------ | 7498| Promise\<[X509CertRawData](#x509certrawdata9)\> | Promise used to return the result. If the operation fails, an error message is returned.| 7499 7500**Error codes** 7501 7502| ID| Error Message | 7503| -------- | ---------------------- | 7504| 2303501 | SSL is null. | 7505| 2303504 | An error occurred when verifying the X.509 certificate. | 7506| 2300002 | System internal error. | 7507 7508**Example** 7509 7510```ts 7511import { socket } from '@kit.NetworkKit'; 7512import { BusinessError } from '@kit.BasicServicesKit'; 7513import { util } from '@kit.ArkTS'; 7514 7515let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 7516let netAddress: socket.NetAddress = { 7517 address: '192.168.xx.xxx', 7518 port: 8080 7519} 7520let tlsSecureOptions: socket.TLSSecureOptions = { 7521 key: "xxxx", 7522 cert: "xxxx", 7523 ca: ["xxxx"], 7524 password: "xxxx", 7525 protocols: socket.Protocol.TLSv12, 7526 useRemoteCipherPrefer: true, 7527 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 7528 cipherSuite: "AES256-SHA256" 7529} 7530let tlsConnectOptions: socket.TLSConnectOptions = { 7531 address: netAddress, 7532 secureOptions: tlsSecureOptions, 7533 ALPNProtocols: ["spdy/1", "http/1.1"] 7534} 7535tlsServer.listen(tlsConnectOptions).then(() => { 7536 console.log("listen callback success"); 7537}).catch((err: BusinessError) => { 7538 console.log("failed: " + JSON.stringify(err)); 7539}); 7540tlsServer.getCertificate().then((data: socket.X509CertRawData) => { 7541 const decoder = util.TextDecoder.create(); 7542 const str = decoder.decodeWithStream(data.data); 7543 console.log("getCertificate: " + str); 7544}).catch((err: BusinessError) => { 7545 console.error("failed" + err); 7546}); 7547``` 7548 7549### getProtocol<sup>10+</sup> 7550 7551getProtocol(callback: AsyncCallback\<string\>): void 7552 7553Obtains the communication protocol version after a TLS socket server connection is established. This API uses an asynchronous callback to return the result. 7554 7555> **NOTE** 7556> This API can be called only after **listen** is successfully called. 7557 7558**System capability**: SystemCapability.Communication.NetStack 7559 7560**Parameters** 7561 7562| Name | Type | Mandatory| Description | 7563| -------- | ----------------------- | ---- | ---------------------------------------------------- | 7564| callback | AsyncCallback\<string\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| 7565 7566**Error codes** 7567 7568| ID| Error Message | 7569| -------- | -------------------------------------- | 7570| 401 | Parameter error. | 7571| 2303501 | SSL is null. | 7572| 2303505 | An error occurred in the TLS system call. | 7573| 2300002 | System internal error. | 7574 7575**Example** 7576 7577```ts 7578import { socket } from '@kit.NetworkKit'; 7579import { BusinessError } from '@kit.BasicServicesKit'; 7580 7581let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 7582let netAddress: socket.NetAddress = { 7583 address: '192.168.xx.xxx', 7584 port: 8080 7585} 7586let tlsSecureOptions: socket.TLSSecureOptions = { 7587 key: "xxxx", 7588 cert: "xxxx", 7589 ca: ["xxxx"], 7590 password: "xxxx", 7591 protocols: socket.Protocol.TLSv12, 7592 useRemoteCipherPrefer: true, 7593 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 7594 cipherSuite: "AES256-SHA256" 7595} 7596let tlsConnectOptions: socket.TLSConnectOptions = { 7597 address: netAddress, 7598 secureOptions: tlsSecureOptions, 7599 ALPNProtocols: ["spdy/1", "http/1.1"] 7600} 7601tlsServer.listen(tlsConnectOptions).then(() => { 7602 console.log("listen callback success"); 7603}).catch((err: BusinessError) => { 7604 console.log("failed: " + JSON.stringify(err)); 7605}); 7606tlsServer.getProtocol((err: BusinessError, data: string) => { 7607 if (err) { 7608 console.log("getProtocol callback error = " + err); 7609 } else { 7610 console.log("getProtocol callback = " + data); 7611 } 7612}); 7613``` 7614 7615### getProtocol<sup>10+</sup> 7616 7617getProtocol():Promise\<string\> 7618 7619Obtains the communication protocol version after a TLS socket server connection is established. This API uses a promise to return the result. 7620 7621> **NOTE** 7622> This API can be called only after **listen** is successfully called. 7623 7624**System capability**: SystemCapability.Communication.NetStack 7625 7626**Return value** 7627 7628| Type | Description | 7629| ----------------- | ------------------------------------------------------- | 7630| Promise\<string\> | Promise used to return the result. If the operation fails, an error message is returned.| 7631 7632**Error codes** 7633 7634| ID| Error Message | 7635| -------- | -------------------------------------- | 7636| 2303501 | SSL is null. | 7637| 2303505 | An error occurred in the TLS system call. | 7638| 2300002 | System internal error. | 7639 7640**Example** 7641 7642```ts 7643import { socket } from '@kit.NetworkKit'; 7644import { BusinessError } from '@kit.BasicServicesKit'; 7645 7646let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 7647let netAddress: socket.NetAddress = { 7648 address: '192.168.xx.xxx', 7649 port: 8080 7650} 7651let tlsSecureOptions: socket.TLSSecureOptions = { 7652 key: "xxxx", 7653 cert: "xxxx", 7654 ca: ["xxxx"], 7655 password: "xxxx", 7656 protocols: socket.Protocol.TLSv12, 7657 useRemoteCipherPrefer: true, 7658 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 7659 cipherSuite: "AES256-SHA256" 7660} 7661let tlsConnectOptions: socket.TLSConnectOptions = { 7662 address: netAddress, 7663 secureOptions: tlsSecureOptions, 7664 ALPNProtocols: ["spdy/1", "http/1.1"] 7665} 7666tlsServer.listen(tlsConnectOptions).then(() => { 7667 console.log("listen callback success"); 7668}).catch((err: BusinessError) => { 7669 console.log("failed: " + JSON.stringify(err)); 7670}); 7671tlsServer.getProtocol().then((data: string) => { 7672 console.log(data); 7673}).catch((err: BusinessError) => { 7674 console.error("failed" + err); 7675}); 7676``` 7677 7678### getLocalAddress<sup>12+</sup> 7679 7680getLocalAddress(): Promise\<NetAddress\> 7681 7682Obtains the local socket address of a **TLSSocketServer** connection. This API uses a promise to return the result. 7683 7684> **NOTE** 7685> Call this API only after the **TLSSocketServer** connection is successfully established. 7686 7687**System capability**: SystemCapability.Communication.NetStack 7688 7689**Return value** 7690 7691| Type | Description | 7692| -------------- | --------------------------------------------------- | 7693| Promise\<[NetAddress](#netaddress)\> | Promise used to return the result.| 7694 7695**Error codes** 7696 7697| ID| Error Message | 7698| -------- | ------------------------------------------- | 7699| 2300002 | System internal error. | 7700| 2301009 | Bad file descriptor. | 7701| 2303188 | Socket operation on non-socket. | 7702 7703**Example** 7704 7705```ts 7706import { socket } from '@kit.NetworkKit'; 7707import { BusinessError } from '@kit.BasicServicesKit'; 7708 7709let tlsServer: socket.TLSSocket = socket.constructTLSSocketServerInstance(); 7710tlsServer.getLocalAddress().then((localAddress: socket.NetAddress) => { 7711 console.info("Get success: " + JSON.stringify(localAddress)); 7712}).catch((err: BusinessError) => { 7713 console.error("Get failed, error: " + JSON.stringify(err)); 7714}) 7715``` 7716 7717### on('connect')<sup>10+</sup> 7718 7719on(type: 'connect', callback: Callback\<TLSSocketConnection\>): void 7720 7721Subscribes to TLS socket server connection events. This API uses an asynchronous callback to return the result. 7722 7723> **NOTE** 7724> This API can be called only after **listen** is successfully called. 7725 7726**System capability**: SystemCapability.Communication.NetStack 7727 7728**Parameters** 7729 7730| Name | Type | Mandatory| Description | 7731| -------- | ------------------------------------------------------- | ---- | ------------------------------------- | 7732| type | string | Yes | Event type.<br/> **connect**: connection event.| 7733| callback | Callback\<[TLSSocketConnection](#tlssocketconnection10)\> | Yes | Callback used to return the result. If the operation fails, an error message is returned. | 7734 7735**Error codes** 7736 7737| ID| Error Message | 7738| -------- | ---------------- | 7739| 401 | Parameter error. | 7740 7741**Example** 7742 7743```ts 7744import { socket } from '@kit.NetworkKit'; 7745import { BusinessError } from '@kit.BasicServicesKit'; 7746 7747let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 7748let netAddress: socket.NetAddress = { 7749 address: '192.168.xx.xxx', 7750 port: 8080 7751} 7752let tlsSecureOptions: socket.TLSSecureOptions = { 7753 key: "xxxx", 7754 cert: "xxxx", 7755 ca: ["xxxx"], 7756 password: "xxxx", 7757 protocols: socket.Protocol.TLSv12, 7758 useRemoteCipherPrefer: true, 7759 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 7760 cipherSuite: "AES256-SHA256" 7761} 7762let tlsConnectOptions: socket.TLSConnectOptions = { 7763 address: netAddress, 7764 secureOptions: tlsSecureOptions, 7765 ALPNProtocols: ["spdy/1", "http/1.1"] 7766} 7767tlsServer.listen(tlsConnectOptions).then(() => { 7768 console.log("listen callback success"); 7769}).catch((err: BusinessError) => { 7770 console.log("failed: " + JSON.stringify(err)); 7771}); 7772tlsServer.on('connect', (data: socket.TLSSocketConnection) => { 7773 console.log(JSON.stringify(data)) 7774}); 7775``` 7776 7777### off('connect')<sup>10+</sup> 7778 7779off(type: 'connect', callback?: Callback\<TLSSocketConnection\>): void 7780 7781Unsubscribes from **connect** events of a **TLSSocketServer** object. This API uses an asynchronous callback to return the result. 7782 7783> **NOTE** 7784> This API can be called only after **listen** is successfully called. 7785> You can pass the callback of the **on** function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 7786 7787**System capability**: SystemCapability.Communication.NetStack 7788 7789**Parameters** 7790 7791| Name | Type | Mandatory| Description | 7792| -------- | ------------------------------------------------------- | ---- | ------------------------------------- | 7793| type | string | Yes | Event type.<br/> **connect**: connection event.| 7794| callback | Callback\<[TLSSocketConnection](#tlssocketconnection10)\> | No | Callback used to return the result. If the operation fails, an error message is returned. | 7795 7796**Error codes** 7797 7798| ID| Error Message | 7799| -------- | ---------------- | 7800| 401 | Parameter error. | 7801 7802**Example** 7803 7804```ts 7805import { socket } from '@kit.NetworkKit'; 7806import { BusinessError } from '@kit.BasicServicesKit'; 7807 7808let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 7809let netAddress: socket.NetAddress = { 7810 address: '192.168.xx.xxx', 7811 port: 8080 7812} 7813let tlsSecureOptions: socket.TLSSecureOptions = { 7814 key: "xxxx", 7815 cert: "xxxx", 7816 ca: ["xxxx"], 7817 password: "xxxx", 7818 protocols: socket.Protocol.TLSv12, 7819 useRemoteCipherPrefer: true, 7820 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 7821 cipherSuite: "AES256-SHA256" 7822} 7823let tlsConnectOptions: socket.TLSConnectOptions = { 7824 address: netAddress, 7825 secureOptions: tlsSecureOptions, 7826 ALPNProtocols: ["spdy/1", "http/1.1"] 7827} 7828tlsServer.listen(tlsConnectOptions).then(() => { 7829 console.log("listen callback success"); 7830}).catch((err: BusinessError) => { 7831 console.log("failed: " + JSON.stringify(err)); 7832}); 7833 7834let callback = (data: socket.TLSSocketConnection) => { 7835 console.log('on connect message: ' + JSON.stringify(data)); 7836} 7837tlsServer.on('connect', callback); 7838// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 7839tlsServer.off('connect', callback); 7840tlsServer.off('connect'); 7841``` 7842 7843### on('error')<sup>10+</sup> 7844 7845on(type: 'error', callback: ErrorCallback): void 7846 7847Subscribes to **error** events of a **TLSSocketServer** object. This API uses an asynchronous callback to return the result. 7848 7849> **NOTE** 7850> This API can be called only after **listen** is successfully called. 7851 7852**System capability**: SystemCapability.Communication.NetStack 7853 7854**Parameters** 7855 7856| Name | Type | Mandatory| Description | 7857| -------- | ------------- | ---- | ------------------------------------ | 7858| type | string | Yes | Event type.<br/> **error**: error event.| 7859| callback | ErrorCallback | Yes | Callback used to return the result. If the operation fails, an error message is returned. | 7860 7861**Error codes** 7862 7863| ID| Error Message | 7864| -------- | ---------------- | 7865| 401 | Parameter error. | 7866 7867**Example** 7868 7869```ts 7870import { socket } from '@kit.NetworkKit'; 7871import { BusinessError } from '@kit.BasicServicesKit'; 7872 7873let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 7874let netAddress: socket.NetAddress = { 7875 address: '192.168.xx.xxx', 7876 port: 8080 7877} 7878let tlsSecureOptions: socket.TLSSecureOptions = { 7879 key: "xxxx", 7880 cert: "xxxx", 7881 ca: ["xxxx"], 7882 password: "xxxx", 7883 protocols: socket.Protocol.TLSv12, 7884 useRemoteCipherPrefer: true, 7885 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 7886 cipherSuite: "AES256-SHA256" 7887} 7888let tlsConnectOptions: socket.TLSConnectOptions = { 7889 address: netAddress, 7890 secureOptions: tlsSecureOptions, 7891 ALPNProtocols: ["spdy/1", "http/1.1"] 7892} 7893tlsServer.listen(tlsConnectOptions).then(() => { 7894 console.log("listen callback success"); 7895}).catch((err: BusinessError) => { 7896 console.log("failed: " + JSON.stringify(err)); 7897}); 7898tlsServer.on('error', (err: BusinessError) => { 7899 console.log("on error, err:" + JSON.stringify(err)) 7900}); 7901``` 7902 7903### off('error')<sup>10+</sup> 7904 7905off(type: 'error', callback?: ErrorCallback): void 7906 7907Unsubscribes from **error** events of a **TLSSocketServer** object. This API uses an asynchronous callback to return the result. 7908 7909> **NOTE** 7910> This API can be called only after **listen** is successfully called. 7911> You can pass the callback of the **on** function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 7912 7913**System capability**: SystemCapability.Communication.NetStack 7914 7915**Parameters** 7916 7917| Name | Type | Mandatory| Description | 7918| -------- | ------------- | ---- | ------------------------------------ | 7919| type | string | Yes | Event type.<br/> **error**: error event.| 7920| callback | ErrorCallback | No | Callback used to return the result. If the operation fails, an error message is returned. | 7921 7922**Error codes** 7923 7924| ID| Error Message | 7925| -------- | ---------------- | 7926| 401 | Parameter error. | 7927 7928**Example** 7929 7930```ts 7931import { socket } from '@kit.NetworkKit'; 7932import { BusinessError } from '@kit.BasicServicesKit'; 7933 7934let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 7935let netAddress: socket.NetAddress = { 7936 address: '192.168.xx.xxx', 7937 port: 8080 7938} 7939let tlsSecureOptions: socket.TLSSecureOptions = { 7940 key: "xxxx", 7941 cert: "xxxx", 7942 ca: ["xxxx"], 7943 password: "xxxx", 7944 protocols: socket.Protocol.TLSv12, 7945 useRemoteCipherPrefer: true, 7946 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 7947 cipherSuite: "AES256-SHA256" 7948} 7949let tlsConnectOptions: socket.TLSConnectOptions = { 7950 address: netAddress, 7951 secureOptions: tlsSecureOptions, 7952 ALPNProtocols: ["spdy/1", "http/1.1"] 7953} 7954tlsServer.listen(tlsConnectOptions).then(() => { 7955 console.log("listen callback success"); 7956}).catch((err: BusinessError) => { 7957 console.log("failed: " + JSON.stringify(err)); 7958}); 7959 7960let callback = (err: BusinessError) => { 7961 console.log("on error, err:" + JSON.stringify(err)); 7962} 7963tlsServer.on('error', callback); 7964// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 7965tlsServer.off('error', callback); 7966tlsServer.off('error'); 7967``` 7968 7969## TLSSocketConnection<sup>10+</sup> 7970 7971Defines a **TLSSocketConnection** object, that is, the connection between the TLSSocket client and the server. Before calling TLSSocketConnection APIs, you need to obtain a **TLSSocketConnection** object. 7972 7973> **NOTE** 7974> The TLSSocket client can call related APIs through the **TLSSocketConnection** object only after a connection is successfully established between the TLSSocket client and the server. 7975 7976**System capability**: SystemCapability.Communication.NetStack 7977 7978### Attributes 7979 7980| Name | Type | Mandatory| Description | 7981| -------- | ------ | ---- | ------------------------------------- | 7982| clientId | number | Yes | ID of the connection between the client and TLSSocketServer.| 7983 7984### send<sup>10+</sup> 7985 7986send(data: string \| ArrayBuffer, callback: AsyncCallback\<void\>): void 7987 7988Sends a message to the client after a TLS socket server connection is established. This API uses an asynchronous callback to return the result. 7989 7990**System capability**: SystemCapability.Communication.NetStack 7991 7992**Parameters** 7993 7994| Name | Type | Mandatory| Description | 7995| -------- | --------------------- | ---- | ------------------------------------------------ | 7996| data | string \| ArrayBuffer | Yes | Parameters for sending data over a TLS socket server connection. | 7997| 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.| 7998 7999**Error codes** 8000 8001| ID| Error Message | 8002| -------- | -------------------------------------- | 8003| 401 | Parameter error. | 8004| 2303501 | SSL is null. | 8005| 2303503 | An error occurred when writing data on the TLS socket.| 8006| 2303505 | An error occurred in the TLS system call.| 8007| 2303506 | Failed to close the TLS connection. | 8008| 2300002 | System internal error. | 8009 8010**Example** 8011 8012```ts 8013import { socket } from '@kit.NetworkKit'; 8014import { BusinessError } from '@kit.BasicServicesKit'; 8015 8016let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 8017let netAddress: socket.NetAddress = { 8018 address: '192.168.xx.xxx', 8019 port: 8080 8020} 8021let tlsSecureOptions: socket.TLSSecureOptions = { 8022 key: "xxxx", 8023 cert: "xxxx", 8024 ca: ["xxxx"], 8025 password: "xxxx", 8026 protocols: socket.Protocol.TLSv12, 8027 useRemoteCipherPrefer: true, 8028 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 8029 cipherSuite: "AES256-SHA256" 8030} 8031let tlsConnectOptions: socket.TLSConnectOptions = { 8032 address: netAddress, 8033 secureOptions: tlsSecureOptions, 8034 ALPNProtocols: ["spdy/1", "http/1.1"] 8035} 8036tlsServer.listen(tlsConnectOptions).then(() => { 8037 console.log("listen callback success"); 8038}).catch((err: BusinessError) => { 8039 console.log("failed" + err); 8040}); 8041 8042tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 8043 client.send('Hello, client!', (err: BusinessError) => { 8044 if (err) { 8045 console.log('send fail'); 8046 return; 8047 } 8048 console.log('send success'); 8049 }); 8050}); 8051``` 8052 8053### send<sup>10+</sup> 8054 8055send(data: string \| ArrayBuffer): Promise\<void\> 8056 8057Sends a message to the server after a TLS socket server connection is established. This API uses a promise to return the result. 8058 8059**System capability**: SystemCapability.Communication.NetStack 8060 8061**Parameters** 8062 8063| Name| Type | Mandatory| Description | 8064| ------ | ------ | ---- | ------------------------------------- | 8065| data | string \| ArrayBuffer | Yes | Parameters for sending data over a TLS socket server connection.| 8066 8067**Return value** 8068 8069| Type | Description | 8070| --------------- | --------------------------------------------------------- | 8071| 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.| 8072 8073**Error codes** 8074 8075| ID| Error Message | 8076| -------- | -------------------------------------- | 8077| 401 | Parameter error. | 8078| 2303501 | SSL is null. | 8079| 2303503 | An error occurred when writing data on the TLS socket.| 8080| 2303505 | An error occurred in the TLS system call.| 8081| 2303506 | Failed to close the TLS connection. | 8082| 2300002 | System internal error. | 8083 8084**Example** 8085 8086```ts 8087import { socket } from '@kit.NetworkKit'; 8088import { BusinessError } from '@kit.BasicServicesKit'; 8089 8090let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 8091let netAddress: socket.NetAddress = { 8092 address: '192.168.xx.xxx', 8093 port: 8080 8094} 8095let tlsSecureOptions: socket.TLSSecureOptions = { 8096 key: "xxxx", 8097 cert: "xxxx", 8098 ca: ["xxxx"], 8099 password: "xxxx", 8100 protocols: socket.Protocol.TLSv12, 8101 useRemoteCipherPrefer: true, 8102 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 8103 cipherSuite: "AES256-SHA256" 8104} 8105let tlsConnectOptions: socket.TLSConnectOptions = { 8106 address: netAddress, 8107 secureOptions: tlsSecureOptions, 8108 ALPNProtocols: ["spdy/1", "http/1.1"] 8109} 8110tlsServer.listen(tlsConnectOptions).then(() => { 8111 console.log("listen callback success"); 8112}).catch((err: BusinessError) => { 8113 console.log("failed" + err); 8114}); 8115 8116tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 8117 client.send('Hello, client!').then(() => { 8118 console.log('send success'); 8119 }).catch((err: BusinessError) => { 8120 console.log('send fail'); 8121 }); 8122}); 8123``` 8124 8125### close<sup>10+</sup> 8126 8127close(callback: AsyncCallback\<void\>): void 8128 8129Closes a TLS socket server connection. This API uses an asynchronous callback to return the result. 8130 8131**System capability**: SystemCapability.Communication.NetStack 8132 8133**Parameters** 8134 8135| Name | Type | Mandatory| Description | 8136| -------- | --------------------- | ---- | ------------------------------------------------ | 8137| 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.| 8138 8139**Error codes** 8140 8141| ID| Error Message | 8142| -------- | -------------------------------------- | 8143| 401 | Parameter error. | 8144| 2303501 | SSL is null. | 8145| 2303505 | An error occurred in the TLS system call. | 8146| 2303506 | Failed to close the TLS connection. | 8147| 2300002 | System internal error. | 8148 8149**Example** 8150 8151```ts 8152import { socket } from '@kit.NetworkKit'; 8153import { BusinessError } from '@kit.BasicServicesKit'; 8154 8155let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 8156let netAddress: socket.NetAddress = { 8157 address: '192.168.xx.xxx', 8158 port: 8080 8159} 8160let tlsSecureOptions: socket.TLSSecureOptions = { 8161 key: "xxxx", 8162 cert: "xxxx", 8163 ca: ["xxxx"], 8164 password: "xxxx", 8165 protocols: socket.Protocol.TLSv12, 8166 useRemoteCipherPrefer: true, 8167 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 8168 cipherSuite: "AES256-SHA256" 8169} 8170let tlsConnectOptions: socket.TLSConnectOptions = { 8171 address: netAddress, 8172 secureOptions: tlsSecureOptions, 8173 ALPNProtocols: ["spdy/1", "http/1.1"] 8174} 8175tlsServer.listen(tlsConnectOptions).then(() => { 8176 console.log("listen callback success"); 8177}).catch((err: BusinessError) => { 8178 console.log("failed" + err); 8179}); 8180 8181tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 8182 client.close((err: BusinessError) => { 8183 if (err) { 8184 console.log('close fail'); 8185 return; 8186 } 8187 console.log('close success'); 8188 }); 8189}); 8190``` 8191 8192### close<sup>10+</sup> 8193 8194close(): Promise\<void\> 8195 8196Closes a TLS socket server connection. This API uses a promise to return the result. 8197 8198**System capability**: SystemCapability.Communication.NetStack 8199 8200**Return value** 8201 8202| Type | Description | 8203| --------------- | --------------------------------------------------------- | 8204| 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. If the operation fails, an error message is returned.| 8205 8206**Error codes** 8207 8208| ID| Error Message | 8209| -------- | -------------------------------------- | 8210| 2303501 | SSL is null. | 8211| 2303505 | An error occurred in the TLS system call. | 8212| 2303506 | Failed to close the TLS connection. | 8213| 2300002 | System internal error. | 8214 8215**Example** 8216 8217```ts 8218import { socket } from '@kit.NetworkKit'; 8219import { BusinessError } from '@kit.BasicServicesKit'; 8220 8221let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 8222let netAddress: socket.NetAddress = { 8223 address: '192.168.xx.xxx', 8224 port: 8080 8225} 8226let tlsSecureOptions: socket.TLSSecureOptions = { 8227 key: "xxxx", 8228 cert: "xxxx", 8229 ca: ["xxxx"], 8230 password: "xxxx", 8231 protocols: socket.Protocol.TLSv12, 8232 useRemoteCipherPrefer: true, 8233 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 8234 cipherSuite: "AES256-SHA256" 8235} 8236let tlsConnectOptions: socket.TLSConnectOptions = { 8237 address: netAddress, 8238 secureOptions: tlsSecureOptions, 8239 ALPNProtocols: ["spdy/1", "http/1.1"] 8240} 8241tlsServer.listen(tlsConnectOptions).then(() => { 8242 console.log("listen callback success"); 8243}).catch((err: BusinessError) => { 8244 console.log("failed" + err); 8245}); 8246tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 8247 client.close().then(() => { 8248 console.log('close success'); 8249 }).catch((err: BusinessError) => { 8250 console.log('close fail'); 8251 }); 8252}); 8253``` 8254 8255### getRemoteAddress<sup>10+</sup> 8256 8257getRemoteAddress(callback: AsyncCallback\<NetAddress\>): void 8258 8259Obtains the remote address of a TLS socket server connection. This API uses an asynchronous callback to return the result. 8260 8261**System capability**: SystemCapability.Communication.NetStack 8262 8263**Parameters** 8264 8265| Name | Type | Mandatory| Description | 8266| -------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | 8267| 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.| 8268 8269**Error codes** 8270 8271| ID| Error Message | 8272| -------- | ------------------------------- | 8273| 401 | Parameter error. | 8274| 2303188 | Socket operation on non-socket. | 8275| 2300002 | System internal error. | 8276 8277**Example** 8278 8279```ts 8280import { socket } from '@kit.NetworkKit'; 8281import { BusinessError } from '@kit.BasicServicesKit'; 8282 8283let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 8284let netAddress: socket.NetAddress = { 8285 address: '192.168.xx.xxx', 8286 port: 8080 8287} 8288let tlsSecureOptions: socket.TLSSecureOptions = { 8289 key: "xxxx", 8290 cert: "xxxx", 8291 ca: ["xxxx"], 8292 password: "xxxx", 8293 protocols: socket.Protocol.TLSv12, 8294 useRemoteCipherPrefer: true, 8295 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 8296 cipherSuite: "AES256-SHA256" 8297} 8298let tlsConnectOptions: socket.TLSConnectOptions = { 8299 address: netAddress, 8300 secureOptions: tlsSecureOptions, 8301 ALPNProtocols: ["spdy/1", "http/1.1"] 8302} 8303tlsServer.listen(tlsConnectOptions).then(() => { 8304 console.log("listen callback success"); 8305}).catch((err: BusinessError) => { 8306 console.log("failed" + err); 8307}); 8308tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 8309 client.getRemoteAddress((err: BusinessError, data: socket.NetAddress) => { 8310 if (err) { 8311 console.log('getRemoteAddress fail'); 8312 return; 8313 } 8314 console.log('getRemoteAddress success:' + JSON.stringify(data)); 8315 }); 8316}); 8317``` 8318 8319### getRemoteAddress<sup>10+</sup> 8320 8321getRemoteAddress(): Promise\<NetAddress\> 8322 8323Obtains the remote address of a TLS socket server connection. This API uses a promise to return the result. 8324 8325**System capability**: SystemCapability.Communication.NetStack 8326 8327**Return value** 8328 8329| Type | Description | 8330| ----------------------------------- | ----------------------------------------------------------- | 8331| Promise\<[NetAddress](#netaddress)\> | Promise used to return the result. If the operation fails, an error message is returned.| 8332 8333**Error codes** 8334 8335| ID| Error Message | 8336| -------- | ------------------------------- | 8337| 2303188 | Socket operation on non-socket. | 8338| 2300002 | System internal error. | 8339 8340**Example** 8341 8342```ts 8343import { socket } from '@kit.NetworkKit'; 8344import { BusinessError } from '@kit.BasicServicesKit'; 8345 8346let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 8347let netAddress: socket.NetAddress = { 8348 address: '192.168.xx.xxx', 8349 port: 8080 8350} 8351let tlsSecureOptions: socket.TLSSecureOptions = { 8352 key: "xxxx", 8353 cert: "xxxx", 8354 ca: ["xxxx"], 8355 password: "xxxx", 8356 protocols: socket.Protocol.TLSv12, 8357 useRemoteCipherPrefer: true, 8358 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 8359 cipherSuite: "AES256-SHA256" 8360} 8361let tlsConnectOptions: socket.TLSConnectOptions = { 8362 address: netAddress, 8363 secureOptions: tlsSecureOptions, 8364 ALPNProtocols: ["spdy/1", "http/1.1"] 8365} 8366tlsServer.listen(tlsConnectOptions).then(() => { 8367 console.log("listen callback success"); 8368}).catch((err: BusinessError) => { 8369 console.log("failed" + err); 8370}); 8371tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 8372 client.getRemoteAddress().then((data: socket.NetAddress) => { 8373 console.log('getRemoteAddress success:' + JSON.stringify(data)); 8374 }).catch((err: BusinessError) => { 8375 console.error("failed" + err); 8376 }); 8377}); 8378``` 8379 8380### getRemoteCertificate<sup>10+</sup> 8381 8382getRemoteCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)\>): void 8383 8384Obtains the digital certificate of the peer end after a TLS socket server connection is established. This API uses an asynchronous callback to return the result. It applies only to the scenario where the client sends a certificate to the server. 8385 8386**System capability**: SystemCapability.Communication.NetStack 8387 8388**Parameters** 8389 8390| Name | Type | Mandatory| Description | 8391| -------- | ----------------------------------------------------- | ---- | ---------------------------------------------------- | 8392| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| 8393 8394**Error codes** 8395 8396| ID| Error Message | 8397| -------- | ---------------------- | 8398| 401 | Parameter error. | 8399| 2303501 | SSL is null. | 8400| 2300002 | System internal error. | 8401 8402**Example** 8403 8404```ts 8405import { socket } from '@kit.NetworkKit'; 8406import { BusinessError } from '@kit.BasicServicesKit'; 8407import { util } from '@kit.ArkTS'; 8408 8409let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 8410let netAddress: socket.NetAddress = { 8411 address: '192.168.xx.xxx', 8412 port: 8080 8413} 8414let tlsSecureOptions: socket.TLSSecureOptions = { 8415 key: "xxxx", 8416 cert: "xxxx", 8417 ca: ["xxxx"], 8418 password: "xxxx", 8419 protocols: socket.Protocol.TLSv12, 8420 useRemoteCipherPrefer: true, 8421 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 8422 cipherSuite: "AES256-SHA256" 8423} 8424let tlsConnectOptions: socket.TLSConnectOptions = { 8425 address: netAddress, 8426 secureOptions: tlsSecureOptions, 8427 ALPNProtocols: ["spdy/1", "http/1.1"] 8428} 8429tlsServer.listen(tlsConnectOptions).then(() => { 8430 console.log("listen callback success"); 8431}).catch((err: BusinessError) => { 8432 console.log("failed" + err); 8433}); 8434tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 8435 client.getRemoteCertificate((err: BusinessError, data: socket.X509CertRawData) => { 8436 if (err) { 8437 console.log("getRemoteCertificate callback error: " + err); 8438 } else { 8439 const decoder = util.TextDecoder.create(); 8440 const str = decoder.decodeWithStream(data.data); 8441 console.log("getRemoteCertificate callback: " + str); 8442 } 8443 }); 8444}); 8445``` 8446 8447### getRemoteCertificate<sup>10+</sup> 8448 8449getRemoteCertificate():Promise\<[X509CertRawData](#x509certrawdata9)\> 8450 8451Obtains the digital certificate of the peer end after a TLS socket server connection is established. This API uses a promise to return the result. It applies only to the scenario where the client sends a certificate to the server. 8452 8453**System capability**: SystemCapability.Communication.NetStack 8454 8455**Return value** 8456 8457| Type | Description | 8458| ----------------------------------------------- | ------------------------------------------------------------ | 8459| Promise\<[X509CertRawData](#x509certrawdata9)\> | Promise used to return the result. If the operation fails, an error message is returned.| 8460 8461**Error codes** 8462 8463| ID| Error Message | 8464| -------- | ---------------------- | 8465| 2303501 | SSL is null. | 8466| 2300002 | System internal error. | 8467 8468**Example** 8469 8470```ts 8471import { socket } from '@kit.NetworkKit'; 8472import { BusinessError } from '@kit.BasicServicesKit'; 8473import { util } from '@kit.ArkTS'; 8474 8475let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 8476let netAddress: socket.NetAddress = { 8477 address: '192.168.xx.xxx', 8478 port: 8080 8479} 8480let tlsSecureOptions: socket.TLSSecureOptions = { 8481 key: "xxxx", 8482 cert: "xxxx", 8483 ca: ["xxxx"], 8484 password: "xxxx", 8485 protocols: socket.Protocol.TLSv12, 8486 useRemoteCipherPrefer: true, 8487 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 8488 cipherSuite: "AES256-SHA256" 8489} 8490let tlsConnectOptions: socket.TLSConnectOptions = { 8491 address: netAddress, 8492 secureOptions: tlsSecureOptions, 8493 ALPNProtocols: ["spdy/1", "http/1.1"] 8494} 8495tlsServer.listen(tlsConnectOptions).then(() => { 8496 console.log("listen callback success"); 8497}).catch((err: BusinessError) => { 8498 console.log("failed" + err); 8499}); 8500tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 8501 client.getRemoteCertificate().then((data: socket.X509CertRawData) => { 8502 const decoder = util.TextDecoder.create(); 8503 const str = decoder.decodeWithStream(data.data); 8504 console.log("getRemoteCertificate success: " + str); 8505 }).catch((err: BusinessError) => { 8506 console.error("failed" + err); 8507 }); 8508}); 8509``` 8510 8511### getCipherSuite<sup>10+</sup> 8512 8513getCipherSuite(callback: AsyncCallback\<Array\<string\>\>): void 8514 8515Obtains the cipher suite negotiated by both communication parties after a TLS socket server connection is established. This API uses an asynchronous callback to return the result. 8516 8517**System capability**: SystemCapability.Communication.NetStack 8518 8519**Parameters** 8520 8521| Name | Type | Mandatory| Description | 8522| -------- | -------------------------------- | ---- | ------------------------------------------------------------ | 8523| callback | AsyncCallback\<Array\<string\>\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| 8524 8525**Error codes** 8526 8527| ID| Error Message | 8528| -------- | -------------------------------------- | 8529| 401 | Parameter error. | 8530| 2303501 | SSL is null. | 8531| 2303502 | An error occurred when reading data on the TLS socket.| 8532| 2303505 | An error occurred in the TLS system call.| 8533| 2300002 | System internal error. | 8534 8535**Example** 8536 8537```ts 8538import { socket } from '@kit.NetworkKit'; 8539import { BusinessError } from '@kit.BasicServicesKit'; 8540 8541let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 8542let netAddress: socket.NetAddress = { 8543 address: '192.168.xx.xxx', 8544 port: 8080 8545} 8546let tlsSecureOptions: socket.TLSSecureOptions = { 8547 key: "xxxx", 8548 cert: "xxxx", 8549 ca: ["xxxx"], 8550 password: "xxxx", 8551 protocols: socket.Protocol.TLSv12, 8552 useRemoteCipherPrefer: true, 8553 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 8554 cipherSuite: "AES256-SHA256" 8555} 8556let tlsConnectOptions: socket.TLSConnectOptions = { 8557 address: netAddress, 8558 secureOptions: tlsSecureOptions, 8559 ALPNProtocols: ["spdy/1", "http/1.1"] 8560} 8561tlsServer.listen(tlsConnectOptions).then(() => { 8562 console.log("listen callback success"); 8563}).catch((err: BusinessError) => { 8564 console.log("failed" + err); 8565}); 8566tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 8567 client.getCipherSuite((err: BusinessError, data: Array<string>) => { 8568 if (err) { 8569 console.log("getCipherSuite callback error = " + err); 8570 } else { 8571 console.log("getCipherSuite callback = " + data); 8572 } 8573 }); 8574}); 8575``` 8576 8577### getCipherSuite<sup>10+</sup> 8578 8579getCipherSuite(): Promise\<Array\<string\>\> 8580 8581Obtains the cipher suite negotiated by both communication parties after a TLS socket server connection is established. This API uses a promise to return the result. 8582 8583**System capability**: SystemCapability.Communication.NetStack 8584 8585**Return value** 8586 8587| Type | Description | 8588| -------------------------- | ------------------------------------------------------------ | 8589| Promise\<Array\<string\>\> | Promise used to return the result. If the operation fails, an error message is returned.| 8590 8591**Error codes** 8592 8593| ID| Error Message | 8594| -------- | -------------------------------------- | 8595| 2303501 | SSL is null. | 8596| 2303502 | An error occurred when reading data on the TLS socket.| 8597| 2303505 | An error occurred in the TLS system call. | 8598| 2300002 | System internal error. | 8599 8600**Example** 8601 8602```ts 8603import { socket } from '@kit.NetworkKit'; 8604import { BusinessError } from '@kit.BasicServicesKit'; 8605 8606let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 8607let netAddress: socket.NetAddress = { 8608 address: '192.168.xx.xxx', 8609 port: 8080 8610} 8611let tlsSecureOptions: socket.TLSSecureOptions = { 8612 key: "xxxx", 8613 cert: "xxxx", 8614 ca: ["xxxx"], 8615 password: "xxxx", 8616 protocols: socket.Protocol.TLSv12, 8617 useRemoteCipherPrefer: true, 8618 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 8619 cipherSuite: "AES256-SHA256" 8620} 8621let tlsConnectOptions: socket.TLSConnectOptions = { 8622 address: netAddress, 8623 secureOptions: tlsSecureOptions, 8624 ALPNProtocols: ["spdy/1", "http/1.1"] 8625} 8626tlsServer.listen(tlsConnectOptions).then(() => { 8627 console.log("listen callback success"); 8628}).catch((err: BusinessError) => { 8629 console.log("failed" + err); 8630}); 8631tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 8632 client.getCipherSuite().then((data: Array<string>) => { 8633 console.log('getCipherSuite success:' + JSON.stringify(data)); 8634 }).catch((err: BusinessError) => { 8635 console.error("failed" + err); 8636 }); 8637}); 8638``` 8639 8640### getSignatureAlgorithms<sup>10+</sup> 8641 8642getSignatureAlgorithms(callback: AsyncCallback\<Array\<string\>\>): void 8643 8644Obtains the signing algorithm negotiated by both communication parties after a TLS socket server connection is established. This API uses an asynchronous callback to return the result. 8645 8646**System capability**: SystemCapability.Communication.NetStack 8647 8648**Parameters** 8649 8650| Name | Type | Mandatory| Description | 8651| -------- | -------------------------------- | ---- | ---------------------------------- | 8652| callback | AsyncCallback\<Array\<string\>\> | Yes | Callback used to return the result. | 8653 8654**Error codes** 8655 8656| ID| Error Message | 8657| -------- | ---------------------- | 8658| 401 | Parameter error. | 8659| 2303501 | SSL is null. | 8660| 2300002 | System internal error. | 8661 8662**Example** 8663 8664```ts 8665import { socket } from '@kit.NetworkKit'; 8666import { BusinessError } from '@kit.BasicServicesKit'; 8667 8668let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 8669let netAddress: socket.NetAddress = { 8670 address: '192.168.xx.xxx', 8671 port: 8080 8672} 8673let tlsSecureOptions: socket.TLSSecureOptions = { 8674 key: "xxxx", 8675 cert: "xxxx", 8676 ca: ["xxxx"], 8677 password: "xxxx", 8678 protocols: socket.Protocol.TLSv12, 8679 useRemoteCipherPrefer: true, 8680 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 8681 cipherSuite: "AES256-SHA256" 8682} 8683let tlsConnectOptions: socket.TLSConnectOptions = { 8684 address: netAddress, 8685 secureOptions: tlsSecureOptions, 8686 ALPNProtocols: ["spdy/1", "http/1.1"] 8687} 8688tlsServer.listen(tlsConnectOptions).then(() => { 8689 console.log("listen callback success"); 8690}).catch((err: BusinessError) => { 8691 console.log("failed" + err); 8692}); 8693tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 8694 client.getSignatureAlgorithms((err: BusinessError, data: Array<string>) => { 8695 if (err) { 8696 console.log("getSignatureAlgorithms callback error = " + err); 8697 } else { 8698 console.log("getSignatureAlgorithms callback = " + data); 8699 } 8700 }); 8701}); 8702``` 8703 8704### getSignatureAlgorithms<sup>10+</sup> 8705 8706getSignatureAlgorithms(): Promise\<Array\<string\>\> 8707 8708Obtains the signing algorithm negotiated by both communication parties after a TLS socket server connection is established. This API uses a promise to return the result. 8709 8710**System capability**: SystemCapability.Communication.NetStack 8711 8712**Return value** 8713 8714| Type | Description | 8715| -------------------------- | --------------------------------------------- | 8716| Promise\<Array\<string\>\> | Promise used to return the result.| 8717 8718**Error codes** 8719 8720| ID| Error Message | 8721| -------- | ---------------------- | 8722| 2303501 | SSL is null. | 8723| 2300002 | System internal error. | 8724 8725**Example** 8726 8727```ts 8728import { socket } from '@kit.NetworkKit'; 8729import { BusinessError } from '@kit.BasicServicesKit'; 8730 8731let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 8732let netAddress: socket.NetAddress = { 8733 address: '192.168.xx.xxx', 8734 port: 8080 8735} 8736let tlsSecureOptions: socket.TLSSecureOptions = { 8737 key: "xxxx", 8738 cert: "xxxx", 8739 ca: ["xxxx"], 8740 password: "xxxx", 8741 protocols: socket.Protocol.TLSv12, 8742 useRemoteCipherPrefer: true, 8743 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 8744 cipherSuite: "AES256-SHA256" 8745} 8746let tlsConnectOptions: socket.TLSConnectOptions = { 8747 address: netAddress, 8748 secureOptions: tlsSecureOptions, 8749 ALPNProtocols: ["spdy/1", "http/1.1"] 8750} 8751tlsServer.listen(tlsConnectOptions).then(() => { 8752 console.log("listen callback success"); 8753}).catch((err: BusinessError) => { 8754 console.log("failed" + err); 8755}); 8756tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 8757 client.getSignatureAlgorithms().then((data: Array<string>) => { 8758 console.log("getSignatureAlgorithms success" + data); 8759 }).catch((err: BusinessError) => { 8760 console.error("failed" + err); 8761 }); 8762}); 8763``` 8764 8765### getLocalAddress<sup>12+</sup> 8766 8767getLocalAddress(): Promise\<NetAddress\> 8768 8769Obtains the local socket address of a **TLSSocketConnection** connection. This API uses a promise to return the result. 8770 8771> **NOTE** 8772> Call this API only after the **TLSSocketServer** connection is successfully established. 8773 8774**System capability**: SystemCapability.Communication.NetStack 8775 8776**Return value** 8777 8778| Type | Description | 8779| -------------- | --------------------------------------------------- | 8780| Promise\<[NetAddress](#netaddress)\> | Promise used to return the result.| 8781 8782**Error codes** 8783 8784| ID| Error Message | 8785| -------- | ------------------------------------------- | 8786| 2300002 | System internal error. | 8787| 2301009 | Bad file descriptor. | 8788| 2303188 | Socket operation on non-socket. | 8789 8790**Example** 8791 8792```ts 8793import { socket } from '@kit.NetworkKit'; 8794import { BusinessError } from '@kit.BasicServicesKit'; 8795 8796let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 8797let netAddress: socket.NetAddress = { 8798 address: '192.168.xx.xxx', 8799 port: 8080 8800} 8801let tlsSecureOptions: socket.TLSSecureOptions = { 8802 key: "xxxx", 8803 cert: "xxxx", 8804 ca: ["xxxx"], 8805 password: "xxxx", 8806 protocols: socket.Protocol.TLSv12, 8807 useRemoteCipherPrefer: true, 8808 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 8809 cipherSuite: "AES256-SHA256" 8810} 8811let tlsConnectOptions: socket.TLSConnectOptions = { 8812 address: netAddress, 8813 secureOptions: tlsSecureOptions, 8814 ALPNProtocols: ["spdy/1", "http/1.1"] 8815} 8816tlsServer.listen(tlsConnectOptions).then(() => { 8817 console.info("listen callback success"); 8818}).catch((err: BusinessError) => { 8819 console.error("failed" + err); 8820}); 8821 8822tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 8823 client.getLocalAddress().then((localAddress: socket.NetAddress) => { 8824 console.info("Family IP Port: " + JSON.stringify(localAddress)); 8825 }).catch((err: BusinessError) => { 8826 console.error("TLS Client Get Family IP Port failed, error: " + JSON.stringify(err)); 8827 }) 8828}); 8829``` 8830 8831### on('message')<sup>10+</sup> 8832 8833on(type: 'message', callback: Callback\<SocketMessageInfo\>): void 8834 8835Subscribes to **message** events of a **TLSSocketConnection** object. This API uses an asynchronous callback to return the result. 8836 8837**System capability**: SystemCapability.Communication.NetStack 8838 8839**Parameters** 8840 8841| Name | Type | Mandatory| Description | 8842| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 8843| type | string | Yes | Event type.<br/> **message**: message receiving event.| 8844| callback | Callback\<[SocketMessageInfo](#socketmessageinfo11)\> | Yes | Callback used to return the result. If the operation is successful, the TLS socket connection information is returned. If the operation fails, an error message is returned. | 8845 8846**Error codes** 8847 8848| ID| Error Message | 8849| -------- | ---------------- | 8850| 401 | Parameter error. | 8851 8852**Example** 8853 8854```ts 8855import { socket } from '@kit.NetworkKit'; 8856import { BusinessError } from '@kit.BasicServicesKit'; 8857 8858let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 8859let netAddress: socket.NetAddress = { 8860 address: '192.168.xx.xxx', 8861 port: 8080 8862} 8863let tlsSecureOptions: socket.TLSSecureOptions = { 8864 key: "xxxx", 8865 cert: "xxxx", 8866 ca: ["xxxx"], 8867 password: "xxxx", 8868 protocols: socket.Protocol.TLSv12, 8869 useRemoteCipherPrefer: true, 8870 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 8871 cipherSuite: "AES256-SHA256" 8872} 8873let tlsConnectOptions: socket.TLSConnectOptions = { 8874 address: netAddress, 8875 secureOptions: tlsSecureOptions, 8876 ALPNProtocols: ["spdy/1", "http/1.1"] 8877} 8878tlsServer.listen(tlsConnectOptions).then(() => { 8879 console.log("listen callback success"); 8880}).catch((err: BusinessError) => { 8881 console.log("failed" + err); 8882}); 8883 8884tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 8885 client.on('message', (value: socket.SocketMessageInfo) => { 8886 let messageView = ''; 8887 for (let i: number = 0; i < value.message.byteLength; i++) { 8888 let uint8Array = new Uint8Array(value.message) 8889 let messages = uint8Array[i] 8890 let message = String.fromCharCode(messages); 8891 messageView += message; 8892 } 8893 console.log('on message message: ' + JSON.stringify(messageView)); 8894 console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo)); 8895 }); 8896}); 8897``` 8898 8899### off('message')<sup>10+</sup> 8900 8901off(type: 'message', callback?: Callback\<SocketMessageInfo\>): void 8902 8903Unsubscribes from **message** events of a **TLSSocketConnection** object. This API uses an asynchronous callback to return the result. 8904 8905**System capability**: SystemCapability.Communication.NetStack 8906 8907**Parameters** 8908 8909| Name | Type | Mandatory| Description | 8910| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 8911| type | string | Yes | Event type.<br/> **message**: message receiving event.| 8912| callback | Callback\<[SocketMessageInfo](#socketmessageinfo11)\> | No | Callback used to return the result. If the operation is successful, the TLS socket connection information is returned. If the operation fails, an error message is returned. | 8913 8914**Error codes** 8915 8916| ID| Error Message | 8917| -------- | ---------------- | 8918| 401 | Parameter error. | 8919 8920**Example** 8921 8922```ts 8923import { socket } from '@kit.NetworkKit'; 8924import { BusinessError } from '@kit.BasicServicesKit'; 8925 8926let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 8927let netAddress: socket.NetAddress = { 8928 address: '192.168.xx.xxx', 8929 port: 8080 8930} 8931let tlsSecureOptions: socket.TLSSecureOptions = { 8932 key: "xxxx", 8933 cert: "xxxx", 8934 ca: ["xxxx"], 8935 password: "xxxx", 8936 protocols: socket.Protocol.TLSv12, 8937 useRemoteCipherPrefer: true, 8938 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 8939 cipherSuite: "AES256-SHA256" 8940} 8941let tlsConnectOptions: socket.TLSConnectOptions = { 8942 address: netAddress, 8943 secureOptions: tlsSecureOptions, 8944 ALPNProtocols: ["spdy/1", "http/1.1"] 8945} 8946tlsServer.listen(tlsConnectOptions).then(() => { 8947 console.log("listen callback success"); 8948}).catch((err: BusinessError) => { 8949 console.log("failed" + err); 8950}); 8951 8952let callback = (value: socket.SocketMessageInfo) => { 8953 let messageView = ''; 8954 for (let i: number = 0; i < value.message.byteLength; i++) { 8955 let uint8Array = new Uint8Array(value.message) 8956 let messages = uint8Array[i] 8957 let message = String.fromCharCode(messages); 8958 messageView += message; 8959 } 8960 console.log('on message message: ' + JSON.stringify(messageView)); 8961 console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo)); 8962} 8963tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 8964 client.on('message', callback); 8965 // You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 8966 client.off('message', callback); 8967 client.off('message'); 8968}); 8969``` 8970 8971### on('close')<sup>10+</sup> 8972 8973on(type: 'close', callback: Callback\<void\>): void 8974 8975Subscribes to **close** events of a **TLSSocketConnection** object. This API uses an asynchronous callback to return the result. 8976 8977**System capability**: SystemCapability.Communication.NetStack 8978 8979**Parameters** 8980 8981| Name | Type | Mandatory| Description | 8982| -------- | ---------------- | ---- | ----------------------------------- | 8983| type | string | Yes | Event type.<br/> **close**: close event.| 8984| callback | Callback\<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. | 8985 8986**Error codes** 8987 8988| ID| Error Message | 8989| -------- | ---------------- | 8990| 401 | Parameter error. | 8991 8992**Example** 8993 8994```ts 8995import { socket } from '@kit.NetworkKit'; 8996import { BusinessError } from '@kit.BasicServicesKit'; 8997 8998let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 8999let netAddress: socket.NetAddress = { 9000 address: '192.168.xx.xxx', 9001 port: 8080 9002} 9003let tlsSecureOptions: socket.TLSSecureOptions = { 9004 key: "xxxx", 9005 cert: "xxxx", 9006 ca: ["xxxx"], 9007 password: "xxxx", 9008 protocols: socket.Protocol.TLSv12, 9009 useRemoteCipherPrefer: true, 9010 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 9011 cipherSuite: "AES256-SHA256" 9012} 9013let tlsConnectOptions: socket.TLSConnectOptions = { 9014 address: netAddress, 9015 secureOptions: tlsSecureOptions, 9016 ALPNProtocols: ["spdy/1", "http/1.1"] 9017} 9018tlsServer.listen(tlsConnectOptions).then(() => { 9019 console.log("listen callback success"); 9020}).catch((err: BusinessError) => { 9021 console.log("failed" + err); 9022}); 9023tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 9024 client.on('close', () => { 9025 console.log("on close success") 9026 }); 9027}); 9028``` 9029 9030### off('close')<sup>10+</sup> 9031 9032off(type: 'close', callback?: Callback\<void\>): void 9033 9034Unsubscribes from **close** events of a **TLSSocketConnection** object. This API uses an asynchronous callback to return the result. 9035 9036**System capability**: SystemCapability.Communication.NetStack 9037 9038**Parameters** 9039 9040| Name | Type | Mandatory| Description | 9041| -------- | ---------------- | ---- | ----------------------------------- | 9042| type | string | Yes | Event type.<br/> **close**: close event.| 9043| callback | Callback\<void\> | No | Callback used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned. | 9044 9045**Error codes** 9046 9047| ID| Error Message | 9048| -------- | ---------------- | 9049| 401 | Parameter error. | 9050 9051**Example** 9052 9053```ts 9054import { socket } from '@kit.NetworkKit'; 9055import { BusinessError } from '@kit.BasicServicesKit'; 9056 9057let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 9058let netAddress: socket.NetAddress = { 9059 address: '192.168.xx.xxx', 9060 port: 8080 9061} 9062let tlsSecureOptions: socket.TLSSecureOptions = { 9063 key: "xxxx", 9064 cert: "xxxx", 9065 ca: ["xxxx"], 9066 password: "xxxx", 9067 protocols: socket.Protocol.TLSv12, 9068 useRemoteCipherPrefer: true, 9069 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 9070 cipherSuite: "AES256-SHA256" 9071} 9072let tlsConnectOptions: socket.TLSConnectOptions = { 9073 address: netAddress, 9074 secureOptions: tlsSecureOptions, 9075 ALPNProtocols: ["spdy/1", "http/1.1"] 9076} 9077tlsServer.listen(tlsConnectOptions).then(() => { 9078 console.log("listen callback success"); 9079}).catch((err: BusinessError) => { 9080 console.log("failed" + err); 9081}); 9082 9083let callback = () => { 9084 console.log("on close success"); 9085} 9086tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 9087 client.on('close', callback); 9088 // You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 9089 client.off('close', callback); 9090 client.off('close'); 9091}); 9092``` 9093 9094### on('error')<sup>10+</sup> 9095 9096on(type: 'error', callback: ErrorCallback): void 9097 9098Subscribes to **error** events of a **TLSSocketConnection** object. This API uses an asynchronous callback to return the result. 9099 9100**System capability**: SystemCapability.Communication.NetStack 9101 9102**Parameters** 9103 9104| Name | Type | Mandatory| Description | 9105| -------- | ------------- | ---- | ------------------------------------ | 9106| type | string | Yes | Event type.<br/> **error**: error event.| 9107| callback | ErrorCallback | 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. | 9108 9109**Error codes** 9110 9111| ID| Error Message | 9112| -------- | ---------------- | 9113| 401 | Parameter error. | 9114 9115**Example** 9116 9117```ts 9118import { socket } from '@kit.NetworkKit'; 9119import { BusinessError } from '@kit.BasicServicesKit'; 9120 9121let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 9122let netAddress: socket.NetAddress = { 9123 address: '192.168.xx.xxx', 9124 port: 8080 9125} 9126let tlsSecureOptions: socket.TLSSecureOptions = { 9127 key: "xxxx", 9128 cert: "xxxx", 9129 ca: ["xxxx"], 9130 password: "xxxx", 9131 protocols: socket.Protocol.TLSv12, 9132 useRemoteCipherPrefer: true, 9133 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 9134 cipherSuite: "AES256-SHA256" 9135} 9136let tlsConnectOptions: socket.TLSConnectOptions = { 9137 address: netAddress, 9138 secureOptions: tlsSecureOptions, 9139 ALPNProtocols: ["spdy/1", "http/1.1"] 9140} 9141tlsServer.listen(tlsConnectOptions).then(() => { 9142 console.log("listen callback success"); 9143}).catch((err: BusinessError) => { 9144 console.log("failed" + err); 9145}); 9146 9147tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 9148 client.on('error', (err: BusinessError) => { 9149 console.log("on error, err:" + JSON.stringify(err)) 9150 }); 9151}); 9152``` 9153 9154### off('error')<sup>10+</sup> 9155 9156off(type: 'error', callback?: ErrorCallback): void 9157 9158Unsubscribes from **error** events of a **TLSSocketConnection** object. This API uses an asynchronous callback to return the result. 9159 9160**System capability**: SystemCapability.Communication.NetStack 9161 9162**Parameters** 9163 9164| Name | Type | Mandatory| Description | 9165| -------- | ------------- | ---- | ------------------------------------ | 9166| type | string | Yes | Event type.<br/> **error**: error event.| 9167| callback | ErrorCallback | No | Callback used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned. | 9168 9169**Error codes** 9170 9171| ID| Error Message | 9172| -------- | ---------------- | 9173| 401 | Parameter error. | 9174 9175**Example** 9176 9177```ts 9178import { socket } from '@kit.NetworkKit'; 9179import { BusinessError } from '@kit.BasicServicesKit'; 9180 9181let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 9182let netAddress: socket.NetAddress = { 9183 address: '192.168.xx.xxx', 9184 port: 8080 9185} 9186let tlsSecureOptions: socket.TLSSecureOptions = { 9187 key: "xxxx", 9188 cert: "xxxx", 9189 ca: ["xxxx"], 9190 password: "xxxx", 9191 protocols: socket.Protocol.TLSv12, 9192 useRemoteCipherPrefer: true, 9193 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 9194 cipherSuite: "AES256-SHA256" 9195} 9196let tlsConnectOptions: socket.TLSConnectOptions = { 9197 address: netAddress, 9198 secureOptions: tlsSecureOptions, 9199 ALPNProtocols: ["spdy/1", "http/1.1"] 9200} 9201tlsServer.listen(tlsConnectOptions).then(() => { 9202 console.log("listen callback success"); 9203}).catch((err: BusinessError) => { 9204 console.log("failed" + err); 9205}); 9206 9207let callback = (err: BusinessError) => { 9208 console.log("on error, err:" + JSON.stringify(err)); 9209} 9210tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 9211 client.on('error', callback); 9212 // You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 9213 client.off('error', callback); 9214 client.off('error'); 9215}); 9216``` 9217