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