1# @ohos.net.socket (Socket Connection) 2 3The **socket** module implements data transfer over TCP, UDP, Web, and TLS socket connections. 4 5> **NOTE** 6> 7> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. 8 9## Modules to Import 10 11```js 12import socket from '@ohos.net.socket'; 13``` 14 15## socket.constructUDPSocketInstance<sup>7+</sup> 16 17constructUDPSocketInstance(): UDPSocket 18 19Creates a **UDPSocket** object. 20 21**System capability**: SystemCapability.Communication.NetStack 22 23**Return value** 24 25| Type | Description | 26| :--------------------------------- | :---------------------- | 27| [UDPSocket](#udpsocket) | **UDPSocket** object.| 28 29**Example** 30 31```js 32import socket from '@ohos.net.socket'; 33let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 34``` 35 36## UDPSocket<sup>7+</sup> 37 38Defines a UDP socket connection. Before calling UDPSocket APIs, you need to call [socket.constructUDPSocketInstance](#socketconstructudpsocketinstance) to create a **UDPSocket** object. 39 40### bind<sup>7+</sup> 41 42bind(address: NetAddress, callback: AsyncCallback\<void\>): void 43 44Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result. 45 46**Required permissions**: ohos.permission.INTERNET 47 48**System capability**: SystemCapability.Communication.NetStack 49 50**Parameters** 51 52| Name | Type | Mandatory| Description | 53| -------- | ---------------------------------- | ---- | ------------------------------------------------------ | 54| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| 55| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | 56 57**Error codes** 58 59| ID| Error Message | 60| ------- | ----------------------- | 61| 401 | Parameter error. | 62| 201 | Permission denied. | 63 64**Example** 65 66```js 67import socket from '@ohos.net.socket'; 68import { BusinessError } from '@ohos.base'; 69 70let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 71let bindAddr: socket.NetAddress = { 72 address: '192.168.xx.xxx', 73 port: 1234 74} 75udp.bind(bindAddr, (err: BusinessError) => { 76 if (err) { 77 console.log('bind fail'); 78 return; 79 } 80 console.log('bind success'); 81}); 82``` 83 84### bind<sup>7+</sup> 85 86bind(address: NetAddress): Promise\<void\> 87 88Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result. 89 90**Required permissions**: ohos.permission.INTERNET 91 92**System capability**: SystemCapability.Communication.NetStack 93 94**Parameters** 95 96| Name | Type | Mandatory| Description | 97| ------- | ---------------------------------- | ---- | ------------------------------------------------------ | 98| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| 99 100**Error codes** 101 102| ID| Error Message | 103| ------- | ----------------------- | 104| 401 | Parameter error. | 105| 201 | Permission denied. | 106 107**Return value** 108 109| Type | Description | 110| :-------------- | :----------------------------------------- | 111| Promise\<void\> | Promise used to return the result.| 112 113**Example** 114 115```js 116import socket from '@ohos.net.socket'; 117import { BusinessError } from '@ohos.base'; 118 119let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 120let bindAddr: socket.NetAddress = { 121 address: '192.168.xx.xxx', 122 port: 8080 123} 124udp.bind(bindAddr).then(() => { 125 console.log('bind success'); 126}).catch((err: BusinessError) => { 127 console.log('bind fail'); 128}); 129``` 130 131### send<sup>7+</sup> 132 133send(options: UDPSendOptions, callback: AsyncCallback\<void\>): void 134 135Sends data over a UDP socket connection. This API uses an asynchronous callback to return the result. 136 137Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and port. 138 139**Required permissions**: ohos.permission.INTERNET 140 141**System capability**: SystemCapability.Communication.NetStack 142 143**Parameters** 144 145| Name | Type | Mandatory| Description | 146| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | 147| options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDP socket connection. For details, see [UDPSendOptions](#udpsendoptions).| 148| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | 149 150**Error codes** 151 152| ID| Error Message | 153| ------- | ----------------------- | 154| 401 | Parameter error. | 155| 201 | Permission denied. | 156 157**Example** 158 159```js 160import socket from '@ohos.net.socket'; 161import { BusinessError } from '@ohos.base'; 162 163let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 164 165let sendOptions: socket.UDPSendOptions = { 166 data: 'Hello, server!', 167 address: { 168 address: '192.168.xx.xxx', 169 port: 8080 170 } 171} 172udp.send(sendOptions, (err: BusinessError) => { 173 if (err) { 174 console.log('send fail'); 175 return; 176 } 177 console.log('send success'); 178}); 179``` 180 181### send<sup>7+</sup> 182 183send(options: UDPSendOptions): Promise\<void\> 184 185Sends data over a UDP socket connection. This API uses a promise to return the result. 186 187Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and port. 188 189**Required permissions**: ohos.permission.INTERNET 190 191**System capability**: SystemCapability.Communication.NetStack 192 193**Parameters** 194 195| Name | Type | Mandatory| Description | 196| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | 197| options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDP socket connection. For details, see [UDPSendOptions](#udpsendoptions).| 198 199**Error codes** 200 201| ID| Error Message | 202| ------- | ----------------------- | 203| 401 | Parameter error. | 204| 201 | Permission denied. | 205 206**Return value** 207 208| Type | Description | 209| :-------------- | :--------------------------------------------- | 210| Promise\<void\> | Promise used to return the result.| 211 212**Example** 213 214```js 215import socket from '@ohos.net.socket'; 216import { BusinessError } from '@ohos.base'; 217 218let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 219 220let sendOptions: socket.UDPSendOptions = { 221 data: 'Hello, server!', 222 address: { 223 address: '192.168.xx.xxx', 224 port: 8080 225 } 226} 227udp.send(sendOptions).then(() => { 228 console.log('send success'); 229}).catch((err: BusinessError) => { 230 console.log('send fail'); 231}); 232``` 233 234### close<sup>7+</sup> 235 236close(callback: AsyncCallback\<void\>): void 237 238Closes a UDP socket connection. This API uses an asynchronous callback to return the result. 239 240**Required permissions**: ohos.permission.INTERNET 241 242**System capability**: SystemCapability.Communication.NetStack 243 244**Parameters** 245 246| Name | Type | Mandatory| Description | 247| -------- | --------------------- | ---- | ---------- | 248| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.| 249 250**Example** 251 252```js 253import socket from '@ohos.net.socket'; 254import { BusinessError } from '@ohos.base'; 255 256let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 257udp.close((err: BusinessError) => { 258 if (err) { 259 console.log('close fail'); 260 return; 261 } 262 console.log('close success'); 263}) 264``` 265 266### close<sup>7+</sup> 267 268close(): Promise\<void\> 269 270Closes a UDP socket connection. This API uses a promise to return the result. 271 272**Required permissions**: ohos.permission.INTERNET 273 274**System capability**: SystemCapability.Communication.NetStack 275 276**Return value** 277 278| Type | Description | 279| :-------------- | :----------------------------------------- | 280| Promise\<void\> | Promise used to return the result.| 281 282**Example** 283 284```js 285import socket from '@ohos.net.socket'; 286import { BusinessError } from '@ohos.base'; 287 288let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 289udp.close().then(() => { 290 console.log('close success'); 291}).catch((err: BusinessError) => { 292 console.log('close fail'); 293}); 294``` 295 296### getState<sup>7+</sup> 297 298getState(callback: AsyncCallback\<SocketStateBase\>): void 299 300Obtains the status of the UDP socket connection. This API uses an asynchronous callback to return the result. 301 302> **NOTE** 303> This API can be called only after **bind** is successfully called. 304 305**Required permissions**: ohos.permission.INTERNET 306 307**System capability**: SystemCapability.Communication.NetStack 308 309**Parameters** 310 311| Name | Type | Mandatory| Description | 312| -------- | ------------------------------------------------------ | ---- | ---------- | 313| callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | Yes | Callback used to return the result.| 314 315**Error codes** 316 317| ID| Error Message | 318| ------- | ----------------------- | 319| 201 | Permission denied. | 320 321**Example** 322 323```js 324import socket from '@ohos.net.socket'; 325import { BusinessError } from '@ohos.base'; 326 327let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 328let bindAddr: socket.NetAddress = { 329 address: '192.168.xx.xxx', 330 port: 8080 331} 332udp.bind(bindAddr, (err: BusinessError) => { 333 if (err) { 334 console.log('bind fail'); 335 return; 336 } 337 console.log('bind success'); 338 udp.getState((err: BusinessError, data: socket.SocketStateBase) => { 339 if (err) { 340 console.log('getState fail'); 341 return; 342 } 343 console.log('getState success:' + JSON.stringify(data)); 344 }) 345}) 346``` 347 348### getState<sup>7+</sup> 349 350getState(): Promise\<SocketStateBase\> 351 352Obtains the status of the UDP socket connection. This API uses a promise to return the result. 353 354> **NOTE** 355> This API can be called only after **bind** is successfully called. 356 357**Required permissions**: ohos.permission.INTERNET 358 359**System capability**: SystemCapability.Communication.NetStack 360 361**Return value** 362 363| Type | Description | 364| :----------------------------------------------- | :----------------------------------------- | 365| Promise\<[SocketStateBase](#socketstatebase)\> | Promise used to return the result.| 366 367**Example** 368 369```js 370import socket from '@ohos.net.socket'; 371import { BusinessError } from '@ohos.base'; 372 373let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 374let bindAddr: socket.NetAddress = { 375 address: '192.168.xx.xxx', 376 port: 8080 377} 378udp.bind(bindAddr, (err: BusinessError) => { 379 if (err) { 380 console.log('bind fail'); 381 return; 382 } 383 console.log('bind success'); 384 udp.getState().then((data: socket.SocketStateBase) => { 385 console.log('getState success:' + JSON.stringify(data)); 386 }).catch((err: BusinessError) => { 387 console.log('getState fail' + JSON.stringify(err)); 388 }); 389}); 390``` 391 392### setExtraOptions<sup>7+</sup> 393 394setExtraOptions(options: UDPExtraOptions, callback: AsyncCallback\<void\>): void 395 396Sets other properties of the UDP socket connection. This API uses an asynchronous callback to return the result. 397 398> **NOTE** 399> This API can be called only after **bind** is successfully called. 400 401**Required permissions**: ohos.permission.INTERNET 402 403**System capability**: SystemCapability.Communication.NetStack 404 405**Parameters** 406 407| Name | Type | Mandatory| Description | 408| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | 409| options | [UDPExtraOptions](#udpextraoptions) | Yes | Other properties of the UDP socket connection. For details, see [UDPExtraOptions](#udpextraoptions).| 410| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | 411 412**Error codes** 413 414| ID| Error Message | 415| ------- | ----------------------- | 416| 401 | Parameter error. | 417| 201 | Permission denied. | 418 419**Example** 420 421```js 422import socket from '@ohos.net.socket'; 423import { BusinessError } from '@ohos.base'; 424 425let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 426 427let bindAddr: socket.NetAddress = { 428 address: '192.168.xx.xxx', 429 port: 8080 430} 431udp.bind(bindAddr, (err: BusinessError) => { 432 if (err) { 433 console.log('bind fail'); 434 return; 435 } 436 console.log('bind success'); 437 let udpextraoptions: socket.UDPExtraOptions = { 438 receiveBufferSize: 1000, 439 sendBufferSize: 1000, 440 reuseAddress: false, 441 socketTimeout: 6000, 442 broadcast: true 443 } 444 udp.setExtraOptions(udpextraoptions, (err: BusinessError) => { 445 if (err) { 446 console.log('setExtraOptions fail'); 447 return; 448 } 449 console.log('setExtraOptions success'); 450 }) 451}) 452``` 453 454### setExtraOptions<sup>7+</sup> 455 456setExtraOptions(options: UDPExtraOptions): Promise\<void\> 457 458Sets other properties of the UDP socket connection. This API uses a promise to return the result. 459 460> **NOTE** 461> This API can be called only after **bind** is successfully called. 462 463**Required permissions**: ohos.permission.INTERNET 464 465**System capability**: SystemCapability.Communication.NetStack 466 467**Parameters** 468 469| Name | Type | Mandatory| Description | 470| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | 471| options | [UDPExtraOptions](#udpextraoptions) | Yes | Other properties of the UDP socket connection. For details, see [UDPExtraOptions](#udpextraoptions).| 472 473**Return value** 474 475| Type | Description | 476| :-------------- | :--------------------------------------------------- | 477| Promise\<void\> | Promise used to return the result.| 478 479**Error codes** 480 481| ID| Error Message | 482| ------- | ----------------------- | 483| 401 | Parameter error. | 484| 201 | Permission denied. | 485 486**Example** 487 488```js 489import socket from '@ohos.net.socket'; 490import { BusinessError } from '@ohos.base'; 491 492let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 493 494let bindAddr: socket.NetAddress = { 495 address: '192.168.xx.xxx', 496 port: 8080 497} 498udp.bind(bindAddr, (err: BusinessError) => { 499 if (err) { 500 console.log('bind fail'); 501 return; 502 } 503 console.log('bind success'); 504 let udpextraoptions: socket.UDPExtraOptions = { 505 receiveBufferSize: 1000, 506 sendBufferSize: 1000, 507 reuseAddress: false, 508 socketTimeout: 6000, 509 broadcast: true 510 } 511 udp.setExtraOptions(udpextraoptions).then(() => { 512 console.log('setExtraOptions success'); 513 }).catch((err: BusinessError) => { 514 console.log('setExtraOptions fail'); 515 }); 516}) 517``` 518 519### on('message')<sup>7+</sup> 520 521on(type: 'message', callback: Callback\<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void 522 523Subscribes to **message** events of the UDP socket connection. This API uses an asynchronous callback to return the result. 524 525**System capability**: SystemCapability.Communication.NetStack 526 527**Parameters** 528 529| Name | Type | Mandatory| Description | 530| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 531| type | string | Yes | Type of the event to subscribe to.<br/> **message**: message receiving event.| 532| callback | Callback\<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}\> | Yes | Callback used to return the result. | 533 534**Example** 535 536```js 537import socket from "@ohos.net.socket"; 538import { BusinessError } from '@ohos.base'; 539let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 540 541class SocketInfo { 542 message: ArrayBuffer = new ArrayBuffer(1); 543 remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 544} 545let messageView = ''; 546udp.on('message', (value: SocketInfo) => { 547 for (let i: number = 0; i < value.message.byteLength; i++) { 548 let messages: number = value.message[i] 549 let message = String.fromCharCode(messages); 550 messageView += message; 551 } 552 console.log('on message message: ' + JSON.stringify(messageView)); 553 console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo)); 554}); 555``` 556 557### off('message')<sup>7+</sup> 558 559off(type: 'message', callback?: Callback\<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void 560 561Unsubscribes from **message** events of the UDP socket connection. This API uses an asynchronous callback to return the result. 562 563> **NOTE** 564> 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. 565 566**System capability**: SystemCapability.Communication.NetStack 567 568**Parameters** 569 570| Name | Type | Mandatory| Description | 571| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 572| type | string | Yes | Type of the event to subscribe to.<br/> **message**: message receiving event.| 573| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No | Callback used to return the result. | 574 575**Example** 576 577```js 578import socket from "@ohos.net.socket"; 579import { BusinessError } from '@ohos.base'; 580class SocketInfo { 581 message: ArrayBuffer = new ArrayBuffer(1); 582 remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 583} 584let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 585let messageView = ''; 586let callback = (value: SocketInfo) => { 587 for (let i: number = 0; i < value.message.byteLength; i++) { 588 let messages: number = value.message[i] 589 let message = String.fromCharCode(messages); 590 messageView += message; 591 } 592 console.log('on message message: ' + JSON.stringify(messageView)); 593 console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo)); 594} 595udp.on('message', callback); 596// 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. 597udp.off('message', callback); 598udp.off('message'); 599``` 600 601### on('listening' | 'close')<sup>7+</sup> 602 603on(type: 'listening' | 'close', callback: Callback\<void\>): void 604 605Subscribes to **listening** events or **close** events of the UDP socket connection. This API uses an asynchronous callback to return the result. 606 607**System capability**: SystemCapability.Communication.NetStack 608 609**Parameters** 610 611| Name | Type | Mandatory| Description | 612| -------- | ---------------- | ---- | ------------------------------------------------------------ | 613| type | string | Yes | Type of the event to subscribe to.<br>- **listening**: data packet message event.<br>- **close**: close event.| 614| callback | Callback\<void\> | Yes | Callback used to return the result. | 615 616**Example** 617 618```js 619import socket from "@ohos.net.socket"; 620import { BusinessError } from '@ohos.base'; 621let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 622udp.on('listening', () => { 623 console.log("on listening success"); 624}); 625udp.on('close', () => { 626 console.log("on close success"); 627}); 628``` 629 630### off('listening' | 'close')<sup>7+</sup> 631 632off(type: 'listening' | 'close', callback?: Callback\<void\>): void 633 634Unsubscribes from **listening** events or **close** events of the UDP socket connection. This API uses an asynchronous callback to return the result. 635 636> **NOTE** 637> 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. 638 639**System capability**: SystemCapability.Communication.NetStack 640 641**Parameters** 642 643| Name | Type | Mandatory| Description | 644| -------- | ---------------- | ---- | ------------------------------------------------------------ | 645| type | string | Yes | Type of the event to subscribe to.<br>- **listening**: data packet message event.<br>- **close**: close event.| 646| callback | Callback\<void\> | No | Callback used to return the result. | 647 648**Example** 649 650```js 651import socket from "@ohos.net.socket"; 652import { BusinessError } from '@ohos.base'; 653let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 654let callback1 = () => { 655 console.log("on listening, success"); 656} 657udp.on('listening', callback1); 658// 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. 659udp.off('listening', callback1); 660udp.off('listening'); 661let callback2 = () => { 662 console.log("on close, success"); 663} 664udp.on('close', callback2); 665// 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. 666udp.off('close', callback2); 667udp.off('close'); 668``` 669 670### on('error')<sup>7+</sup> 671 672on(type: 'error', callback: ErrorCallback): void 673 674Subscribes to **error** events of the UDP socket connection. This API uses an asynchronous callback to return the result. 675 676**System capability**: SystemCapability.Communication.NetStack 677 678**Parameters** 679 680| Name | Type | Mandatory| Description | 681| -------- | ------------- | ---- | ------------------------------------ | 682| type | string | Yes | Type of the event to subscribe to.<br/> **error**: error event.| 683| callback | ErrorCallback | Yes | Callback used to return the result. | 684 685**Example** 686 687```js 688import socket from "@ohos.net.socket"; 689import { BusinessError } from '@ohos.base'; 690let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 691udp.on('error', (err: BusinessError) => { 692 console.log("on error, err:" + JSON.stringify(err)) 693}); 694``` 695 696### off('error')<sup>7+</sup> 697 698off(type: 'error', callback?: ErrorCallback): void 699 700Unsubscribes from **error** events of the UDP socket connection. This API uses an asynchronous callback to return the result. 701 702> **NOTE** 703> 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. 704 705**System capability**: SystemCapability.Communication.NetStack 706 707**Parameters** 708 709| Name | Type | Mandatory| Description | 710| -------- | ------------- | ---- | ------------------------------------ | 711| type | string | Yes | Type of the event to subscribe to.<br/> **error**: error event.| 712| callback | ErrorCallback | No | Callback used to return the result. | 713 714**Example** 715 716```js 717import socket from "@ohos.net.socket"; 718import { BusinessError } from '@ohos.base'; 719let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 720let callback = (err: BusinessError) => { 721 console.log("on error, err:" + JSON.stringify(err)); 722} 723udp.on('error', callback); 724// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events. 725udp.off('error', callback); 726udp.off('error'); 727``` 728 729## NetAddress<sup>7+</sup> 730 731Defines the destination address. 732 733**System capability**: SystemCapability.Communication.NetStack 734 735| Name | Type | Mandatory| Description | 736| ------- | ------ | ---- | ------------------------------------------------------------ | 737| address | string | Yes | Bound IP address. | 738| port | number | No | Port number. The value ranges from **0** to **65535**. If this parameter is not specified, the system randomly allocates a port. | 739| family | number | No | Network protocol type.<br>- **1**: IPv4<br>- **2**: IPv6<br>The default value is **1**.| 740 741## UDPSendOptions<sup>7+</sup> 742 743Defines the parameters for sending data over the UDP socket connection. 744 745**System capability**: SystemCapability.Communication.NetStack 746 747| Name | Type | Mandatory| Description | 748| ------- | ---------------------------------- | ---- | -------------- | 749| data | string \| ArrayBuffer<sup>7+</sup> | Yes | Data to send. | 750| address | [NetAddress](#netaddress) | Yes | Destination address.| 751 752## UDPExtraOptions<sup>7+</sup> 753 754Defines other properties of the UDP socket connection. 755 756**System capability**: SystemCapability.Communication.NetStack 757 758| Name | Type | Mandatory| Description | 759| ----------------- | ------- | ---- | -------------------------------- | 760| broadcast | boolean | No | Whether to send broadcast messages. The default value is **false**. | 761| receiveBufferSize | number | No | Size of the receive buffer, in bytes. The default value is **0**. | 762| sendBufferSize | number | No | Size of the send buffer, in bytes. The default value is **0**. | 763| reuseAddress | boolean | No | Whether to reuse addresses. The default value is **false**. | 764| socketTimeout | number | No | Timeout duration of the UDP socket connection, in ms. The default value is **0**.| 765 766## SocketStateBase<sup>7+</sup> 767 768Defines the status of the socket connection. 769 770**System capability**: SystemCapability.Communication.NetStack 771 772| Name | Type | Mandatory| Description | 773| ----------- | ------- | ---- | ---------- | 774| isBound | boolean | Yes | Whether the connection is in the bound state.| 775| isClose | boolean | Yes | Whether the connection is in the closed state.| 776| isConnected | boolean | Yes | Whether the connection is in the connected state.| 777 778## SocketRemoteInfo<sup>7+</sup> 779 780Defines information about the socket connection. 781 782**System capability**: SystemCapability.Communication.NetStack 783 784| Name | Type | Mandatory| Description | 785| ------- | ------ | ---- | ------------------------------------------------------------ | 786| address | string | Yes | Bound IP address. | 787| family | string | Yes | Network protocol type.<br>- IPv4<br>- IPv6<br>The default value is **IPv4**.| 788| port | number | Yes | Port number. The value ranges from **0** to **65535**. | 789| size | number | Yes | Length of the server response message, in bytes. | 790 791## Description of UDP Error Codes 792 793The UDP error code mapping is in the format of 2301000 + Linux kernel error code. 794 795For details about error codes, see [Socket Error Codes](../errorcodes/errorcode-net-socket.md). 796 797## socket.constructTCPSocketInstance<sup>7+</sup> 798 799constructTCPSocketInstance(): TCPSocket 800 801Creates a **TCPSocket** object. 802 803**System capability**: SystemCapability.Communication.NetStack 804 805**Return value** 806 807| Type | Description | 808 | :--------------------------------- | :---------------------- | 809| [TCPSocket](#tcpsocket) | **TCPSocket** object.| 810 811**Example** 812 813```js 814import socket from "@ohos.net.socket"; 815let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 816``` 817 818## TCPSocket<sup>7+</sup> 819 820Defines a TCP socket connection. Before calling TCPSocket APIs, you need to call [socket.constructTCPSocketInstance](#socketconstructtcpsocketinstance) to create a **TCPSocket** object. 821 822### bind<sup>7+</sup> 823 824bind(address: NetAddress, callback: AsyncCallback\<void\>): void 825 826Binds 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. 827 828> **NOTE** 829> If the bind operation fails due to a port conflict, the system will randomly allocate a port number. 830> 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. 831> 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 must be deployed on the same device. 832 833**Required permissions**: ohos.permission.INTERNET 834 835**System capability**: SystemCapability.Communication.NetStack 836 837**Parameters** 838 839| Name | Type | Mandatory| Description | 840| -------- | ---------------------------------- | ---- | ------------------------------------------------------ | 841| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| 842| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | 843 844**Error codes** 845 846| ID| Error Message | 847| ------- | ----------------------- | 848| 401 | Parameter error. | 849| 201 | Permission denied. | 850 851**Example** 852 853```js 854import socket from "@ohos.net.socket"; 855import { BusinessError } from '@ohos.base'; 856let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 857let bindAddr: socket.NetAddress = { 858 address: '192.168.xx.xxx', 859 port: 8080 860} 861tcp.bind(bindAddr, (err: BusinessError) => { 862 if (err) { 863 console.log('bind fail'); 864 return; 865 } 866 console.log('bind success'); 867}) 868``` 869 870### bind<sup>7+</sup> 871 872bind(address: NetAddress): Promise\<void\> 873 874Binds 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. 875 876> **NOTE** 877> If the bind operation fails due to a port conflict, the system will randomly allocate a port number. 878> 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. 879> 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. 880 881**Required permissions**: ohos.permission.INTERNET 882 883**System capability**: SystemCapability.Communication.NetStack 884 885**Parameters** 886 887| Name | Type | Mandatory| Description | 888| ------- | ---------------------------------- | ---- | ------------------------------------------------------ | 889| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| 890 891**Return value** 892 893| Type | Description | 894| :-------------- | :------------------------------------------------------- | 895| Promise\<void\> | Promise used to return the result.| 896 897**Error codes** 898 899| ID| Error Message | 900| ------- | ----------------------- | 901| 401 | Parameter error. | 902| 201 | Permission denied. | 903 904**Example** 905 906```js 907import socket from "@ohos.net.socket"; 908import { BusinessError } from '@ohos.base'; 909let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 910let bindAddr: socket.NetAddress = { 911 address: '192.168.xx.xxx', 912 port: 8080 913} 914tcp.bind(bindAddr).then(() => { 915 console.log('bind success'); 916}).catch((err: BusinessError) => { 917 console.log('bind fail'); 918}); 919``` 920 921### connect<sup>7+</sup> 922 923connect(options: TCPConnectOptions, callback: AsyncCallback\<void\>): void 924 925Sets up a connection to the specified IP address and port number. This API uses an asynchronous callback to return the result. 926 927> **NOTE** 928> This API allows you to connect to the TCP server without first executing **tcp.bind**. 929 930**Required permissions**: ohos.permission.INTERNET 931 932**System capability**: SystemCapability.Communication.NetStack 933 934**Parameters** 935 936| Name | Type | Mandatory| Description | 937| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | 938| options | [TCPConnectOptions](#tcpconnectoptions) | Yes | TCP socket connection parameters. For details, see [TCPConnectOptions](#tcpconnectoptions).| 939| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | 940 941**Error codes** 942 943| ID| Error Message | 944| ------- | ----------------------- | 945| 401 | Parameter error. | 946| 201 | Permission denied. | 947 948**Example** 949 950```js 951import socket from "@ohos.net.socket"; 952import { BusinessError } from '@ohos.base'; 953let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 954 955let tcpconnectoptions: socket.TCPConnectOptions = { 956 address: { 957 address: '192.168.xx.xxx', 958 port: 8080 959 }, 960 timeout: 6000 961} 962tcp.connect(tcpconnectoptions, (err: BusinessError) => { 963 if (err) { 964 console.log('connect fail'); 965 return; 966 } 967 console.log('connect success'); 968}) 969``` 970 971### connect<sup>7+</sup> 972 973connect(options: TCPConnectOptions): Promise\<void\> 974 975Sets up a connection to the specified IP address and port number. This API uses a promise to return the result. 976 977> **NOTE** 978> This API allows you to connect to the TCP server without first executing **tcp.bind**. 979 980**Required permissions**: ohos.permission.INTERNET 981 982**System capability**: SystemCapability.Communication.NetStack 983 984**Parameters** 985 986| Name | Type | Mandatory| Description | 987| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | 988| options | [TCPConnectOptions](#tcpconnectoptions) | Yes | TCP socket connection parameters. For details, see [TCPConnectOptions](#tcpconnectoptions).| 989 990**Return value** 991 992| Type | Description | 993| :-------------- | :--------------------------------------------------------- | 994| Promise\<void\> | Promise used to return the result.| 995 996**Error codes** 997 998| ID| Error Message | 999| ------- | ----------------------- | 1000| 401 | Parameter error. | 1001| 201 | Permission denied. | 1002 1003**Example** 1004 1005```js 1006import socket from "@ohos.net.socket"; 1007import { BusinessError } from '@ohos.base'; 1008let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1009 1010let tcpconnectoptions: socket.TCPConnectOptions = { 1011 address: { 1012 address: '192.168.xx.xxx', 1013 port: 8080 1014 }, 1015 timeout: 6000 1016} 1017tcp.connect(tcpconnectoptions).then(() => { 1018 console.log('connect success') 1019}).catch((err: BusinessError) => { 1020 console.log('connect fail'); 1021}); 1022``` 1023 1024### send<sup>7+</sup> 1025 1026send(options: TCPSendOptions, callback: AsyncCallback\<void\>): void 1027 1028Sends data over a TCP socket connection. This API uses an asynchronous callback to return the result. 1029 1030> **NOTE** 1031> This API can be called only after **connect** is successfully called. 1032 1033**Required permissions**: ohos.permission.INTERNET 1034 1035**System capability**: SystemCapability.Communication.NetStack 1036 1037**Parameters** 1038 1039| Name | Type | Mandatory| Description | 1040| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | 1041| options | [TCPSendOptions](#tcpsendoptions) | Yes | Parameters for sending data over the TCP socket connection. For details, see [TCPSendOptions](#tcpsendoptions).| 1042| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | 1043 1044**Error codes** 1045 1046| ID| Error Message | 1047| ------- | ----------------------- | 1048| 401 | Parameter error. | 1049| 201 | Permission denied. | 1050 1051**Example** 1052 1053```js 1054import socket from "@ohos.net.socket"; 1055import { BusinessError } from '@ohos.base'; 1056let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1057 1058let tcpconnectoptions: socket.TCPConnectOptions = { 1059 address: { 1060 address: '192.168.xx.xxx', 1061 port: 8080 1062 }, 1063 timeout: 6000 1064} 1065tcp.connect(tcpconnectoptions, () => { 1066 console.log('connect success'); 1067 let tcpSendOptions: socket.TCPSendOptions = { 1068 data: 'Hello, server!' 1069 } 1070 tcp.send(tcpSendOptions, (err: BusinessError) => { 1071 if (err) { 1072 console.log('send fail'); 1073 return; 1074 } 1075 console.log('send success'); 1076 }) 1077}) 1078``` 1079 1080### send<sup>7+</sup> 1081 1082send(options: TCPSendOptions): Promise\<void\> 1083 1084Sends data over a TCP socket connection. This API uses a promise to return the result. 1085 1086> **NOTE** 1087> This API can be called only after **connect** is successfully called. 1088 1089**Required permissions**: ohos.permission.INTERNET 1090 1091**System capability**: SystemCapability.Communication.NetStack 1092 1093**Parameters** 1094 1095| Name | Type | Mandatory| Description | 1096| ------- | --------------------------------------- | ---- | ------------------------------------------------------------ | 1097| options | [TCPSendOptions](#tcpsendoptions) | Yes | Parameters for sending data over the TCP socket connection. For details, see [TCPSendOptions](#tcpsendoptions).| 1098 1099**Return value** 1100 1101| Type | Description | 1102| :-------------- | :------------------------------------------------- | 1103| Promise\<void\> | Promise used to return the result.| 1104 1105**Error codes** 1106 1107| ID| Error Message | 1108| ------- | ----------------------- | 1109| 401 | Parameter error. | 1110| 201 | Permission denied. | 1111 1112**Example** 1113 1114```js 1115import socket from "@ohos.net.socket"; 1116import { BusinessError } from '@ohos.base'; 1117let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1118 1119let tcpconnectoptions: socket.TCPConnectOptions = { 1120 address: { 1121 address: '192.168.xx.xxx', 1122 port: 8080 1123 }, 1124 timeout: 6000 1125} 1126tcp.connect(tcpconnectoptions, () => { 1127 console.log('connect success'); 1128 let tcpSendOptions: socket.TCPSendOptions = { 1129 data: 'Hello, server!' 1130 } 1131 tcp.send(tcpSendOptions).then(() => { 1132 console.log('send success'); 1133 }).catch((err: BusinessError) => { 1134 console.log('send fail'); 1135 }); 1136}) 1137``` 1138 1139### close<sup>7+</sup> 1140 1141close(callback: AsyncCallback\<void\>): void 1142 1143Closes a TCP socket connection. This API uses an asynchronous callback to return the result. 1144 1145**Required permissions**: ohos.permission.INTERNET 1146 1147**System capability**: SystemCapability.Communication.NetStack 1148 1149**Parameters** 1150 1151| Name | Type | Mandatory| Description | 1152| -------- | --------------------- | ---- | ---------- | 1153| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.| 1154 1155**Error codes** 1156 1157| ID| Error Message | 1158| ------- | ----------------------- | 1159| 201 | Permission denied. | 1160 1161**Example** 1162 1163```js 1164import socket from "@ohos.net.socket"; 1165import { BusinessError } from '@ohos.base'; 1166let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1167 1168tcp.close((err: BusinessError) => { 1169 if (err) { 1170 console.log('close fail'); 1171 return; 1172 } 1173 console.log('close success'); 1174}) 1175``` 1176 1177### close<sup>7+</sup> 1178 1179close(): Promise\<void\> 1180 1181Closes a TCP socket connection. This API uses a promise to return the result. 1182 1183**Required permissions**: ohos.permission.INTERNET 1184 1185**System capability**: SystemCapability.Communication.NetStack 1186 1187**Return value** 1188 1189| Type | Description | 1190| :-------------- | :----------------------------------------- | 1191| Promise\<void\> | Promise used to return the result.| 1192 1193**Error codes** 1194 1195| ID| Error Message | 1196| ------- | ----------------------- | 1197| 201 | Permission denied. | 1198 1199**Example** 1200 1201```js 1202import socket from "@ohos.net.socket"; 1203let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1204 1205tcp.close().then(() => { 1206 console.log('close success'); 1207}).catch((err: BusinessError) => { 1208 console.log('close fail'); 1209}); 1210``` 1211 1212### getRemoteAddress<sup>7+</sup> 1213 1214getRemoteAddress(callback: AsyncCallback\<NetAddress\>): void 1215 1216Obtains the remote address of a socket connection. This API uses an asynchronous callback to return the result. 1217 1218> **NOTE** 1219> This API can be called only after **connect** is successfully called. 1220 1221**Required permissions**: ohos.permission.INTERNET 1222 1223**System capability**: SystemCapability.Communication.NetStack 1224 1225**Parameters** 1226 1227| Name | Type | Mandatory| Description | 1228| -------- | ------------------------------------------------- | ---- | ---------- | 1229| callback | AsyncCallback<[NetAddress](#netaddress)> | Yes | Callback used to return the result.| 1230 1231**Error codes** 1232 1233| ID| Error Message | 1234| ------- | ----------------------- | 1235| 201 | Permission denied. | 1236 1237**Example** 1238 1239```js 1240import socket from "@ohos.net.socket"; 1241import { BusinessError } from '@ohos.base'; 1242let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1243 1244let tcpconnectoptions: socket.TCPConnectOptions = { 1245 address: { 1246 address: '192.168.xx.xxx', 1247 port: 8080 1248 }, 1249 timeout: 6000 1250} 1251tcp.connect(tcpconnectoptions, () => { 1252 console.log('connect success'); 1253 tcp.getRemoteAddress((err: BusinessError, data: socket.NetAddress) => { 1254 if (err) { 1255 console.log('getRemoteAddressfail'); 1256 return; 1257 } 1258 console.log('getRemoteAddresssuccess:' + JSON.stringify(data)); 1259 }) 1260}); 1261``` 1262 1263### getRemoteAddress<sup>7+</sup> 1264 1265getRemoteAddress(): Promise\<NetAddress\> 1266 1267Obtains the remote address of a socket connection. This API uses a promise to return the result. 1268 1269> **NOTE** 1270> This API can be called only after **connect** is successfully called. 1271 1272**Required permissions**: ohos.permission.INTERNET 1273 1274**System capability**: SystemCapability.Communication.NetStack 1275 1276**Return value** 1277 1278| Type | Description | 1279| :------------------------------------------ | :------------------------------------------ | 1280| Promise<[NetAddress](#netaddress)> | Promise used to return the result.| 1281 1282**Error codes** 1283 1284| ID| Error Message | 1285| ------- | ----------------------- | 1286| 201 | Permission denied. | 1287 1288**Example** 1289 1290```js 1291import socket from "@ohos.net.socket"; 1292import { BusinessError } from '@ohos.base'; 1293let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1294 1295let tcpconnectoptions: socket.TCPConnectOptions = { 1296 address: { 1297 address: '192.168.xx.xxx', 1298 port: 8080 1299 }, 1300 timeout: 6000 1301} 1302tcp.connect(tcpconnectoptions).then(() => { 1303 console.log('connect success'); 1304 tcp.getRemoteAddress().then(() => { 1305 console.log('getRemoteAddress success'); 1306 }).catch((err: BusinessError) => { 1307 console.log('getRemoteAddressfail'); 1308 }); 1309}).catch((err: BusinessError) => { 1310 console.log('connect fail'); 1311}); 1312``` 1313 1314### getState<sup>7+</sup> 1315 1316getState(callback: AsyncCallback\<SocketStateBase\>): void 1317 1318Obtains the status of the TCP socket connection. This API uses an asynchronous callback to return the result. 1319 1320> **NOTE** 1321> This API can be called only after **bind** or **connect** is successfully called. 1322 1323**Required permissions**: ohos.permission.INTERNET 1324 1325**System capability**: SystemCapability.Communication.NetStack 1326 1327**Parameters** 1328 1329| Name | Type | Mandatory| Description | 1330| -------- | ------------------------------------------------------ | ---- | ---------- | 1331| callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | Yes | Callback used to return the result.| 1332 1333**Error codes** 1334 1335| ID| Error Message | 1336| ------- | ----------------------- | 1337| 201 | Permission denied. | 1338 1339**Example** 1340 1341```js 1342import socket from "@ohos.net.socket"; 1343import { BusinessError } from '@ohos.base'; 1344let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1345 1346let tcpconnectoptions: socket.TCPConnectOptions = { 1347 address: { 1348 address: '192.168.xx.xxx', 1349 port: 8080 1350 }, 1351 timeout: 6000 1352} 1353tcp.connect(tcpconnectoptions, () => { 1354 console.log('connect success'); 1355 tcp.getState((err: BusinessError, data: socket.SocketStateBase) => { 1356 if (err) { 1357 console.log('getState fail'); 1358 return; 1359 } 1360 console.log('getState success:' + JSON.stringify(data)); 1361 }); 1362}); 1363``` 1364 1365### getState<sup>7+</sup> 1366 1367getState(): Promise\<SocketStateBase\> 1368 1369Obtains the status of the TCP socket connection. This API uses a promise to return the result. 1370 1371> **NOTE** 1372> This API can be called only after **bind** or **connect** is successfully called. 1373 1374**Required permissions**: ohos.permission.INTERNET 1375 1376**System capability**: SystemCapability.Communication.NetStack 1377 1378**Return value** 1379 1380| Type | Description | 1381| :----------------------------------------------- | :----------------------------------------- | 1382| Promise<[SocketStateBase](#socketstatebase)> | Promise used to return the result.| 1383 1384**Error codes** 1385 1386| ID| Error Message | 1387| ------- | ----------------------- | 1388| 201 | Permission denied. | 1389 1390**Example** 1391 1392```js 1393import socket from "@ohos.net.socket"; 1394import { BusinessError } from '@ohos.base'; 1395let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1396 1397let tcpconnectoptions: socket.TCPConnectOptions = { 1398 address: { 1399 address: '192.168.xx.xxx', 1400 port: 8080 1401 }, 1402 timeout: 6000 1403} 1404tcp.connect(tcpconnectoptions).then(() => { 1405 console.log('connect success'); 1406 tcp.getState().then(() => { 1407 console.log('getState success'); 1408 }).catch((err: BusinessError) => { 1409 console.log('getState fail'); 1410 }); 1411}).catch((err: BusinessError) => { 1412 console.log('connect fail'); 1413}); 1414``` 1415 1416### getSocketFd<sup>10+</sup> 1417 1418getSocketFd(callback: AsyncCallback\<number\>): void 1419 1420Obtains the file descriptor of the **TCPSocket** object. This API uses an asynchronous callback to return the result. 1421 1422> **NOTE** 1423> This API can be called only after **bind** or **connect** is successfully called. 1424 1425**System capability**: SystemCapability.Communication.NetStack 1426 1427**Parameters** 1428 1429| Name | Type | Mandatory| Description | 1430| -------- | ------------------------------------------------------ | ---- | ---------- | 1431| 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.| 1432 1433**Example** 1434 1435```js 1436import socket from "@ohos.net.socket"; 1437import { BusinessError } from '@ohos.base'; 1438let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1439let bindAddr: socket.NetAddress = { 1440 address: '0.0.0.0' 1441} 1442tcp.bind(bindAddr) 1443let tcpconnectoptions: socket.TCPConnectOptions = { 1444 address: { 1445 address: '192.168.xx.xxx', 1446 port: 8080 1447 }, 1448 timeout: 6000 1449} 1450tcp.connect(tcpconnectoptions) 1451tcp.getSocketFd((err: BusinessError, data: number) => { 1452 console.info("getSocketFd failed: " + err); 1453 console.info("tunenlfd: " + data); 1454}) 1455``` 1456### getSocketFd<sup>10+</sup> 1457 1458getSocketFd(): Promise\<number\> 1459 1460Obtains the file descriptor of the **TCPSocket** object. This API uses a promise to return the result. 1461 1462> **NOTE** 1463> This API can be called only after **bind** or **connect** is successfully called. 1464 1465**System capability**: SystemCapability.Communication.NetStack 1466 1467**Return value** 1468 1469| Type | Description | 1470| :----------------------------------------------- | :----------------------------------------- | 1471| Promise\<number\> | Promise used to return the result.| 1472 1473**Example** 1474 1475```js 1476import socket from "@ohos.net.socket"; 1477import { BusinessError } from '@ohos.base'; 1478let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1479let bindAddr: socket.NetAddress = { 1480 address: '0.0.0.0' 1481} 1482tcp.bind(bindAddr) 1483let tcpconnectoptions: socket.TCPConnectOptions = { 1484 address: { 1485 address: '192.168.xx.xxx', 1486 port: 8080 1487 }, 1488 timeout: 6000 1489} 1490tcp.connect(tcpconnectoptions) 1491tcp.getSocketFd().then((data: number) => { 1492 console.info("tunenlfd: " + data); 1493}) 1494``` 1495 1496### setExtraOptions<sup>7+</sup> 1497 1498setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\<void\>): void 1499 1500Sets other properties of the TCP socket connection. This API uses an asynchronous callback to return the result. 1501 1502> **NOTE** 1503> This API can be called only after **bind** or **connect** is successfully called. 1504 1505**Required permissions**: ohos.permission.INTERNET 1506 1507**System capability**: SystemCapability.Communication.NetStack 1508 1509**Parameters** 1510 1511| Name | Type | Mandatory| Description | 1512| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | 1513| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCP socket connection. For details, see [TCPExtraOptions](#tcpextraoptions).| 1514| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | 1515 1516**Error codes** 1517 1518| ID| Error Message | 1519| ------- | ----------------------- | 1520| 401 | Parameter error. | 1521| 201 | Permission denied. | 1522 1523**Example** 1524 1525```js 1526import socket from "@ohos.net.socket"; 1527import { BusinessError } from '@ohos.base'; 1528let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1529let tcpconnectoptions: socket.TCPConnectOptions = { 1530 address: { 1531 address: '192.168.xx.xxx', 1532 port: 8080 1533 }, 1534 timeout: 6000 1535} 1536tcp.connect(tcpconnectoptions, () => { 1537 console.log('connect success'); 1538 let tcpExtraOptions: socket.TCPExtraOptions = { 1539 keepAlive: true, 1540 OOBInline: true, 1541 TCPNoDelay: true, 1542 socketLinger: { on: true, linger: 10 }, 1543 receiveBufferSize: 1000, 1544 sendBufferSize: 1000, 1545 reuseAddress: true, 1546 socketTimeout: 3000 1547 } 1548 tcp.setExtraOptions(tcpExtraOptions, (err: BusinessError) => { 1549 if (err) { 1550 console.log('setExtraOptions fail'); 1551 return; 1552 } 1553 console.log('setExtraOptions success'); 1554 }); 1555}); 1556``` 1557 1558### setExtraOptions<sup>7+</sup> 1559 1560setExtraOptions(options: TCPExtraOptions): Promise\<void\> 1561 1562Sets other properties of the TCP socket connection. This API uses a promise to return the result. 1563 1564> **NOTE** 1565> This API can be called only after **bind** or **connect** is successfully called. 1566 1567**Required permissions**: ohos.permission.INTERNET 1568 1569**System capability**: SystemCapability.Communication.NetStack 1570 1571**Parameters** 1572 1573| Name | Type | Mandatory| Description | 1574| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | 1575| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCP socket connection. For details, see [TCPExtraOptions](#tcpextraoptions).| 1576 1577**Return value** 1578 1579| Type | Description | 1580| :-------------- | :--------------------------------------------------- | 1581| Promise\<void\> | Promise used to return the result.| 1582 1583**Error codes** 1584 1585| ID| Error Message | 1586| ------- | ----------------------- | 1587| 401 | Parameter error. | 1588| 201 | Permission denied. | 1589 1590**Example** 1591 1592```js 1593import socket from "@ohos.net.socket"; 1594import { BusinessError } from '@ohos.base'; 1595let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1596let tcpconnectoptions: socket.TCPConnectOptions = { 1597 address: { 1598 address: '192.168.xx.xxx', 1599 port: 8080 1600 }, 1601 timeout: 6000 1602} 1603tcp.connect(tcpconnectoptions, () => { 1604 console.log('connect success'); 1605 let tcpExtraOptions: socket.TCPExtraOptions = { 1606 keepAlive: true, 1607 OOBInline: true, 1608 TCPNoDelay: true, 1609 socketLinger: { on: true, linger: 10 }, 1610 receiveBufferSize: 1000, 1611 sendBufferSize: 1000, 1612 reuseAddress: true, 1613 socketTimeout: 3000 1614 } 1615 tcp.setExtraOptions(tcpExtraOptions).then(() => { 1616 console.log('setExtraOptions success'); 1617 }).catch((err: BusinessError) => { 1618 console.log('setExtraOptions fail'); 1619 }); 1620}); 1621``` 1622 1623### on('message')<sup>7+</sup> 1624 1625on(type: 'message', callback: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void 1626 1627Subscribes to **message** events of the TCP socket connection. This API uses an asynchronous callback to return the result. 1628 1629**System capability**: SystemCapability.Communication.NetStack 1630 1631**Parameters** 1632 1633| Name | Type | Mandatory| Description | 1634| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 1635| type | string | Yes | Type of the event to subscribe to.<br/> **message**: message receiving event.| 1636| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | Yes | Callback used to return the result. | 1637 1638**Example** 1639 1640```js 1641import socket from "@ohos.net.socket"; 1642import { BusinessError } from '@ohos.base'; 1643let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1644class SocketInfo { 1645 message: ArrayBuffer = new ArrayBuffer(1); 1646 remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 1647} 1648let messageView = ''; 1649tcp.on('message', (value: SocketInfo) => { 1650 for (let i: number = 0; i < value.message.byteLength; i++) { 1651 let messages: number = value.message[i] 1652 let message = String.fromCharCode(messages); 1653 messageView += message; 1654 } 1655 console.log('on message message: ' + JSON.stringify(messageView)); 1656 console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo)); 1657}); 1658``` 1659 1660### off('message')<sup>7+</sup> 1661 1662off(type: 'message', callback?: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void 1663 1664Unsubscribes from **message** events of the TCP socket connection. This API uses an asynchronous callback to return the result. 1665 1666> **NOTE** 1667> 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. 1668 1669**System capability**: SystemCapability.Communication.NetStack 1670 1671**Parameters** 1672 1673| Name | Type | Mandatory| Description | 1674| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 1675| type | string | Yes | Type of the event to subscribe to.<br/> **message**: message receiving event.| 1676| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No | Callback used to return the result. | 1677 1678**Example** 1679 1680```js 1681import socket from "@ohos.net.socket"; 1682import { BusinessError } from '@ohos.base'; 1683let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1684class SocketInfo { 1685 message: ArrayBuffer = new ArrayBuffer(1); 1686 remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 1687} 1688let messageView = ''; 1689let callback = (value: SocketInfo) => { 1690 for (let i: number = 0; i < value.message.byteLength; i++) { 1691 let messages: number = value.message[i] 1692 let message = String.fromCharCode(messages); 1693 messageView += message; 1694 } 1695 console.log('on message message: ' + JSON.stringify(messageView)); 1696 console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo)); 1697} 1698tcp.on('message', callback); 1699// 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. 1700tcp.off('message', callback); 1701tcp.off('message'); 1702``` 1703 1704### on('connect' | 'close')<sup>7+</sup> 1705 1706on(type: 'connect' | 'close', callback: Callback\<void\>): void 1707 1708Subscribes to connection or close events of the TCP socket connection. This API uses an asynchronous callback to return the result. 1709 1710**System capability**: SystemCapability.Communication.NetStack 1711 1712**Parameters** 1713 1714| Name | Type | Mandatory| Description | 1715| -------- | ---------------- | ---- | ------------------------------------------------------------ | 1716| type | string | Yes | Type of the event to subscribe to.<br>- **connect**: connection event.<br>- **close**: close event.| 1717| callback | Callback\<void\> | Yes | Callback used to return the result. | 1718 1719**Example** 1720 1721```js 1722import socket from "@ohos.net.socket"; 1723import { BusinessError } from '@ohos.base'; 1724let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1725tcp.on('connect', () => { 1726 console.log("on connect success") 1727}); 1728tcp.on('close', () => { 1729 console.log("on close success") 1730}); 1731``` 1732 1733### off('connect' | 'close')<sup>7+</sup> 1734 1735off(type: 'connect' | 'close', callback?: Callback\<void\>): void 1736 1737Unsubscribes from connection or close events of the TCP socket connection. This API uses an asynchronous callback to return the result. 1738 1739> **NOTE** 1740> 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. 1741 1742**System capability**: SystemCapability.Communication.NetStack 1743 1744**Parameters** 1745 1746| Name | Type | Mandatory| Description | 1747| -------- | ---------------- | ---- | ------------------------------------------------------------ | 1748| type | string | Yes | Type of the event to subscribe to.<br>- **connect**: connection event.<br>- **close**: close event.| 1749| callback | Callback\<void\> | No | Callback used to return the result. | 1750 1751**Example** 1752 1753```js 1754import socket from "@ohos.net.socket"; 1755import { BusinessError } from '@ohos.base'; 1756let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1757let callback1 = () => { 1758 console.log("on connect success"); 1759} 1760tcp.on('connect', callback1); 1761// 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. 1762tcp.off('connect', callback1); 1763tcp.off('connect'); 1764let callback2 = () => { 1765 console.log("on close success"); 1766} 1767tcp.on('close', callback2); 1768// 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. 1769tcp.off('close', callback2); 1770tcp.off('close'); 1771``` 1772 1773### on('error')<sup>7+</sup> 1774 1775on(type: 'error', callback: ErrorCallback): void 1776 1777Subscribes to **error** events of the TCP socket connection. This API uses an asynchronous callback to return the result. 1778 1779**System capability**: SystemCapability.Communication.NetStack 1780 1781**Parameters** 1782 1783| Name | Type | Mandatory| Description | 1784| -------- | ------------- | ---- | ------------------------------------ | 1785| type | string | Yes | Type of the event to subscribe to.<br/> **error**: error event.| 1786| callback | ErrorCallback | Yes | Callback used to return the result. | 1787 1788**Example** 1789 1790```js 1791import socket from "@ohos.net.socket"; 1792import { BusinessError } from '@ohos.base'; 1793let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1794tcp.on('error', (err: BusinessError) => { 1795 console.log("on error, err:" + JSON.stringify(err)) 1796}); 1797``` 1798 1799### off('error')<sup>7+</sup> 1800 1801off(type: 'error', callback?: ErrorCallback): void 1802 1803Unsubscribes from **error** events of the TCP socket connection. This API uses an asynchronous callback to return the result. 1804 1805> **NOTE** 1806> 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. 1807 1808**System capability**: SystemCapability.Communication.NetStack 1809 1810**Parameters** 1811 1812| Name | Type | Mandatory| Description | 1813| -------- | ------------- | ---- | ------------------------------------ | 1814| type | string | Yes | Type of the event to subscribe to.<br/> **error**: error event.| 1815| callback | ErrorCallback | No | Callback used to return the result. | 1816 1817**Example** 1818 1819```js 1820import socket from "@ohos.net.socket"; 1821import { BusinessError } from '@ohos.base'; 1822let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 1823let callback = (err: BusinessError) => { 1824 console.log("on error, err:" + JSON.stringify(err)); 1825} 1826tcp.on('error', callback); 1827// 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. 1828tcp.off('error', callback); 1829tcp.off('error'); 1830``` 1831 1832## TCPConnectOptions<sup>7+</sup> 1833 1834Defines TCP socket connection parameters. 1835 1836**System capability**: SystemCapability.Communication.NetStack 1837 1838| Name | Type | Mandatory| Description | 1839| ------- | ---------------------------------- | ---- | -------------------------- | 1840| address | [NetAddress](#netaddress) | Yes | Bound IP address and port number. | 1841| timeout | number | No | Timeout duration of the TCP socket connection, in ms.| 1842 1843## TCPSendOptions<sup>7+</sup> 1844 1845Defines the parameters for sending data over the TCP socket connection. 1846 1847**System capability**: SystemCapability.Communication.NetStack 1848 1849| Name | Type | Mandatory| Description | 1850| -------- | ------ | ---- | ------------------------------------------------------------ | 1851| data | string\| ArrayBuffer<sup>7+</sup> | Yes | Data to send. | 1852| 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**.| 1853 1854## TCPExtraOptions<sup>7+</sup> 1855 1856Defines other properties of the TCP socket connection. 1857 1858**System capability**: SystemCapability.Communication.NetStack 1859 1860| Name | Type | Mandatory| Description | 1861| ----------------- | ------- | ---- | ------------------------------------------------------------ | 1862| keepAlive | boolean | No | Whether to keep the connection alive. The default value is **false**. | 1863| OOBInline | boolean | No | Whether to enable OOBInline. The default value is **false**. | 1864| TCPNoDelay | boolean | No | Whether to enable no-delay on the TCP socket connection. The default value is **false**. | 1865| socketLinger | Object | Yes | Socket linger.<br>- **on**: whether to enable socket linger. The value true means to enable socket linger and false means the opposite.<br>- **linger**: linger time, in ms. The value ranges from **0** to **65535**.<br>Specify this parameter only when **on** is set to **true**.| 1866| receiveBufferSize | number | No | Size of the receive buffer, in bytes. The default value is **0**. | 1867| sendBufferSize | number | No | Size of the send buffer, in bytes. The default value is **0**. | 1868| reuseAddress | boolean | No | Whether to reuse addresses. The default value is **false**. | 1869| socketTimeout | number | No | Timeout duration of the UDP socket connection, in ms. The default value is **0**. | 1870 1871## socket.constructTCPSocketServerInstance<sup>10+</sup> 1872 1873constructTCPSocketServerInstance(): TCPSocketServer 1874 1875Creates a **TCPSocketServer** object. 1876 1877**System capability**: SystemCapability.Communication.NetStack 1878 1879**Return value** 1880 1881| Type | Description | 1882| :---------------------------------- | :---------------------------- | 1883| [TCPSocketServer](#tcpsocketserver10) | **TCPSocketServer** object.| 1884 1885**Example** 1886 1887```js 1888import socket from "@ohos.net.socket"; 1889let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 1890``` 1891 1892## TCPSocketServer<sup>10+</sup> 1893 1894Defines a TCPSocketServer connection. Before calling TCPSocketServer APIs, you need to call [socket.constructTCPSocketServerInstance](#socketconstructtcpsocketserverinstance10) to create a **TCPSocketServer** object. 1895 1896### listen<sup>10+</sup> 1897 1898listen(address: NetAddress, callback: AsyncCallback\<void\>): void 1899 1900Binds 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. 1901 1902> **NOTE** 1903> 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. 1904 1905**Required permissions**: ohos.permission.INTERNET 1906 1907**System capability**: SystemCapability.Communication.NetStack 1908 1909**Parameters** 1910 1911| Name | Type | Mandatory| Description | 1912| -------- | ------------------------- | ---- | --------------------------------------------- | 1913| address | [NetAddress](#netaddress7) | Yes | Destination address.| 1914| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | 1915 1916**Error codes** 1917 1918| ID| Error Message | 1919| -------- | ------------------------------------------- | 1920| 401 | Parameter error. | 1921| 201 | Permission denied. | 1922| 2300002 | System internal error. | 1923| 2303109 | Bad file number. | 1924| 2303111 | Resource temporarily unavailable try again. | 1925| 2303198 | Address already in use. | 1926| 2303199 | Cannot assign requested address. | 1927 1928**Example** 1929 1930```js 1931import socket from "@ohos.net.socket"; 1932import { BusinessError } from '@ohos.base'; 1933let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 1934let listenAddr: socket.NetAddress = { 1935 address: '192.168.xx.xxx', 1936 port: 8080, 1937 family: 1 1938} 1939tcpServer.listen(listenAddr, (err: BusinessError) => { 1940 if (err) { 1941 console.log("listen fail"); 1942 return; 1943 } 1944 console.log("listen success"); 1945}) 1946``` 1947 1948### listen<sup>10+</sup> 1949 1950listen(address: NetAddress): Promise\<void\> 1951 1952Binds 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. 1953 1954> **NOTE** 1955> 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. 1956 1957**Required permissions**: ohos.permission.INTERNET 1958 1959**System capability**: SystemCapability.Communication.NetStack 1960 1961**Parameters** 1962 1963| Name | Type | Mandatory| Description | 1964| ------- | ------------------------- | ---- | --------------------------------------------- | 1965| address | [NetAddress](#netaddress7) | Yes | Destination address.| 1966 1967**Return value** 1968 1969| Type | Description | 1970| :-------------- | :----------------------------------------------------------- | 1971| 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.| 1972 1973**Error codes** 1974 1975| ID| Error Message | 1976| -------- | ------------------------------------------- | 1977| 401 | Parameter error. | 1978| 201 | Permission denied. | 1979| 2300002 | System internal error. | 1980| 2303109 | Bad file number. | 1981| 2303111 | Resource temporarily unavailable try again. | 1982| 2303198 | Address already in use. | 1983| 2303199 | Cannot assign requested address. | 1984 1985**Example** 1986 1987```js 1988import socket from "@ohos.net.socket"; 1989import { BusinessError } from '@ohos.base'; 1990let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 1991let listenAddr: socket.NetAddress = { 1992 address: '192.168.xx.xxx', 1993 port: 8080, 1994 family: 1 1995} 1996tcpServer.listen(listenAddr).then(() => { 1997 console.log('listen success'); 1998}).catch((err: BusinessError) => { 1999 console.log('listen fail'); 2000}); 2001``` 2002 2003### getState<sup>10+</sup> 2004 2005getState(callback: AsyncCallback\<SocketStateBase\>): void 2006 2007Obtains the status of the TCPSocketServer connection. This API uses an asynchronous callback to return the result. 2008 2009> **NOTE** 2010> This API can be called only after **listen** is successfully called. 2011 2012**Required permissions**: ohos.permission.INTERNET 2013 2014**System capability**: SystemCapability.Communication.NetStack 2015 2016**Parameters** 2017 2018| Name | Type | Mandatory| Description | 2019| -------- | -------------------------------------------------- | ---- | ---------- | 2020| callback | AsyncCallback<[SocketStateBase](#socketstatebase7)> | Yes | Callback used to return the result.| 2021 2022**Error codes** 2023 2024| ID| Error Message | 2025| -------- | ------------------------------- | 2026| 401 | Parameter error. | 2027| 201 | Permission denied. | 2028| 2300002 | System internal error. | 2029| 2303188 | Socket operation on non-socket. | 2030 2031**Example** 2032 2033```js 2034import socket from "@ohos.net.socket"; 2035import { BusinessError } from '@ohos.base'; 2036let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 2037let listenAddr: socket.NetAddress = { 2038 address: '192.168.xx.xxx', 2039 port: 8080, 2040 family: 1 2041} 2042tcpServer.listen(listenAddr, (err: BusinessError) => { 2043 if (err) { 2044 console.log("listen fail"); 2045 return; 2046 } 2047 console.log("listen success"); 2048}) 2049tcpServer.getState((err: BusinessError, data: socket.SocketStateBase) => { 2050 if (err) { 2051 console.log('getState fail'); 2052 return; 2053 } 2054 console.log('getState success:' + JSON.stringify(data)); 2055}) 2056``` 2057 2058### getState<sup>10+</sup> 2059 2060getState(): Promise\<SocketStateBase\> 2061 2062Obtains the status of the TCPSocketServer connection. This API uses a promise to return the result. 2063 2064> **NOTE** 2065> This API can be called only after **listen** is successfully called. 2066 2067**Required permissions**: ohos.permission.INTERNET 2068 2069**System capability**: SystemCapability.Communication.NetStack 2070 2071**Return value** 2072 2073| Type | Description | 2074| :------------------------------------------- | :----------------------------------------- | 2075| Promise<[SocketStateBase](#socketstatebase7)> | Promise used to return the result.| 2076 2077**Error codes** 2078 2079| ID| Error Message | 2080| -------- | ------------------------------- | 2081| 201 | Permission denied. | 2082| 2300002 | System internal error. | 2083| 2303188 | Socket operation on non-socket. | 2084 2085**Example** 2086 2087```js 2088import socket from "@ohos.net.socket"; 2089import { BusinessError } from '@ohos.base'; 2090let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 2091let listenAddr: socket.NetAddress = { 2092 address: '192.168.xx.xxx', 2093 port: 8080, 2094 family: 1 2095} 2096tcpServer.listen(listenAddr, (err: BusinessError) => { 2097 if (err) { 2098 console.log("listen fail"); 2099 return; 2100 } 2101 console.log("listen success"); 2102}) 2103tcpServer.getState().then((data: socket.SocketStateBase) => { 2104 console.log('getState success' + JSON.stringify(data)); 2105}).catch((err: BusinessError) => { 2106 console.log('getState fail'); 2107}); 2108``` 2109 2110### setExtraOptions<sup>10+</sup> 2111 2112setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\<void\>): void 2113 2114Sets other properties of the TCPSocketServer connection. This API uses an asynchronous callback to return the result. 2115 2116> **NOTE** 2117> This API can be called only after **listen** is successfully called. 2118 2119**Required permissions**: ohos.permission.INTERNET 2120 2121**System capability**: SystemCapability.Communication.NetStack 2122 2123**Parameters** 2124 2125| Name | Type | Mandatory| Description | 2126| -------- | ----------------------------------- | ---- | ------------------------------------------------------------ | 2127| options | [TCPExtraOptions](#tcpextraoptions7) | Yes | Other properties of the TCPSocketServer connection.| 2128| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | 2129 2130**Error codes** 2131 2132| ID| Error Message | 2133| -------- | ------------------------------- | 2134| 401 | Parameter error. | 2135| 201 | Permission denied. | 2136| 2300002 | System internal error. | 2137| 2303188 | Socket operation on non-socket. | 2138 2139**Example** 2140 2141```js 2142import socket from "@ohos.net.socket"; 2143import { BusinessError } from '@ohos.base'; 2144let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 2145let listenAddr: socket.NetAddress = { 2146 address: '192.168.xx.xxx', 2147 port: 8080, 2148 family: 1 2149} 2150tcpServer.listen(listenAddr, (err: BusinessError) => { 2151 if (err) { 2152 console.log("listen fail"); 2153 return; 2154 } 2155 console.log("listen success"); 2156}) 2157 2158let tcpExtraOptions: socket.TCPExtraOptions = { 2159 keepAlive: true, 2160 OOBInline: true, 2161 TCPNoDelay: true, 2162 socketLinger: { on: true, linger: 10 }, 2163 receiveBufferSize: 1000, 2164 sendBufferSize: 1000, 2165 reuseAddress: true, 2166 socketTimeout: 3000 2167} 2168tcpServer.setExtraOptions(tcpExtraOptions, (err: BusinessError) => { 2169 if (err) { 2170 console.log('setExtraOptions fail'); 2171 return; 2172 } 2173 console.log('setExtraOptions success'); 2174}); 2175``` 2176 2177### setExtraOptions<sup>10+</sup> 2178 2179setExtraOptions(options: TCPExtraOptions): Promise\<void\> 2180 2181Sets other properties of the TCPSocketServer connection. This API uses a promise to return the result. 2182 2183> **NOTE** 2184> This API can be called only after **listen** is successfully called. 2185 2186**Required permissions**: ohos.permission.INTERNET 2187 2188**System capability**: SystemCapability.Communication.NetStack 2189 2190**Parameters** 2191 2192| Name | Type | Mandatory| Description | 2193| ------- | ----------------------------------- | ---- | ------------------------------------------------------------ | 2194| options | [TCPExtraOptions](#tcpextraoptions7) | Yes | Other properties of the TCPSocketServer connection.| 2195 2196**Return value** 2197 2198| Type | Description | 2199| :-------------- | :--------------------------------------------------------- | 2200| 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.| 2201 2202**Error codes** 2203 2204| ID| Error Message | 2205| -------- | ------------------------------- | 2206| 401 | Parameter error. | 2207| 201 | Permission denied. | 2208| 2300002 | System internal error. | 2209| 2303188 | Socket operation on non-socket. | 2210 2211**Example** 2212 2213```js 2214import socket from "@ohos.net.socket"; 2215import { BusinessError } from '@ohos.base'; 2216let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 2217let listenAddr: socket.NetAddress = { 2218 address: '192.168.xx.xxx', 2219 port: 8080, 2220 family: 1 2221} 2222tcpServer.listen(listenAddr, (err: BusinessError) => { 2223 if (err) { 2224 console.log("listen fail"); 2225 return; 2226 } 2227 console.log("listen success"); 2228}) 2229 2230let tcpExtraOptions: socket.TCPExtraOptions = { 2231 keepAlive: true, 2232 OOBInline: true, 2233 TCPNoDelay: true, 2234 socketLinger: { on: true, linger: 10 }, 2235 receiveBufferSize: 1000, 2236 sendBufferSize: 1000, 2237 reuseAddress: true, 2238 socketTimeout: 3000 2239} 2240tcpServer.setExtraOptions(tcpExtraOptions).then(() => { 2241 console.log('setExtraOptions success'); 2242}).catch((err: BusinessError) => { 2243 console.log('setExtraOptions fail'); 2244}); 2245``` 2246 2247### on('connect')<sup>10+</sup> 2248 2249on(type: 'connect', callback: Callback\<TCPSocketConnection\>): void 2250 2251Subscribes to TCPSocketServer connection events. This API uses an asynchronous callback to return the result. 2252 2253> **NOTE** 2254> This API can be called only after **listen** is successfully called. 2255 2256**System capability**: SystemCapability.Communication.NetStack 2257 2258**Parameters** 2259 2260| Name | Type | Mandatory| Description | 2261| -------- | ------------------------------- | ---- | ------------------------------------- | 2262| type | string | Yes | Type of the event to subscribe to.<br/> **connect**: connection event.| 2263| callback | Callback<[TCPSocketConnection](#tcpsocketconnection10)> | Yes | Callback used to return the result. | 2264 2265**Error codes** 2266 2267| ID| Error Message | 2268| -------- | ---------------- | 2269| 401 | Parameter error. | 2270 2271**Example** 2272 2273```js 2274import socket from "@ohos.net.socket"; 2275let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 2276tcpServer.on('connect', (data: socket.TCPSocketConnection) => { 2277 console.log(JSON.stringify(data)) 2278}); 2279``` 2280 2281### off('connect')<sup>10+</sup> 2282 2283off(type: 'connect', callback?: Callback\<TCPSocketConnection\>): void 2284 2285Unsubscribes from TCPSocketServer connection events. This API uses an asynchronous callback to return the result. 2286 2287> **NOTE** 2288> 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. 2289 2290**System capability**: SystemCapability.Communication.NetStack 2291 2292**Parameters** 2293 2294| Name | Type | Mandatory| Description | 2295| -------- | ------------------------------- | ---- | ------------------------------------- | 2296| type | string | Yes | Type of the event to subscribe to.<br/> **connect**: connection event.| 2297| callback | Callback<[TCPSocketConnection](#tcpsocketconnection10)> | No | Callback used to return the result. | 2298 2299**Error codes** 2300 2301| ID| Error Message | 2302| -------- | ---------------- | 2303| 401 | Parameter error. | 2304 2305**Example** 2306 2307```js 2308import socket from "@ohos.net.socket"; 2309let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 2310let callback = (data: socket.TCPSocketConnection) => { 2311 console.log('on connect message: ' + JSON.stringify(data)); 2312} 2313tcpServer.on('connect', callback); 2314// 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. 2315tcpServer.off('connect', callback); 2316tcpServer.off('connect'); 2317``` 2318 2319### on('error')<sup>10+</sup> 2320 2321on(type: 'error', callback: ErrorCallback): void 2322 2323Subscribes to **error** events of the TCPSocketServer connection. This API uses an asynchronous callback to return the result. 2324 2325> **NOTE** 2326> This API can be called only after **listen** is successfully called. 2327 2328**System capability**: SystemCapability.Communication.NetStack 2329 2330**Parameters** 2331 2332| Name | Type | Mandatory| Description | 2333| -------- | ------------- | ---- | ------------------------------------ | 2334| type | string | Yes | Type of the event to subscribe to.<br/> **error**: error event.| 2335| callback | ErrorCallback | Yes | Callback used to return the result. | 2336 2337**Error codes** 2338 2339| ID| Error Message | 2340| -------- | ---------------- | 2341| 401 | Parameter error. | 2342 2343**Example** 2344 2345```js 2346import socket from "@ohos.net.socket"; 2347import { BusinessError } from '@ohos.base'; 2348let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 2349tcpServer.on('error', (err: BusinessError) => { 2350 console.log("on error, err:" + JSON.stringify(err)) 2351}); 2352``` 2353 2354### off('error')<sup>10+</sup> 2355 2356off(type: 'error', callback?: ErrorCallback): void 2357 2358Unsubscribes from **error** events of the TCPSocketServer connection. This API uses an asynchronous callback to return the result. 2359 2360> **NOTE** 2361> 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. 2362 2363**System capability**: SystemCapability.Communication.NetStack 2364 2365**Parameters** 2366 2367| Name | Type | Mandatory| Description | 2368| -------- | ------------- | ---- | ------------------------------------ | 2369| type | string | Yes | Type of the event to subscribe to.<br/> **error**: error event.| 2370| callback | ErrorCallback | No | Callback used to return the result. | 2371 2372**Error codes** 2373 2374| ID| Error Message | 2375| -------- | ---------------- | 2376| 401 | Parameter error. | 2377 2378**Example** 2379 2380```js 2381import socket from "@ohos.net.socket"; 2382import { BusinessError } from '@ohos.base'; 2383let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 2384let callback = (err: BusinessError) => { 2385 console.log("on error, err:" + JSON.stringify(err)); 2386} 2387tcpServer.on('error', callback); 2388// 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. 2389tcpServer.off('error', callback); 2390tcpServer.off('error'); 2391``` 2392 2393## TCPSocketConnection<sup>10+</sup> 2394 2395Defines 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. 2396 2397> **NOTE** 2398> 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. 2399 2400**System capability**: SystemCapability.Communication.NetStack 2401 2402### Attributes 2403 2404| Name | Type | Mandatory| Description | 2405| -------- | ------ | ---- | ----------------------------------------- | 2406| clientId | number | Yes | ID of the connection between the client and TCPSocketServer.| 2407 2408### send<sup>10+</sup> 2409 2410send(options: TCPSendOptions, callback: AsyncCallback\<void\>): void 2411 2412Sends data over a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result. 2413 2414> **NOTE** 2415> This API can be called only after a connection with the client is set up. 2416 2417**Required permissions**: ohos.permission.INTERNET 2418 2419**System capability**: SystemCapability.Communication.NetStack 2420 2421**Parameters** 2422 2423| Name | Type | Mandatory| Description | 2424| -------- | --------------------------------- | ---- | ------------------------------------------------------------ | 2425| options | [TCPSendOptions](#tcpsendoptions7) | Yes | Defines the parameters for sending data over the **TCPSocketConnection** object.| 2426| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. | 2427 2428**Error codes** 2429 2430| ID| Error Message | 2431| -------- | ---------------------- | 2432| 401 | Parameter error. | 2433| 201 | Permission denied. | 2434| 2300002 | System internal error. | 2435 2436**Example** 2437 2438```js 2439import socket from "@ohos.net.socket"; 2440let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 2441 2442tcpServer.on('connect', (client: socket.TCPSocketConnection) => { 2443 let tcpSendOption: socket.TCPSendOptions = { 2444 data: 'Hello, client!' 2445 } 2446 client.send(tcpSendOption, () => { 2447 console.log('send success'); 2448 }); 2449}); 2450``` 2451 2452### send<sup>10+</sup> 2453 2454send(options: TCPSendOptions): Promise\<void\> 2455 2456Sends data over a **TCPSocketConnection** object. This API uses a promise to return the result. 2457 2458> **NOTE** 2459> This API can be called only after a connection with the client is set up. 2460 2461**Required permissions**: ohos.permission.INTERNET 2462 2463**System capability**: SystemCapability.Communication.NetStack 2464 2465**Parameters** 2466 2467| Name | Type | Mandatory| Description | 2468| ------- | --------------------------------- | ---- | ------------------------------------------------------------ | 2469| options | [TCPSendOptions](#tcpsendoptions7) | Yes | Defines the parameters for sending data over the **TCPSocketConnection** object.| 2470 2471**Return value** 2472 2473| Type | Description | 2474| :-------------- | :----------------------------------------------------------- | 2475| 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.| 2476 2477**Error codes** 2478 2479| ID| Error Message | 2480| -------- | ---------------------- | 2481| 401 | Parameter error. | 2482| 201 | Permission denied. | 2483| 2300002 | System internal error. | 2484 2485**Example** 2486 2487```js 2488import socket from "@ohos.net.socket"; 2489import { BusinessError } from '@ohos.base'; 2490let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 2491 2492tcpServer.on('connect', (client: socket.TCPSocketConnection) => { 2493 let tcpSendOption: socket.TCPSendOptions = { 2494 data: 'Hello, client!' 2495 } 2496 client.send(tcpSendOption).then(() => { 2497 console.log('send success'); 2498 }).catch((err: BusinessError) => { 2499 console.log('send fail'); 2500 }); 2501}); 2502``` 2503 2504### close<sup>10+</sup> 2505 2506close(callback: AsyncCallback\<void\>): void 2507 2508Closes a TCP socket connection. This API uses an asynchronous callback to return the result. 2509 2510**Required permissions**: ohos.permission.INTERNET 2511 2512**System capability**: SystemCapability.Communication.NetStack 2513 2514**Parameters** 2515 2516| Name | Type | Mandatory| Description | 2517| -------- | --------------------- | ---- | ---------- | 2518| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.| 2519 2520**Error codes** 2521 2522| ID| Error Message | 2523| -------- | ---------------------- | 2524| 401 | Parameter error. | 2525| 201 | Permission denied. | 2526| 2300002 | System internal error. | 2527 2528**Example** 2529 2530```js 2531import socket from "@ohos.net.socket"; 2532import { BusinessError } from '@ohos.base'; 2533let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 2534 2535tcpServer.on('connect', (client: socket.TCPSocketConnection) => { 2536 client.close((err: BusinessError) => { 2537 if (err) { 2538 console.log('close fail'); 2539 return; 2540 } 2541 console.log('close success'); 2542 }); 2543}); 2544``` 2545 2546### close<sup>10+</sup> 2547 2548close(): Promise\<void\> 2549 2550Closes a TCP socket connection. This API uses a promise to return the result. 2551 2552**Required permissions**: ohos.permission.INTERNET 2553 2554**System capability**: SystemCapability.Communication.NetStack 2555 2556**Return value** 2557 2558| Type | Description | 2559| :-------------- | :------------------------------------------- | 2560| 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.| 2561 2562**Error codes** 2563 2564| ID| Error Message | 2565| -------- | ---------------------- | 2566| 201 | Permission denied. | 2567| 2300002 | System internal error. | 2568 2569**Example** 2570 2571```js 2572import socket from "@ohos.net.socket"; 2573let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 2574tcpServer.on('connect', (client: socket.TCPSocketConnection) => { 2575 client.close().then(() => { 2576 console.log('close success'); 2577 }).catch((err: BusinessError) => { 2578 console.log('close fail'); 2579 }); 2580}); 2581``` 2582 2583### getRemoteAddress<sup>10+</sup> 2584 2585getRemoteAddress(callback: AsyncCallback\<NetAddress\>): void 2586 2587Obtains the remote address of a socket connection. This API uses an asynchronous callback to return the result. 2588 2589> **NOTE** 2590> This API can be called only after a connection with the client is set up. 2591 2592**Required permissions**: ohos.permission.INTERNET 2593 2594**System capability**: SystemCapability.Communication.NetStack 2595 2596**Parameters** 2597 2598| Name | Type | Mandatory| Description | 2599| -------- | ---------------------------------------- | ---- | ---------- | 2600| callback | AsyncCallback<[NetAddress](#netaddress7)> | Yes | Callback used to return the result.| 2601 2602**Error codes** 2603 2604| ID| Error Message | 2605| -------- | ------------------------------- | 2606| 401 | Parameter error. | 2607| 201 | Permission denied. | 2608| 2300002 | System internal error. | 2609| 2303188 | Socket operation on non-socket. | 2610 2611**Example** 2612 2613```js 2614import socket from "@ohos.net.socket"; 2615import { BusinessError } from '@ohos.base'; 2616let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 2617tcpServer.on('connect', (client: socket.TCPSocketConnection) => { 2618 client.getRemoteAddress((err: BusinessError, data: socket.NetAddress) => { 2619 if (err) { 2620 console.log('getRemoteAddress fail'); 2621 return; 2622 } 2623 console.log('getRemoteAddress success:' + JSON.stringify(data)); 2624 }); 2625}); 2626``` 2627 2628### getRemoteAddress<sup>10+</sup> 2629 2630getRemoteAddress(): Promise\<NetAddress\> 2631 2632Obtains the remote address of a socket connection. This API uses a promise to return the result. 2633 2634> **NOTE** 2635> This API can be called only after a connection with the client is set up. 2636 2637**Required permissions**: ohos.permission.INTERNET 2638 2639**System capability**: SystemCapability.Communication.NetStack 2640 2641**Return value** 2642 2643| Type | Description | 2644| :--------------------------------- | :------------------------------------------ | 2645| Promise<[NetAddress](#netaddress7)> | Promise used to return the result.| 2646 2647**Error codes** 2648 2649| ID| Error Message | 2650| -------- | ------------------------------- | 2651| 201 | Permission denied. | 2652| 2300002 | System internal error. | 2653| 2303188 | Socket operation on non-socket. | 2654 2655**Example** 2656 2657```js 2658import socket from "@ohos.net.socket"; 2659import { BusinessError } from '@ohos.base'; 2660let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 2661tcpServer.on('connect', (client: socket.TCPSocketConnection) => { 2662 client.getRemoteAddress().then(() => { 2663 console.log('getRemoteAddress success'); 2664 }).catch((err: BusinessError) => { 2665 console.log('getRemoteAddress fail'); 2666 }); 2667}); 2668``` 2669 2670### on('message')<sup>10+</sup> 2671 2672on(type: 'message', callback: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void 2673 2674Subscribes to **message** events of a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result. 2675 2676**System capability**: SystemCapability.Communication.NetStack 2677 2678**Parameters** 2679 2680| Name | Type | Mandatory| Description | 2681| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 2682| type | string | Yes | Type of the event to subscribe to.<br/> **message**: message receiving event.| 2683| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo7)}> | Yes | Callback used to return the result.<br> **message**: received message.<br>**remoteInfo**: socket connection information. | 2684 2685**Error codes** 2686 2687| ID| Error Message | 2688| -------- | ---------------- | 2689| 401 | Parameter error. | 2690 2691**Example** 2692 2693```js 2694import socket from "@ohos.net.socket"; 2695import { BusinessError } from '@ohos.base'; 2696let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 2697 2698class SocketInfo { 2699 message: ArrayBuffer = new ArrayBuffer(1); 2700 remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 2701} 2702tcpServer.on('connect', (client: socket.TCPSocketConnection) => { 2703 client.on('message', (value: SocketInfo) => { 2704 let messageView = ''; 2705 for (let i: number = 0; i < value.message.byteLength; i++) { 2706 let messages: number = value.message[i] 2707 let message = String.fromCharCode(messages); 2708 messageView += message; 2709 } 2710 console.log('on message message: ' + JSON.stringify(messageView)); 2711 console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo)); 2712 }); 2713}); 2714``` 2715 2716### off('message')<sup>10+</sup> 2717 2718off(type: 'message', callback?: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void 2719 2720Unsubscribes from **message** events of a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result. 2721 2722> **NOTE** 2723> 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. 2724 2725**System capability**: SystemCapability.Communication.NetStack 2726 2727**Parameters** 2728 2729| Name | Type | Mandatory| Description | 2730| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 2731| type | string | Yes | Type of the event to subscribe to.<br/> **message**: message receiving event.| 2732| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo7)}> | No | Callback used to return the result.<br> **message**: received message.<br>**remoteInfo**: socket connection information. | 2733 2734**Error codes** 2735 2736| ID| Error Message | 2737| -------- | ---------------- | 2738| 401 | Parameter error. | 2739 2740**Example** 2741 2742```js 2743import socket from "@ohos.net.socket"; 2744import { BusinessError } from '@ohos.base'; 2745let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 2746class SocketInfo { 2747 message: ArrayBuffer = new ArrayBuffer(1); 2748 remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 2749} 2750let callback = (value: SocketInfo) => { 2751 let messageView = ''; 2752 for (let i: number = 0; i < value.message.byteLength; i++) { 2753 let messages: number = value.message[i] 2754 let message = String.fromCharCode(messages); 2755 messageView += message; 2756 } 2757 console.log('on message message: ' + JSON.stringify(messageView)); 2758 console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo)); 2759} 2760tcpServer.on('connect', (client: socket.TCPSocketConnection) => { 2761 client.on('message', callback); 2762 // 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. 2763 client.off('message', callback); 2764 client.off('message'); 2765}); 2766``` 2767 2768### on('close')<sup>10+</sup> 2769 2770on(type: 'close', callback: Callback\<void\>): void 2771 2772Subscribes to **close** events of a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result. 2773 2774**System capability**: SystemCapability.Communication.NetStack 2775 2776**Parameters** 2777 2778| Name | Type | Mandatory| Description | 2779| -------- | ---------------- | ---- | ----------------------------------- | 2780| type | string | Yes | Type of the event to subscribe to.<br/> **close**: close event.| 2781| callback | Callback\<void\> | Yes | Callback used to return the result. | 2782 2783**Error codes** 2784 2785| ID| Error Message | 2786| -------- | ---------------- | 2787| 401 | Parameter error. | 2788 2789**Example** 2790 2791```js 2792import socket from "@ohos.net.socket"; 2793import { BusinessError } from '@ohos.base'; 2794let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 2795tcpServer.on('connect', (client: socket.TCPSocketConnection) => { 2796 client.on('close', () => { 2797 console.log("on close success") 2798 }); 2799}); 2800``` 2801 2802### off('close')<sup>10+</sup> 2803 2804off(type: 'close', callback?: Callback\<void\>): void 2805 2806Unsubscribes from **close** events of a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result. 2807 2808> **NOTE** 2809> 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. 2810 2811**System capability**: SystemCapability.Communication.NetStack 2812 2813**Parameters** 2814 2815| Name | Type | Mandatory| Description | 2816| -------- | ---------------- | ---- | ----------------------------------- | 2817| type | string | Yes | Type of the event to subscribe to.<br/> **close**: close event.| 2818| callback | Callback\<void\> | No | Callback used to return the result. | 2819 2820**Error codes** 2821 2822| ID| Error Message | 2823| -------- | ---------------- | 2824| 401 | Parameter error. | 2825 2826**Example** 2827 2828```js 2829import socket from "@ohos.net.socket"; 2830let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 2831let callback = () => { 2832 console.log("on close success"); 2833} 2834tcpServer.on('connect', (client: socket.TCPSocketConnection) => { 2835 client.on('close', callback); 2836 // 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. 2837 client.off('close', callback); 2838 client.off('close'); 2839}); 2840``` 2841 2842### on('error')<sup>10+</sup> 2843 2844on(type: 'error', callback: ErrorCallback): void 2845 2846Subscribes to **error** events of a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result. 2847 2848**System capability**: SystemCapability.Communication.NetStack 2849 2850**Parameters** 2851 2852| Name | Type | Mandatory| Description | 2853| -------- | ------------- | ---- | ------------------------------------ | 2854| type | string | Yes | Type of the event to subscribe to.<br/> **error**: error event.| 2855| callback | ErrorCallback | Yes | Callback used to return the result. | 2856 2857**Error codes** 2858 2859| ID| Error Message | 2860| -------- | ---------------- | 2861| 401 | Parameter error. | 2862 2863**Example** 2864 2865```js 2866import socket from "@ohos.net.socket"; 2867import { BusinessError } from '@ohos.base'; 2868let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 2869tcpServer.on('connect', (client: socket.TCPSocketConnection) => { 2870 client.on('error', (err: BusinessError) => { 2871 console.log("on error, err:" + JSON.stringify(err)) 2872 }); 2873}); 2874``` 2875 2876### off('error')<sup>10+</sup> 2877 2878off(type: 'error', callback?: ErrorCallback): void 2879 2880Unsubscribes from **error** events of a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result. 2881 2882> **NOTE** 2883> 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. 2884 2885**System capability**: SystemCapability.Communication.NetStack 2886 2887**Parameters** 2888 2889| Name | Type | Mandatory| Description | 2890| -------- | ------------- | ---- | ------------------------------------ | 2891| type | string | Yes | Type of the event to subscribe to.<br/> **error**: error event.| 2892| callback | ErrorCallback | No | Callback used to return the result. | 2893 2894**Error codes** 2895 2896| ID| Error Message | 2897| -------- | ---------------- | 2898| 401 | Parameter error. | 2899 2900**Example** 2901 2902```js 2903import socket from "@ohos.net.socket"; 2904import { BusinessError } from '@ohos.base'; 2905let callback = (err: BusinessError) => { 2906 console.log("on error, err:" + JSON.stringify(err)); 2907} 2908let tcpServer: socket = socket.constructTCPSocketServerInstance(); 2909tcpServer.on('connect', (client: socket.TCPSocketConnection) => { 2910 client.on('error', callback); 2911 // 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. 2912 client.off('error', callback); 2913 client.off('error'); 2914}); 2915``` 2916 2917## Description of TCP Error Codes 2918 2919The TCP error code mapping is in the format of 2301000 + Linux kernel error code. 2920 2921For details about error codes, see [Socket Error Codes](../errorcodes/errorcode-net-socket.md). 2922 2923## socket.constructTLSSocketInstance<sup>9+</sup> 2924 2925constructTLSSocketInstance(): TLSSocket 2926 2927Creates a **TLSSocket** object. 2928 2929**System capability**: SystemCapability.Communication.NetStack 2930 2931**Return value** 2932 2933| Type | Description | 2934| :--------------------------------- | :---------------------- | 2935| [TLSSocket](#tlssocket9) | **TLSSocket** object.| 2936 2937**Example** 2938 2939```js 2940import socket from "@ohos.net.socket"; 2941let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 2942``` 2943 2944## TLSSocket<sup>9+</sup> 2945 2946Defines a TLS socket connection. Before calling TLSSocket APIs, you need to call [socket.constructTLSSocketInstance](#socketconstructtlssocketinstance9) to create a **TLSSocket** object. 2947 2948### bind<sup>9+</sup> 2949 2950bind(address: NetAddress, callback: AsyncCallback\<void\>): void 2951 2952Binds the IP address and port number. This API uses an asynchronous callback to return the result. 2953 2954**Required permissions**: ohos.permission.INTERNET 2955 2956**System capability**: SystemCapability.Communication.NetStack 2957 2958**Parameters** 2959 2960| Name | Type | Mandatory| Description | 2961| -------- | ---------------------------------- | ---- | ------------------------------------------------------ | 2962| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| 2963| 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.| 2964 2965**Error codes** 2966 2967| ID| Error Message | 2968| ------- | ----------------------- | 2969| 401 | Parameter error. | 2970| 201 | Permission denied. | 2971| 2303198 | Address already in use. | 2972| 2300002 | System internal error. | 2973 2974**Example** 2975 2976```js 2977import socket from "@ohos.net.socket"; 2978import { BusinessError } from '@ohos.base'; 2979let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 2980let bindAddr: socket.NetAddress = { 2981 address: '192.168.xx.xxx', 2982 port: 8080 2983} 2984tls.bind(bindAddr, (err: BusinessError) => { 2985 if (err) { 2986 console.log('bind fail'); 2987 return; 2988 } 2989 console.log('bind success'); 2990}); 2991``` 2992 2993### bind<sup>9+</sup> 2994 2995bind(address: NetAddress): Promise\<void\> 2996 2997Binds the IP address and port number. This API uses a promise to return the result. 2998 2999**Required permissions**: ohos.permission.INTERNET 3000 3001**System capability**: SystemCapability.Communication.NetStack 3002 3003**Parameters** 3004 3005| Name | Type | Mandatory| Description | 3006| ------- | ---------------------------------- | ---- | ------------------------------------------------------ | 3007| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| 3008 3009**Return value** 3010 3011| Type | Description | 3012| :-------------- | :------------------------------------------------------- | 3013| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.| 3014 3015**Error codes** 3016 3017| ID| Error Message | 3018| ------- | ----------------------- | 3019| 401 | Parameter error. | 3020| 201 | Permission denied. | 3021| 2303198 | Address already in use. | 3022| 2300002 | System internal error. | 3023 3024**Example** 3025 3026```js 3027import socket from "@ohos.net.socket"; 3028import { BusinessError } from '@ohos.base'; 3029let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 3030let bindAddr: socket.NetAddress = { 3031 address: '192.168.xx.xxx', 3032 port: 8080 3033} 3034tls.bind(bindAddr).then(() => { 3035 console.log('bind success'); 3036}).catch((err: BusinessError) => { 3037 console.log('bind fail'); 3038}); 3039``` 3040 3041### getState<sup>9+</sup> 3042 3043getState(callback: AsyncCallback\<SocketStateBase\>): void 3044 3045Obtains the status of the TLS socket connection. This API uses an asynchronous callback to return the result. 3046 3047**System capability**: SystemCapability.Communication.NetStack 3048 3049**Parameters** 3050 3051| Name | Type | Mandatory| Description | 3052| -------- | ------------------------------------------------------ | ---- | ---------- | 3053| 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.| 3054 3055**Error codes** 3056 3057| ID| Error Message | 3058| ------- | ------------------------------ | 3059| 2303188 | Socket operation on non-socket.| 3060| 2300002 | System internal error. | 3061 3062**Example** 3063 3064```js 3065import socket from "@ohos.net.socket"; 3066import { BusinessError } from '@ohos.base'; 3067let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 3068let bindAddr: socket.NetAddress = { 3069 address: '192.168.xx.xxx', 3070 port: 8080 3071} 3072tls.bind(bindAddr, (err: BusinessError) => { 3073 if (err) { 3074 console.log('bind fail'); 3075 return; 3076 } 3077 console.log('bind success'); 3078}); 3079tls.getState((err: BusinessError, data: socket.SocketStateBase) => { 3080 if (err) { 3081 console.log('getState fail'); 3082 return; 3083 } 3084 console.log('getState success:' + JSON.stringify(data)); 3085}); 3086``` 3087 3088### getState<sup>9+</sup> 3089 3090getState(): Promise\<SocketStateBase\> 3091 3092Obtains the status of the TLS socket connection. This API uses a promise to return the result. 3093 3094**System capability**: SystemCapability.Communication.NetStack 3095 3096**Return value** 3097 3098| Type | Description | 3099| :----------------------------------------------- | :----------------------------------------- | 3100| Promise\<[SocketStateBase](#socketstatebase)> | Promise used to return the result. If the operation fails, an error message is returned.| 3101 3102**Error codes** 3103 3104| ID| Error Message | 3105| ------- | ------------------------------ | 3106| 2303188 | Socket operation on non-socket.| 3107| 2300002 | System internal error. | 3108 3109**Example** 3110 3111```js 3112import socket from "@ohos.net.socket"; 3113import { BusinessError } from '@ohos.base'; 3114let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 3115let bindAddr: socket.NetAddress = { 3116 address: '192.168.xx.xxx', 3117 port: 8080 3118} 3119tls.bind(bindAddr, (err: BusinessError) => { 3120 if (err) { 3121 console.log('bind fail'); 3122 return; 3123 } 3124 console.log('bind success'); 3125}); 3126tls.getState().then(() => { 3127 console.log('getState success'); 3128}).catch((err: BusinessError) => { 3129 console.log('getState fail'); 3130}); 3131``` 3132 3133### setExtraOptions<sup>9+</sup> 3134 3135setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\<void\>): void 3136 3137Sets other properties of the TCP socket connection after **bind** is successfully called. This API uses an asynchronous callback to return the result. 3138 3139**System capability**: SystemCapability.Communication.NetStack 3140 3141**Parameters** 3142 3143| Name | Type | Mandatory| Description | 3144| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | 3145| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCP socket connection. For details, see [TCPExtraOptions](#tcpextraoptions).| 3146| 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.| 3147 3148**Error codes** 3149 3150| ID| Error Message | 3151| ------- | ----------------------------- | 3152| 401 | Parameter error. | 3153| 2303188 | Socket operation on non-socket.| 3154| 2300002 | System internal error. | 3155 3156**Example** 3157 3158```js 3159import socket from "@ohos.net.socket"; 3160import { BusinessError } from '@ohos.base'; 3161let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 3162let bindAddr: socket.NetAddress = { 3163 address: '192.168.xx.xxx', 3164 port: 8080 3165} 3166tls.bind(bindAddr, (err: BusinessError) => { 3167 if (err) { 3168 console.log('bind fail'); 3169 return; 3170 } 3171 console.log('bind success'); 3172}); 3173 3174let tcpExtraOptions: socket.TCPExtraOptions = { 3175 keepAlive: true, 3176 OOBInline: true, 3177 TCPNoDelay: true, 3178 socketLinger: { on: true, linger: 10 }, 3179 receiveBufferSize: 1000, 3180 sendBufferSize: 1000, 3181 reuseAddress: true, 3182 socketTimeout: 3000 3183} 3184tls.setExtraOptions(tcpExtraOptions, (err: BusinessError) => { 3185 if (err) { 3186 console.log('setExtraOptions fail'); 3187 return; 3188 } 3189 console.log('setExtraOptions success'); 3190}); 3191``` 3192 3193### setExtraOptions<sup>9+</sup> 3194 3195setExtraOptions(options: TCPExtraOptions): Promise\<void\> 3196 3197Sets other properties of the TCP socket connection after **bind** is successfully called. This API uses a promise to return the result. 3198 3199**System capability**: SystemCapability.Communication.NetStack 3200 3201**Parameters** 3202 3203| Name | Type | Mandatory| Description | 3204| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | 3205| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCP socket connection. For details, see [TCPExtraOptions](#tcpextraoptions).| 3206 3207**Return value** 3208 3209| Type | Description | 3210| :-------------- | :--------------------------------------------------- | 3211| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.| 3212 3213**Error codes** 3214 3215| ID| Error Message | 3216| ------- | ------------------------------ | 3217| 401 | Parameter error. | 3218| 2303188 | Socket operation on non-socket.| 3219| 2300002 | System internal error. | 3220 3221**Example** 3222 3223```js 3224import socket from "@ohos.net.socket"; 3225import { BusinessError } from '@ohos.base'; 3226let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 3227let bindAddr: socket.NetAddress = { 3228 address: '192.168.xx.xxx', 3229 port: 8080 3230} 3231tls.bind(bindAddr, (err: BusinessError) => { 3232 if (err) { 3233 console.log('bind fail'); 3234 return; 3235 } 3236 console.log('bind success'); 3237}); 3238 3239let tcpExtraOptions: socket.TCPExtraOptions = { 3240 keepAlive: true, 3241 OOBInline: true, 3242 TCPNoDelay: true, 3243 socketLinger: { on: true, linger: 10 }, 3244 receiveBufferSize: 1000, 3245 sendBufferSize: 1000, 3246 reuseAddress: true, 3247 socketTimeout: 3000 3248} 3249tls.setExtraOptions(tcpExtraOptions).then(() => { 3250 console.log('setExtraOptions success'); 3251}).catch((err: BusinessError) => { 3252 console.log('setExtraOptions fail'); 3253}); 3254``` 3255 3256### on('message')<sup>9+</sup> 3257 3258on(type: 'message', callback: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}>): void; 3259 3260Subscribes to **message** events of the TLS socket connection. This API uses an asynchronous callback to return the result. 3261 3262**System capability**: SystemCapability.Communication.NetStack 3263 3264**Parameters** 3265 3266| Name | Type | Mandatory| Description | 3267| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 3268| type | string | Yes | Type of the event to subscribe to.<br/> **message**: message receiving event.| 3269| callback | Callback\<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}\> | Yes | Callback used to return the result.<br> **message**: received message.<br>**remoteInfo**: socket connection information.| 3270 3271**Example** 3272 3273```js 3274import socket from "@ohos.net.socket"; 3275import { BusinessError } from '@ohos.base'; 3276let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 3277class SocketInfo { 3278 message: ArrayBuffer = new ArrayBuffer(1); 3279 remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 3280} 3281let messageView = ''; 3282tls.on('message', (value: SocketInfo) => { 3283 for (let i: number = 0; i < value.message.byteLength; i++) { 3284 let messages: number = value.message[i] 3285 let message = String.fromCharCode(messages); 3286 messageView += message; 3287 } 3288 console.log('on message message: ' + JSON.stringify(messageView)); 3289 console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo)); 3290}); 3291``` 3292 3293### off('message')<sup>9+</sup> 3294 3295off(type: 'message', callback?: Callback\<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void 3296 3297Unsubscribes from **message** events of the TLS socket connection. This API uses an asynchronous callback to return the result. 3298 3299> **NOTE** 3300> 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. 3301 3302**System capability**: SystemCapability.Communication.NetStack 3303 3304**Parameters** 3305 3306| Name | Type | Mandatory| Description | 3307| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 3308| type | string | Yes | Type of the event to subscribe to.<br/> **message**: message receiving event.| 3309| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No | Callback used to return the result.<br> **message**: received message.<br>**remoteInfo**: socket connection information.| 3310 3311**Example** 3312 3313```js 3314import socket from "@ohos.net.socket"; 3315import { BusinessError } from '@ohos.base'; 3316let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 3317class SocketInfo { 3318 message: ArrayBuffer = new ArrayBuffer(1); 3319 remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 3320} 3321let messageView = ''; 3322let callback = (value: SocketInfo) => { 3323 for (let i: number = 0; i < value.message.byteLength; i++) { 3324 let messages: number = value.message[i] 3325 let message = String.fromCharCode(messages); 3326 messageView += message; 3327 } 3328 console.log('on message message: ' + JSON.stringify(messageView)); 3329 console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo)); 3330} 3331tls.on('message', callback); 3332// 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. 3333tls.off('message', callback); 3334``` 3335### on('connect' | 'close')<sup>9+</sup> 3336 3337on(type: 'connect' | 'close', callback: Callback\<void\>): void 3338 3339Subscribes to **connect** or **close** events of the TLS socket connection. This API uses an asynchronous callback to return the result. 3340 3341**System capability**: SystemCapability.Communication.NetStack 3342 3343**Parameters** 3344 3345| Name | Type | Mandatory| Description | 3346| -------- | ---------------- | ---- | ------------------------------------------------------------ | 3347| type | string | Yes | Type of the event to subscribe to.<br>- **connect**: connection event.<br>- **close**: close event.| 3348| callback | Callback\<void\> | Yes | Callback used to return the result. | 3349 3350**Example** 3351 3352```js 3353import socket from "@ohos.net.socket"; 3354import { BusinessError } from '@ohos.base'; 3355let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 3356tls.on('connect', () => { 3357 console.log("on connect success") 3358}); 3359tls.on('close', () => { 3360 console.log("on close success") 3361}); 3362``` 3363 3364### off('connect' | 'close')<sup>9+</sup> 3365 3366off(type: 'connect' | 'close', callback?: Callback\<void\>): void 3367 3368Unsubscribes from **connect** or **close** events of the TLS socket connection. This API uses an asynchronous callback to return the result. 3369 3370> **NOTE** 3371> 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. 3372 3373**System capability**: SystemCapability.Communication.NetStack 3374 3375**Parameters** 3376 3377| Name | Type | Mandatory| Description | 3378| -------- | ---------------- | ---- | ------------------------------------------------------------ | 3379| type | string | Yes | Type of the event to subscribe to.<br>- **connect**: connection event.<br>- **close**: close event.| 3380| callback | Callback\<void\> | No | Callback used to return the result. | 3381 3382**Example** 3383 3384```js 3385import socket from "@ohos.net.socket"; 3386import { BusinessError } from '@ohos.base'; 3387let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 3388let callback1 = () => { 3389 console.log("on connect success"); 3390} 3391tls.on('connect', callback1); 3392// 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. 3393tls.off('connect', callback1); 3394tls.off('connect'); 3395let callback2 = () => { 3396 console.log("on close success"); 3397} 3398tls.on('close', callback2); 3399// 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. 3400tls.off('close', callback2); 3401``` 3402 3403### on('error')<sup>9+</sup> 3404 3405on(type: 'error', callback: ErrorCallback): void 3406 3407Subscribes to **error** events of the TLS socket connection. This API uses an asynchronous callback to return the result. 3408 3409**System capability**: SystemCapability.Communication.NetStack 3410 3411**Parameters** 3412 3413| Name | Type | Mandatory| Description | 3414| -------- | ------------- | ---- | ------------------------------------ | 3415| type | string | Yes | Type of the event to subscribe to.<br/> **error**: error event.| 3416| callback | ErrorCallback | Yes | Callback used to return the result. | 3417 3418**Example** 3419 3420```js 3421import socket from "@ohos.net.socket"; 3422import { BusinessError } from '@ohos.base'; 3423let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 3424tls.on('error', (err: BusinessError) => { 3425 console.log("on error, err:" + JSON.stringify(err)) 3426}); 3427``` 3428 3429### off('error')<sup>9+</sup> 3430 3431off(type: 'error', callback?: ErrorCallback): void 3432 3433Unsubscribes from **error** events of the TLS socket connection. This API uses an asynchronous callback to return the result. 3434 3435> **NOTE** 3436> 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. 3437 3438**System capability**: SystemCapability.Communication.NetStack 3439 3440**Parameters** 3441 3442| Name | Type | Mandatory| Description | 3443| -------- | ------------- | ---- | ------------------------------------ | 3444| type | string | Yes | Type of the event to subscribe to.<br/> **error**: error event.| 3445| callback | ErrorCallback | No | Callback used to return the result. | 3446 3447**Example** 3448 3449```js 3450import socket from "@ohos.net.socket"; 3451import { BusinessError } from '@ohos.base'; 3452let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 3453let callback = (err: BusinessError) => { 3454 console.log("on error, err:" + JSON.stringify(err)); 3455} 3456tls.on('error', callback); 3457// 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. 3458tls.off('error', callback); 3459``` 3460 3461### connect<sup>9+</sup> 3462 3463connect(options: TLSConnectOptions, callback: AsyncCallback\<void\>): void 3464 3465Sets 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. 3466 3467**System capability**: SystemCapability.Communication.NetStack 3468 3469**Parameters** 3470 3471| Name | Type | Mandatory| Description| 3472| -------- | ---------------------------------------| ----| --------------- | 3473| options | [TLSConnectOptions](#tlsconnectoptions9) | Yes | Parameters required for the TLS socket connection.| 3474| 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.| 3475 3476**Error codes** 3477 3478| ID| Error Message | 3479| ------- | -------------------------------------------- | 3480| 401 | Parameter error. | 3481| 2303104 | Interrupted system call. | 3482| 2303109 | Bad file number. | 3483| 2303111 | Resource temporarily unavailable try again. | 3484| 2303188 | Socket operation on non-socket. | 3485| 2303191 | Protocol wrong type for socket. | 3486| 2303198 | Address already in use. | 3487| 2303199 | Cannot assign requested address. | 3488| 2303210 | Connection timed out. | 3489| 2303501 | SSL is null. | 3490| 2303502 | Error in tls reading. | 3491| 2303503 | Error in tls writing | 3492| 2303505 | Error occurred in the tls system call. | 3493| 2303506 | Error clearing tls connection. | 3494| 2300002 | System internal error. | 3495 3496**Example** 3497 3498```js 3499import socket from "@ohos.net.socket"; 3500import { BusinessError } from '@ohos.base'; 3501let tlsTwoWay: socket.TLSSocket = socket.constructTLSSocketInstance(); // Two way authentication 3502let bindAddr: socket.NetAddress = { 3503 address: '0.0.0.0', 3504} 3505tlsTwoWay.bind(bindAddr, (err: BusinessError) => { 3506 if (err) { 3507 console.log('bind fail'); 3508 return; 3509 } 3510 console.log('bind success'); 3511}); 3512 3513let tlsConnectOptions: socket.TLSConnectOptions = { 3514 address: { 3515 address: '192.168.xx.xxx', 3516 port: 8080 3517 }, 3518 secureOptions: { 3519 key: "xxxx", 3520 cert: "xxxx", 3521 ca: ["xxxx"], 3522 password: "xxxx", 3523 protocols: socket.Protocol.TLSv12, 3524 useRemoteCipherPrefer: true, 3525 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 3526 cipherSuite: "AES256-SHA256" 3527 }, 3528 ALPNProtocols: ["spdy/1", "http/1.1"] 3529} 3530 3531tlsTwoWay.connect(tlsConnectOptions, (err: BusinessError) => { 3532 console.error("connect callback error" + err); 3533}); 3534 3535let tlsOneWay: socket.TLSSocket = socket.constructTLSSocketInstance(); // One way authentication 3536tlsOneWay.bind(bindAddr, (err: BusinessError) => { 3537 if (err) { 3538 console.log('bind fail'); 3539 return; 3540 } 3541 console.log('bind success'); 3542}); 3543 3544let tlsOneWayConnectOptions: socket.TLSConnectOptions = { 3545 address: { 3546 address: '192.168.xx.xxx', 3547 port: 8080 3548 }, 3549 secureOptions: { 3550 ca: ["xxxx", "xxxx"], 3551 cipherSuite: "AES256-SHA256" 3552 } 3553} 3554tlsOneWay.connect(tlsOneWayConnectOptions, (err: BusinessError) => { 3555 console.error("connect callback error" + err); 3556}); 3557``` 3558 3559### connect<sup>9+</sup> 3560 3561connect(options: TLSConnectOptions): Promise\<void\> 3562 3563Sets 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. 3564 3565**System capability**: SystemCapability.Communication.NetStack 3566 3567**Parameters** 3568 3569| Name | Type | Mandatory| Description| 3570| -------- | --------------------------------------| ----| --------------- | 3571| options | [TLSConnectOptions](#tlsconnectoptions9) | Yes | Parameters required for the connection.| 3572 3573**Return value** 3574 3575| Type | Description | 3576| ------------------------------------------- | ----------------------------- | 3577| 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.| 3578 3579**Error codes** 3580 3581| ID| Error Message | 3582| ------- | -------------------------------------------- | 3583| 401 | Parameter error. | 3584| 2303104 | Interrupted system call. | 3585| 2303109 | Bad file number. | 3586| 2303111 | Resource temporarily unavailable try again. | 3587| 2303188 | Socket operation on non-socket. | 3588| 2303191 | Protocol wrong type for socket. | 3589| 2303198 | Address already in use. | 3590| 2303199 | Cannot assign requested address. | 3591| 2303210 | Connection timed out. | 3592| 2303501 | SSL is null. | 3593| 2303502 | Error in tls reading. | 3594| 2303503 | Error in tls writing | 3595| 2303505 | Error occurred in the tls system call. | 3596| 2303506 | Error clearing tls connection. | 3597| 2300002 | System internal error. | 3598 3599**Example** 3600 3601```js 3602import socket from "@ohos.net.socket"; 3603import { BusinessError } from '@ohos.base'; 3604let tlsTwoWay: socket.TLSSocket = socket.constructTLSSocketInstance(); // Two way authentication 3605let bindAddr: socket.NetAddress = { 3606 address: '0.0.0.0', 3607} 3608tlsTwoWay.bind(bindAddr, (err: BusinessError) => { 3609 if (err) { 3610 console.log('bind fail'); 3611 return; 3612 } 3613 console.log('bind success'); 3614}); 3615 3616let tlsConnectOptions: socket.TLSConnectOptions = { 3617 address: { 3618 address: '192.168.xx.xxx', 3619 port: 8080 3620 }, 3621 secureOptions: { 3622 key: "xxxx", 3623 cert: "xxxx", 3624 ca: ["xxxx"], 3625 password: "xxxx", 3626 protocols: socket.Protocol.TLSv12, 3627 useRemoteCipherPrefer: true, 3628 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 3629 cipherSuite: "AES256-SHA256" 3630 }, 3631 ALPNProtocols: ["spdy/1", "http/1.1"] 3632} 3633 3634tlsTwoWay.connect(tlsConnectOptions).then(() => { 3635 console.log("connect successfully"); 3636}).catch((err: BusinessError) => { 3637 console.log("connect failed " + JSON.stringify(err)); 3638}); 3639 3640let tlsOneWay: socket.TLSSocket = socket.constructTLSSocketInstance(); // One way authentication 3641tlsOneWay.bind(bindAddr, (err: BusinessError) => { 3642 if (err) { 3643 console.log('bind fail'); 3644 return; 3645 } 3646 console.log('bind success'); 3647}); 3648 3649let tlsOneWayConnectOptions: socket.TLSConnectOptions = { 3650 address: { 3651 address: '192.168.xx.xxx', 3652 port: 8080 3653 }, 3654 secureOptions: { 3655 ca: ["xxxx", "xxxx"], 3656 cipherSuite: "AES256-SHA256" 3657 } 3658} 3659tlsOneWay.connect(tlsOneWayConnectOptions).then(() => { 3660 console.log("connect successfully"); 3661}).catch((err: BusinessError) => { 3662 console.log("connect failed " + JSON.stringify(err)); 3663}); 3664``` 3665 3666### getRemoteAddress<sup>9+</sup> 3667 3668getRemoteAddress(callback: AsyncCallback\<NetAddress\>): void 3669 3670Obtains the remote address of a TLS socket connection. This API uses an asynchronous callback to return the result. 3671 3672**System capability**: SystemCapability.Communication.NetStack 3673 3674**Parameters** 3675 3676| Name | Type | Mandatory| Description | 3677| -------- | ------------------------------------------------- | ---- | ---------- | 3678| 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.| 3679 3680**Error codes** 3681 3682| ID| Error Message | 3683| ------- | ----------------------------- | 3684| 2303188 | Socket operation on non-socket.| 3685| 2300002 | System internal error. | 3686 3687**Example** 3688 3689```js 3690import socket from "@ohos.net.socket"; 3691import { BusinessError } from '@ohos.base'; 3692let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 3693tls.getRemoteAddress((err: BusinessError, data: socket.NetAddress) => { 3694 if (err) { 3695 console.log('getRemoteAddress fail'); 3696 return; 3697 } 3698 console.log('getRemoteAddress success:' + JSON.stringify(data)); 3699}); 3700``` 3701 3702### getRemoteAddress<sup>9+</sup> 3703 3704getRemoteAddress(): Promise\<NetAddress\> 3705 3706Obtains the remote address of a TLS socket connection. This API uses a promise to return the result. 3707 3708**System capability**: SystemCapability.Communication.NetStack 3709 3710**Return value** 3711 3712| Type | Description | 3713| :------------------------------------------ | :------------------------------------------ | 3714| Promise\<[NetAddress](#netaddress)> | Promise used to return the result. If the operation fails, an error message is returned.| 3715 3716**Error codes** 3717 3718| ID| Error Message | 3719| ------- | ------------------------------ | 3720| 2303188 | Socket operation on non-socket.| 3721| 2300002 | System internal error. | 3722 3723**Example** 3724 3725```js 3726import socket from "@ohos.net.socket"; 3727import { BusinessError } from '@ohos.base'; 3728let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 3729tls.getRemoteAddress().then(() => { 3730 console.log('getRemoteAddress success'); 3731}).catch((err: BusinessError) => { 3732 console.log('getRemoteAddress fail'); 3733}); 3734``` 3735 3736### getCertificate<sup>9+</sup> 3737 3738getCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)\>): void 3739 3740Obtains 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. 3741 3742**System capability**: SystemCapability.Communication.NetStack 3743 3744**Parameters** 3745 3746| Name | Type | Mandatory| Description| 3747| -------- | ----------------------------------------| ---- | ---------------| 3748| 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.| 3749 3750**Error codes** 3751 3752| ID| Error Message | 3753| ------- | ------------------------------ | 3754| 2303501 | SSL is null. | 3755| 2303504 | Error looking up x509. | 3756| 2300002 | System internal error. | 3757 3758**Example** 3759 3760```js 3761import socket from "@ohos.net.socket"; 3762import { BusinessError } from '@ohos.base'; 3763let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 3764tls.getCertificate((err: BusinessError, data: socket.X509CertRawData) => { 3765 if (err) { 3766 console.log("getCertificate callback error = " + err); 3767 } else { 3768 console.log("getCertificate callback = " + data); 3769 } 3770}); 3771``` 3772 3773### getCertificate<sup>9+</sup> 3774 3775getCertificate():Promise\<[X509CertRawData](#x509certrawdata9)\> 3776 3777Obtains 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. 3778 3779**System capability**: SystemCapability.Communication.NetStack 3780 3781**Return value** 3782 3783| Type | Description | 3784| -------------- | -------------------- | 3785| Promise\<[X509CertRawData](#x509certrawdata9)\> | Promise used to return the result. If the operation fails, an error message is returned.| 3786 3787**Error codes** 3788 3789| ID| Error Message | 3790| ------- | ------------------------------ | 3791| 2303501 | SSL is null. | 3792| 2303504 | Error looking up x509. | 3793| 2300002 | System internal error. | 3794 3795**Example** 3796 3797```js 3798import socket from "@ohos.net.socket"; 3799import { BusinessError } from '@ohos.base'; 3800let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 3801tls.getCertificate().then((data: socket.X509CertRawData) => { 3802 console.log(data); 3803}).catch((err: BusinessError) => { 3804 console.error("failed" + err); 3805}); 3806``` 3807 3808### getRemoteCertificate<sup>9+</sup> 3809 3810getRemoteCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)\>): void 3811 3812Obtains the digital certificate of the server after a TLS socket connection is established. This API uses an asynchronous callback to return the result. 3813 3814**System capability**: SystemCapability.Communication.NetStack 3815 3816**Parameters** 3817 3818| Name | Type | Mandatory | Description | 3819| -------- | ----------------------------------------| ---- | ---------------| 3820| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| 3821 3822**Error codes** 3823 3824| ID| Error Message | 3825| ------- | ------------------------------ | 3826| 2303501 | SSL is null. | 3827| 2300002 | System internal error. | 3828 3829**Example** 3830 3831```js 3832import socket from "@ohos.net.socket"; 3833import { BusinessError } from '@ohos.base'; 3834let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 3835tls.getRemoteCertificate((err: BusinessError, data: socket.X509CertRawData) => { 3836 if (err) { 3837 console.log("getRemoteCertificate callback error = " + err); 3838 } else { 3839 console.log("getRemoteCertificate callback = " + data); 3840 } 3841}); 3842``` 3843 3844### getRemoteCertificate<sup>9+</sup> 3845 3846getRemoteCertificate():Promise\<[X509CertRawData](#x509certrawdata9)\> 3847 3848Obtains the digital certificate of the server after a TLS socket connection is established. This API uses a promise to return the result. 3849 3850**System capability**: SystemCapability.Communication.NetStack 3851 3852**Return value** 3853 3854| Type | Description | 3855| -------------- | -------------------- | 3856| Promise\<[X509CertRawData](#x509certrawdata9)\> | Promise used to return the result. If the operation fails, an error message is returned.| 3857 3858**Error codes** 3859 3860| ID| Error Message | 3861| ------- | ------------------------------ | 3862| 2303501 | SSL is null. | 3863| 2300002 | System internal error. | 3864 3865**Example** 3866 3867```js 3868import socket from "@ohos.net.socket"; 3869import { BusinessError } from '@ohos.base'; 3870let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 3871tls.getRemoteCertificate().then((data: socket.X509CertRawData) => { 3872 console.log(data); 3873}).catch((err: BusinessError) => { 3874 console.error("failed" + err); 3875}); 3876``` 3877 3878### getProtocol<sup>9+</sup> 3879 3880getProtocol(callback: AsyncCallback\<string\>): void 3881 3882Obtains the communication protocol version after a TLS socket connection is established. This API uses an asynchronous callback to return the result. 3883 3884**System capability**: SystemCapability.Communication.NetStack 3885 3886**Parameters** 3887 3888| Name | Type | Mandatory| Description | 3889| -------- | ----------------------------------------| ---- | ---------------| 3890| callback | AsyncCallback\<string\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| 3891 3892**Error codes** 3893 3894| ID| Error Message | 3895| ------- | ----------------------------- | 3896| 2303501 | SSL is null. | 3897| 2303505 | Error occurred in the tls system call. | 3898| 2300002 | System internal error. | 3899 3900**Example** 3901 3902```js 3903import socket from "@ohos.net.socket"; 3904import { BusinessError } from '@ohos.base'; 3905let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 3906tls.getProtocol((err: BusinessError, data: string) => { 3907 if (err) { 3908 console.log("getProtocol callback error = " + err); 3909 } else { 3910 console.log("getProtocol callback = " + data); 3911 } 3912}); 3913``` 3914 3915### getProtocol<sup>9+</sup> 3916 3917getProtocol():Promise\<string\> 3918 3919Obtains the communication protocol version after a TLS socket connection is established. This API uses a promise to return the result. 3920 3921**System capability**: SystemCapability.Communication.NetStack 3922 3923**Return value** 3924 3925| Type | Description | 3926| -------------- | -------------------- | 3927| Promise\<string\> | Promise used to return the result. If the operation fails, an error message is returned.| 3928 3929**Error codes** 3930 3931| ID| Error Message | 3932| ------- | ------------------------------ | 3933| 2303501 | SSL is null. | 3934| 2303505 | Error occurred in the tls system call. | 3935| 2300002 | System internal error. | 3936 3937**Example** 3938 3939```js 3940import socket from "@ohos.net.socket"; 3941import { BusinessError } from '@ohos.base'; 3942let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 3943tls.getProtocol().then((data: string) => { 3944 console.log(data); 3945}).catch((err: BusinessError) => { 3946 console.error("failed" + err); 3947}); 3948``` 3949 3950### getCipherSuite<sup>9+</sup> 3951 3952getCipherSuite(callback: AsyncCallback\<Array\<string\>\>): void 3953 3954Obtains 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. 3955 3956**System capability**: SystemCapability.Communication.NetStack 3957 3958**Parameters** 3959 3960| Name | Type | Mandatory| Description| 3961| -------- | ----------------------------------------| ---- | ---------------| 3962| callback | AsyncCallback\<Array\<string\>\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| 3963 3964**Error codes** 3965 3966| ID| Error Message | 3967| ------- | ------------------------------ | 3968| 2303501 | SSL is null. | 3969| 2303502 | Error in tls reading. | 3970| 2303505 | Error occurred in the tls system call. | 3971| 2300002 | System internal error. | 3972 3973**Example** 3974 3975```js 3976import socket from "@ohos.net.socket"; 3977import { BusinessError } from '@ohos.base'; 3978let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 3979tls.getCipherSuite((err: BusinessError, data: Array<string>) => { 3980 if (err) { 3981 console.log("getCipherSuite callback error = " + err); 3982 } else { 3983 console.log("getCipherSuite callback = " + data); 3984 } 3985}); 3986``` 3987 3988### getCipherSuite<sup>9+</sup> 3989 3990getCipherSuite(): Promise\<Array\<string\>\> 3991 3992Obtains the cipher suite negotiated by both communication parties after a TLS socket connection is established. This API uses a promise to return the result. 3993 3994**System capability**: SystemCapability.Communication.NetStack 3995 3996**Return value** 3997 3998| Type | Description | 3999| ---------------------- | --------------------- | 4000| Promise\<Array\<string\>\> | Promise used to return the result. If the operation fails, an error message is returned.| 4001 4002**Error codes** 4003 4004| ID| Error Message | 4005| ------- | ------------------------------ | 4006| 2303501 | SSL is null. | 4007| 2303502 | Error in tls reading. | 4008| 2303505 | Error occurred in the tls system call. | 4009| 2300002 | System internal error. | 4010 4011**Example** 4012 4013```js 4014import socket from "@ohos.net.socket"; 4015import { BusinessError } from '@ohos.base'; 4016let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 4017tls.getCipherSuite().then((data: Array<string>) => { 4018 console.log('getCipherSuite success:' + JSON.stringify(data)); 4019}).catch((err: BusinessError) => { 4020 console.error("failed" + err); 4021}); 4022``` 4023 4024### getSignatureAlgorithms<sup>9+</sup> 4025 4026getSignatureAlgorithms(callback: AsyncCallback\<Array\<string\>\>): void 4027 4028Obtains 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. 4029 4030**System capability**: SystemCapability.Communication.NetStack 4031 4032**Parameters** 4033 4034| Name | Type | Mandatory| Description | 4035| -------- | -------------------------------------| ---- | ---------------| 4036| callback | AsyncCallback\<Array\<string\>\> | Yes | Callback used to return the result. | 4037 4038**Error codes** 4039 4040| ID| Error Message | 4041| ------- | ------------------------------ | 4042| 2303501 | SSL is null. | 4043| 2300002 | System internal error. | 4044 4045**Example** 4046 4047```js 4048import socket from "@ohos.net.socket"; 4049import { BusinessError } from '@ohos.base'; 4050let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 4051tls.getSignatureAlgorithms((err: BusinessError, data: Array<string>) => { 4052 if (err) { 4053 console.log("getSignatureAlgorithms callback error = " + err); 4054 } else { 4055 console.log("getSignatureAlgorithms callback = " + data); 4056 } 4057}); 4058``` 4059 4060### getSignatureAlgorithms<sup>9+</sup> 4061 4062getSignatureAlgorithms(): Promise\<Array\<string\>\> 4063 4064Obtains 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. 4065 4066**System capability**: SystemCapability.Communication.NetStack 4067 4068**Return value** 4069 4070| Type | Description | 4071| ---------------------- | -------------------- | 4072| Promise\<Array\<string\>\> | Promise used to return the result.| 4073 4074**Error codes** 4075 4076| ID| Error Message | 4077| ------- | ------------------------------ | 4078| 2303501 | SSL is null. | 4079| 2300002 | System internal error. | 4080 4081**Example** 4082 4083```js 4084import socket from "@ohos.net.socket"; 4085import { BusinessError } from '@ohos.base'; 4086let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 4087tls.getSignatureAlgorithms().then((data: Array<string>) => { 4088 console.log("getSignatureAlgorithms success" + data); 4089}).catch((err: BusinessError) => { 4090 console.error("failed" + err); 4091}); 4092``` 4093 4094### send<sup>9+</sup> 4095 4096send(data: string, callback: AsyncCallback\<void\>): void 4097 4098Sends a message to the server after a TLS socket connection is established. This API uses an asynchronous callback to return the result. 4099 4100**System capability**: SystemCapability.Communication.NetStack 4101 4102**Parameters** 4103 4104| Name | Type | Mandatory| Description | 4105| -------- | -----------------------------| ---- | ---------------| 4106| data | string | Yes | Data content of the message to send. | 4107| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| 4108 4109**Error codes** 4110 4111| ID| Error Message | 4112| ------- | -------------------------------------------- | 4113| 401 | Parameter error. | 4114| 2303501 | SSL is null. | 4115| 2303503 | Error in tls writing. | 4116| 2303505 | Error occurred in the tls system call. | 4117| 2303506 | Error clearing tls connection. | 4118| 2300002 | System internal error. | 4119 4120**Example** 4121 4122```js 4123import socket from "@ohos.net.socket"; 4124import { BusinessError } from '@ohos.base'; 4125let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 4126tls.send("xxxx", (err: BusinessError) => { 4127 if (err) { 4128 console.log("send callback error = " + err); 4129 } else { 4130 console.log("send success"); 4131 } 4132}); 4133``` 4134 4135### send<sup>9+</sup> 4136 4137send(data: string): Promise\<void\> 4138 4139Sends a message to the server after a TLS socket connection is established. This API uses a promise to return the result. 4140 4141**System capability**: SystemCapability.Communication.NetStack 4142 4143**Parameters** 4144 4145| Name | Type | Mandatory| Description | 4146| -------- | -----------------------------| ---- | ---------------| 4147| data | string | Yes | Data content of the message to send. | 4148 4149**Error codes** 4150 4151| ID| Error Message | 4152| ------- | -------------------------------------------- | 4153| 401 | Parameter error. | 4154| 2303501 | SSL is null. | 4155| 2303503 | Error in tls writing. | 4156| 2303505 | Error occurred in the tls system call. | 4157| 2303506 | Error clearing tls connection. | 4158| 2300002 | System internal error. | 4159 4160**Return value** 4161 4162| Type | Description | 4163| -------------- | -------------------- | 4164| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.| 4165 4166**Example** 4167 4168```js 4169import socket from "@ohos.net.socket"; 4170import { BusinessError } from '@ohos.base'; 4171let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 4172tls.send("xxxx").then(() => { 4173 console.log("send success"); 4174}).catch((err: BusinessError) => { 4175 console.error("failed" + err); 4176}); 4177``` 4178 4179### close<sup>9+</sup> 4180 4181close(callback: AsyncCallback\<void\>): void 4182 4183Closes a TLS socket connection. This API uses an asynchronous callback to return the result. 4184 4185**System capability**: SystemCapability.Communication.NetStack 4186 4187**Parameters** 4188 4189| Name | Type | Mandatory| Description | 4190| -------- | -----------------------------| ---- | ---------------| 4191| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| 4192 4193**Error codes** 4194 4195| ID| Error Message | 4196| ------- | -------------------------------------------- | 4197| 401 | Parameter error. | 4198| 2303501 | SSL is null. | 4199| 2303505 | Error occurred in the tls system call. | 4200| 2303506 | Error clearing tls connection. | 4201| 2300002 | System internal error. | 4202 4203**Example** 4204 4205```js 4206import socket from "@ohos.net.socket"; 4207import { BusinessError } from '@ohos.base'; 4208let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 4209tls.close((err: BusinessError) => { 4210 if (err) { 4211 console.log("close callback error = " + err); 4212 } else { 4213 console.log("close success"); 4214 } 4215}); 4216``` 4217 4218### close<sup>9+</sup> 4219 4220close(): Promise\<void\> 4221 4222Closes a TLS socket connection. This API uses a promise to return the result. 4223 4224**System capability**: SystemCapability.Communication.NetStack 4225 4226**Return value** 4227 4228| Type | Description | 4229| -------------- | -------------------- | 4230| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.| 4231 4232**Error codes** 4233 4234| ID| Error Message | 4235| ------- | -------------------------------------------- | 4236| 401 | Parameter error. | 4237| 2303501 | SSL is null. | 4238| 2303505 | Error occurred in the tls system call. | 4239| 2303506 | Error clearing tls connection. | 4240| 2300002 | System internal error. | 4241 4242**Example** 4243 4244```js 4245import socket from "@ohos.net.socket"; 4246import { BusinessError } from '@ohos.base'; 4247let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 4248tls.close().then(() => { 4249 console.log("close success"); 4250}).catch((err: BusinessError) => { 4251 console.error("failed" + err); 4252}); 4253``` 4254 4255## TLSConnectOptions<sup>9+</sup> 4256 4257Defines TLS connection options. 4258 4259**System capability**: SystemCapability.Communication.NetStack 4260 4261| Name | Type | Mandatory| Description | 4262| -------------- | ------------------------------------- | --- |-------------- | 4263| address | [NetAddress](#netaddress) | Yes | Gateway address. | 4264| secureOptions | [TLSSecureOptions](#tlssecureoptions9) | Yes| TLS security options.| 4265| ALPNProtocols | Array\<string\> | No| ALPN protocol. The value range is ["spdy/1", "http/1.1"]. The default value is **[]**. | 4266 4267## TLSSecureOptions<sup>9+</sup> 4268 4269Defines TLS security options. The CA certificate is mandatory, and other parameters are optional. When **cert** (local certificate) and **key** (private key) are not empty, the two-way authentication mode is enabled. If **cert** or **key** is empty, one-way authentication is enabled. 4270 4271**System capability**: SystemCapability.Communication.NetStack 4272 4273| Name | Type | Mandatory| Description | 4274| --------------------- | ------------------------------------------------------ | --- |----------------------------------- | 4275| ca | string \| Array\<string\> | Yes| CA certificate of the server, which is used to authenticate the digital certificate of the server.| 4276| cert | string | No| Digital certificate of the local client. | 4277| key | string | No| Private key of the local digital certificate. | 4278| password | string | No| Password for reading the private key. | 4279| protocols | [Protocol](#protocol9) \|Array\<[Protocol](#protocol9)\> | No| TLS protocol version. The default value is **TLSv1.2**. | 4280| useRemoteCipherPrefer | boolean | No| Whether to use the remote cipher suite preferentially. | 4281| signatureAlgorithms | string | No| Signing algorithm used during communication. The default value is **""**. | 4282| cipherSuite | string | No| Cipher suite used during communication. The default value is **""**. | 4283 4284## Protocol<sup>9+</sup> 4285 4286Enumerates TLS protocol versions. 4287 4288**System capability**: SystemCapability.Communication.NetStack 4289 4290| Name | Value | Description | 4291| --------- | --------- |------------------ | 4292| TLSv12 | "TLSv1.2" | TLSv1.2.| 4293| TLSv13 | "TLSv1.3" | TLSv1.3.| 4294 4295## X509CertRawData<sup>9+</sup> 4296 4297Defines the certificate raw data. 4298 4299**System capability**: SystemCapability.Communication.NetStack 4300 4301## socket.constructTLSSocketServerInstance<sup>10+</sup> 4302 4303constructTLSSocketServerInstance(): TLSSocketServer 4304 4305Creates a **TLSSocketServer** object. 4306 4307**System capability**: SystemCapability.Communication.NetStack 4308 4309**Return value** 4310 4311| Type | Description | 4312| :------------------------------------ | :---------------------------- | 4313| [TLSSocketServer](#tlssocketserver10) | **TLSSocketServer** object.| 4314 4315**Example** 4316 4317```js 4318import socket from "@ohos.net.socket"; 4319import { BusinessError } from '@ohos.base'; 4320let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 4321``` 4322 4323## TLSSocketServer<sup>10+</sup> 4324 4325Defines a TLS socket server connection. Before calling TLSSocketServer APIs, you need to call [socket.constructTLSSocketServerInstance](#socketconstructtlssocketserverinstance10) to create a **TLSSocketServer** object. 4326 4327### listen<sup>10+</sup> 4328 4329listen(options: TLSConnectOptions, callback: AsyncCallback\<void\>): void 4330 4331Listens 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. 4332 4333**Required permissions**: ohos.permission.INTERNET 4334 4335**System capability**: SystemCapability.Communication.NetStack 4336 4337**Parameters** 4338 4339| Name | Type | Mandatory| Description | 4340| -------- | ---------------------------------------- | ---- | ------------------------------------------------ | 4341| options | [TLSConnectOptions](#tlsconnectoptions9) | Yes | Parameters required for the connection. | 4342| 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.| 4343 4344**Error codes** 4345 4346| ID| Error Message | 4347| -------- | ------------------------------------------- | 4348| 401 | Parameter error. | 4349| 201 | Permission denied. | 4350| 2300002 | System internal error. | 4351| 2303109 | Bad file number. | 4352| 2303111 | Resource temporarily unavailable try again. | 4353| 2303198 | Address already in use. | 4354| 2303199 | Cannot assign requested address. | 4355| 2303501 | SSL is null. | 4356| 2303502 | Error in tls reading. | 4357| 2303503 | Error in tls writing | 4358| 2303505 | Error occurred in the tls system call. | 4359| 2303506 | Error clearing tls connection. | 4360 4361**Example** 4362 4363```js 4364import socket from "@ohos.net.socket"; 4365import { BusinessError } from '@ohos.base'; 4366let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 4367 4368let tlsConnectOptions: socket.TLSConnectOptions = { 4369 address: { 4370 address: '192.168.xx.xxx', 4371 port: 8080 4372 }, 4373 secureOptions: { 4374 key: "xxxx", 4375 cert: "xxxx", 4376 ca: ["xxxx"], 4377 password: "xxxx", 4378 protocols: socket.Protocol.TLSv12, 4379 useRemoteCipherPrefer: true, 4380 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 4381 cipherSuite: "AES256-SHA256" 4382 }, 4383 ALPNProtocols: ["spdy/1", "http/1.1"] 4384} 4385tlsServer.listen(tlsConnectOptions, (err: BusinessError) => { 4386 console.log("listen callback error" + err); 4387}); 4388``` 4389 4390### listen<sup>10+</sup> 4391 4392listen(options: TLSConnectOptions): Promise\<void\> 4393 4394Listens 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. 4395 4396**Required permissions**: ohos.permission.INTERNET 4397 4398**System capability**: SystemCapability.Communication.NetStack 4399 4400**Parameters** 4401 4402| Name | Type | Mandatory| Description | 4403| ------- | ---------------------------------------- | ---- | ------------------ | 4404| options | [TLSConnectOptions](#tlsconnectoptions9) | Yes | Parameters required for the connection.| 4405 4406**Return value** 4407 4408| Type | Description | 4409| --------------- | --------------------------------------------------------- | 4410| 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.| 4411 4412**Error codes** 4413 4414| ID| Error Message | 4415| -------- | ------------------------------------------- | 4416| 401 | Parameter error. | 4417| 201 | Permission denied. | 4418| 2300002 | System internal error. | 4419| 2303109 | Bad file number. | 4420| 2303111 | Resource temporarily unavailable try again. | 4421| 2303198 | Address already in use. | 4422| 2303199 | Cannot assign requested address. | 4423| 2303501 | SSL is null. | 4424| 2303502 | Error in tls reading. | 4425| 2303503 | Error in tls writing | 4426| 2303505 | Error occurred in the tls system call. | 4427| 2303506 | Error clearing tls connection. | 4428 4429**Example** 4430 4431```js 4432import socket from "@ohos.net.socket"; 4433import { BusinessError } from '@ohos.base'; 4434let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 4435 4436let tlsConnectOptions: socket.TLSConnectOptions = { 4437 address: { 4438 address: '192.168.xx.xxx', 4439 port: 8080 4440 }, 4441 secureOptions: { 4442 key: "xxxx", 4443 cert: "xxxx", 4444 ca: ["xxxx"], 4445 password: "xxxx", 4446 protocols: socket.Protocol.TLSv12, 4447 useRemoteCipherPrefer: true, 4448 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 4449 cipherSuite: "AES256-SHA256" 4450 }, 4451 ALPNProtocols: ["spdy/1", "http/1.1"] 4452} 4453tlsServer.listen(tlsConnectOptions).then(() => { 4454 console.log("listen callback success"); 4455}).catch((err: BusinessError) => { 4456 console.log("failed: " + JSON.stringify(err)); 4457}); 4458``` 4459 4460### getState<sup>10+</sup> 4461 4462getState(callback: AsyncCallback\<SocketStateBase\>): void 4463 4464Obtains the status of the TLS socket server connection upon successful listening. This API uses an asynchronous callback to return the result. 4465 4466> **NOTE** 4467> This API can be called only after **listen** is successfully called. 4468 4469**System capability**: SystemCapability.Communication.NetStack 4470 4471**Parameters** 4472 4473| Name | Type | Mandatory| Description | 4474| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | 4475| callback | AsyncCallback\<[SocketStateBase](#socketstatebase7)> | 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.| 4476 4477**Error codes** 4478 4479| ID| Error Message | 4480| -------- | ------------------------------- | 4481| 401 | Parameter error. | 4482| 2303188 | Socket operation on non-socket. | 4483| 2300002 | System internal error. | 4484 4485**Example** 4486 4487```js 4488import socket from "@ohos.net.socket"; 4489import { BusinessError } from '@ohos.base'; 4490let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 4491let tlsConnectOptions: socket.TLSConnectOptions = { 4492 address: { 4493 address: '192.168.xx.xxx', 4494 port: 8080 4495 }, 4496 secureOptions: { 4497 key: "xxxx", 4498 cert: "xxxx", 4499 ca: ["xxxx"], 4500 password: "xxxx", 4501 protocols: socket.Protocol.TLSv12, 4502 useRemoteCipherPrefer: true, 4503 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 4504 cipherSuite: "AES256-SHA256" 4505 }, 4506 ALPNProtocols: ["spdy/1", "http/1.1"] 4507} 4508tlsServer.listen(tlsConnectOptions).then(() => { 4509 console.log("listen callback success"); 4510}).catch((err: BusinessError) => { 4511 console.log("failed: " + JSON.stringify(err)); 4512}); 4513tlsServer.getState((err: BusinessError, data: socket.SocketStateBase) => { 4514 if (err) { 4515 console.log('getState fail'); 4516 return; 4517 } 4518 console.log('getState success:' + JSON.stringify(data)); 4519}); 4520``` 4521 4522### getState<sup>10+</sup> 4523 4524getState(): Promise\<SocketStateBase\> 4525 4526Obtains the status of the TLS socket server connection upon successful listening. This API uses a promise to return the result. 4527 4528> **NOTE** 4529> This API can be called only after **listen** is successfully called. 4530 4531**System capability**: SystemCapability.Communication.NetStack 4532 4533**Return value** 4534 4535| Type | Description | 4536| :--------------------------------------------- | :----------------------------------------------------------- | 4537| Promise\<[SocketStateBase](#socketstatebase7)> | Promise used to return the result. If the operation fails, an error message is returned.| 4538 4539**Error codes** 4540 4541| ID| Error Message | 4542| -------- | ------------------------------- | 4543| 2303188 | Socket operation on non-socket. | 4544| 2300002 | System internal error. | 4545 4546**Example** 4547 4548```js 4549import socket from "@ohos.net.socket"; 4550import { BusinessError } from '@ohos.base'; 4551let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 4552let tlsConnectOptions: socket.TLSConnectOptions = { 4553 address: { 4554 address: '192.168.xx.xxx', 4555 port: 8080 4556 }, 4557 secureOptions: { 4558 key: "xxxx", 4559 cert: "xxxx", 4560 ca: ["xxxx"], 4561 password: "xxxx", 4562 protocols: socket.Protocol.TLSv12, 4563 useRemoteCipherPrefer: true, 4564 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 4565 cipherSuite: "AES256-SHA256" 4566 }, 4567 ALPNProtocols: ["spdy/1", "http/1.1"] 4568} 4569tlsServer.listen(tlsConnectOptions).then(() => { 4570 console.log("listen callback success"); 4571}).catch((err: BusinessError) => { 4572 console.log("failed: " + JSON.stringify(err)); 4573}); 4574tlsServer.getState().then(() => { 4575 console.log('getState success'); 4576}).catch((err: BusinessError) => { 4577 console.log('getState fail'); 4578}); 4579``` 4580 4581### setExtraOptions<sup>10+</sup> 4582 4583setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\<void\>): void 4584 4585Sets other properties of the TLS socket server connection upon successful listening. This API uses an asynchronous callback to return the result. 4586 4587> **NOTE** 4588> This API can be called only after **listen** is successfully called. 4589 4590**System capability**: SystemCapability.Communication.NetStack 4591 4592**Parameters** 4593 4594| Name | Type | Mandatory| Description | 4595| -------- | ------------------------------------ | ---- | ------------------------------------------------ | 4596| options | [TCPExtraOptions](#tcpextraoptions7) | Yes | Other properties of the TLS socket server connection. | 4597| 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.| 4598 4599**Error codes** 4600 4601| ID| Error Message | 4602| -------- | ------------------------------- | 4603| 401 | Parameter error. | 4604| 2303188 | Socket operation on non-socket. | 4605| 2300002 | System internal error. | 4606 4607**Example** 4608 4609```js 4610import socket from "@ohos.net.socket"; 4611import { BusinessError } from '@ohos.base'; 4612let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 4613let tlsConnectOptions: socket.TLSConnectOptions = { 4614 address: { 4615 address: '192.168.xx.xxx', 4616 port: 8080 4617 }, 4618 secureOptions: { 4619 key: "xxxx", 4620 cert: "xxxx", 4621 ca: ["xxxx"], 4622 password: "xxxx", 4623 protocols: socket.Protocol.TLSv12, 4624 useRemoteCipherPrefer: true, 4625 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 4626 cipherSuite: "AES256-SHA256" 4627 }, 4628 ALPNProtocols: ["spdy/1", "http/1.1"] 4629} 4630tlsServer.listen(tlsConnectOptions).then(() => { 4631 console.log("listen callback success"); 4632}).catch((err: BusinessError) => { 4633 console.log("failed: " + JSON.stringify(err)); 4634}); 4635 4636let tcpExtraOptions: socket.TCPExtraOptions = { 4637 keepAlive: true, 4638 OOBInline: true, 4639 TCPNoDelay: true, 4640 socketLinger: { on: true, linger: 10 }, 4641 receiveBufferSize: 1000, 4642 sendBufferSize: 1000, 4643 reuseAddress: true, 4644 socketTimeout: 3000 4645} 4646tlsServer.setExtraOptions(tcpExtraOptions, (err: BusinessError) => { 4647 if (err) { 4648 console.log('setExtraOptions fail'); 4649 return; 4650 } 4651 console.log('setExtraOptions success'); 4652}); 4653``` 4654 4655### setExtraOptions<sup>10+</sup> 4656 4657setExtraOptions(options: TCPExtraOptions): Promise\<void\> 4658 4659Sets other properties of the TLS socket server connection upon successful listening. This API uses a promise to return the result. 4660 4661> **NOTE** 4662> This API can be called only after **listen** is successfully called. 4663 4664**System capability**: SystemCapability.Communication.NetStack 4665 4666**Parameters** 4667 4668| Name | Type | Mandatory| Description | 4669| ------- | ------------------------------------ | ---- | ------------------------------- | 4670| options | [TCPExtraOptions](#tcpextraoptions7) | Yes | Other properties of the TLS socket server connection.| 4671 4672**Return value** 4673 4674| Type | Description | 4675| :-------------- | :-------------------------------------------------------- | 4676| 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.| 4677 4678**Error codes** 4679 4680| ID| Error Message | 4681| -------- | ------------------------------- | 4682| 401 | Parameter error. | 4683| 2303188 | Socket operation on non-socket. | 4684| 2300002 | System internal error. | 4685 4686**Example** 4687 4688```js 4689import socket from "@ohos.net.socket"; 4690import { BusinessError } from '@ohos.base'; 4691let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 4692let tlsConnectOptions: socket.TLSConnectOptions = { 4693 address: { 4694 address: '192.168.xx.xxx', 4695 port: 8080 4696 }, 4697 secureOptions: { 4698 key: "xxxx", 4699 cert: "xxxx", 4700 ca: ["xxxx"], 4701 password: "xxxx", 4702 protocols: socket.Protocol.TLSv12, 4703 useRemoteCipherPrefer: true, 4704 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 4705 cipherSuite: "AES256-SHA256" 4706 }, 4707 ALPNProtocols: ["spdy/1", "http/1.1"] 4708} 4709tlsServer.listen(tlsConnectOptions).then(() => { 4710 console.log("listen callback success"); 4711}).catch((err: BusinessError) => { 4712 console.log("failed: " + JSON.stringify(err)); 4713}); 4714 4715let tcpExtraOptions: socket.TCPExtraOptions = { 4716 keepAlive: true, 4717 OOBInline: true, 4718 TCPNoDelay: true, 4719 socketLinger: { on: true, linger: 10 }, 4720 receiveBufferSize: 1000, 4721 sendBufferSize: 1000, 4722 reuseAddress: true, 4723 socketTimeout: 3000 4724} 4725tlsServer.setExtraOptions(tcpExtraOptions).then(() => { 4726 console.log('setExtraOptions success'); 4727}).catch((err: BusinessError) => { 4728 console.log('setExtraOptions fail'); 4729}); 4730``` 4731 4732### getCertificate<sup>10+</sup> 4733 4734getCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)\>): void 4735 4736Obtains the local digital certificate after a TLS socket server connection is established. This API uses an asynchronous callback to return the result. 4737 4738> **NOTE** 4739> This API can be called only after **listen** is successfully called. 4740 4741**System capability**: SystemCapability.Communication.NetStack 4742 4743**Parameters** 4744 4745| Name | Type | Mandatory| Description | 4746| -------- | ----------------------------------------------------- | ---- | -------------------------------------------------------- | 4747| 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.| 4748 4749**Error codes** 4750 4751| ID| Error Message | 4752| -------- | ---------------------- | 4753| 401 | Parameter error. | 4754| 2303501 | SSL is null. | 4755| 2303504 | Error looking up x509. | 4756| 2300002 | System internal error. | 4757 4758**Example** 4759 4760```js 4761import socket from "@ohos.net.socket"; 4762import { BusinessError } from '@ohos.base'; 4763let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 4764let tlsConnectOptions: socket.TLSConnectOptions = { 4765 address: { 4766 address: '192.168.xx.xxx', 4767 port: 8080 4768 }, 4769 secureOptions: { 4770 key: "xxxx", 4771 cert: "xxxx", 4772 ca: ["xxxx"], 4773 password: "xxxx", 4774 protocols: socket.Protocol.TLSv12, 4775 useRemoteCipherPrefer: true, 4776 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 4777 cipherSuite: "AES256-SHA256" 4778 }, 4779 ALPNProtocols: ["spdy/1", "http/1.1"] 4780} 4781tlsServer.listen(tlsConnectOptions).then(() => { 4782 console.log("listen callback success"); 4783}).catch((err: BusinessError) => { 4784 console.log("failed: " + JSON.stringify(err)); 4785}); 4786tlsServer.getCertificate((err: BusinessError, data: socket.X509CertRawData) => { 4787 if (err) { 4788 console.log("getCertificate callback error = " + err); 4789 } else { 4790 console.log("getCertificate callback = " + data); 4791 } 4792}); 4793``` 4794 4795### getCertificate<sup>10+</sup> 4796 4797getCertificate():Promise\<[X509CertRawData](#x509certrawdata9)\> 4798 4799Obtains the local digital certificate after a TLS socket server connection is established. This API uses a promise to return the result. 4800 4801> **NOTE** 4802> This API can be called only after **listen** is successfully called. 4803 4804**System capability**: SystemCapability.Communication.NetStack 4805 4806**Return value** 4807 4808| Type | Description | 4809| ----------------------------------------------- | ------------------------------------------------------------ | 4810| Promise\<[X509CertRawData](#x509certrawdata9)\> | Promise used to return the result. If the operation fails, an error message is returned.| 4811 4812**Error codes** 4813 4814| ID| Error Message | 4815| -------- | ---------------------- | 4816| 2303501 | SSL is null. | 4817| 2303504 | Error looking up x509. | 4818| 2300002 | System internal error. | 4819 4820**Example** 4821 4822```js 4823import socket from "@ohos.net.socket"; 4824import { BusinessError } from '@ohos.base'; 4825let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 4826let tlsConnectOptions: socket.TLSConnectOptions = { 4827 address: { 4828 address: '192.168.xx.xxx', 4829 port: 8080 4830 }, 4831 secureOptions: { 4832 key: "xxxx", 4833 cert: "xxxx", 4834 ca: ["xxxx"], 4835 password: "xxxx", 4836 protocols: socket.Protocol.TLSv12, 4837 useRemoteCipherPrefer: true, 4838 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 4839 cipherSuite: "AES256-SHA256" 4840 }, 4841 ALPNProtocols: ["spdy/1", "http/1.1"] 4842} 4843tlsServer.listen(tlsConnectOptions).then(() => { 4844 console.log("listen callback success"); 4845}).catch((err: BusinessError) => { 4846 console.log("failed: " + JSON.stringify(err)); 4847}); 4848tlsServer.getCertificate().then((data: socket.x509certrawdata9) => { 4849 console.log(data); 4850}).catch((err: BusinessError) => { 4851 console.error("failed" + err); 4852}); 4853``` 4854 4855### getProtocol<sup>10+</sup> 4856 4857getProtocol(callback: AsyncCallback\<string\>): void 4858 4859Obtains the communication protocol version after a TLS socket server connection is established. This API uses an asynchronous callback to return the result. 4860 4861> **NOTE** 4862> This API can be called only after **listen** is successfully called. 4863 4864**System capability**: SystemCapability.Communication.NetStack 4865 4866**Parameters** 4867 4868| Name | Type | Mandatory| Description | 4869| -------- | ----------------------- | ---- | ---------------------------------------------------- | 4870| callback | AsyncCallback\<string\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| 4871 4872**Error codes** 4873 4874| ID| Error Message | 4875| -------- | -------------------------------------- | 4876| 401 | Parameter error. | 4877| 2303501 | SSL is null. | 4878| 2303505 | Error occurred in the tls system call. | 4879| 2300002 | System internal error. | 4880 4881**Example** 4882 4883```js 4884import socket from "@ohos.net.socket"; 4885import { BusinessError } from '@ohos.base'; 4886let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 4887let tlsConnectOptions: socket.TLSConnectOptions = { 4888 address: { 4889 address: '192.168.xx.xxx', 4890 port: 8080 4891 }, 4892 secureOptions: { 4893 key: "xxxx", 4894 cert: "xxxx", 4895 ca: ["xxxx"], 4896 password: "xxxx", 4897 protocols: socket.Protocol.TLSv12, 4898 useRemoteCipherPrefer: true, 4899 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 4900 cipherSuite: "AES256-SHA256" 4901 }, 4902 ALPNProtocols: ["spdy/1", "http/1.1"] 4903} 4904tlsServer.listen(tlsConnectOptions).then(() => { 4905 console.log("listen callback success"); 4906}).catch((err: BusinessError) => { 4907 console.log("failed: " + JSON.stringify(err)); 4908}); 4909tlsServer.getProtocol((err: BusinessError, data: string) => { 4910 if (err) { 4911 console.log("getProtocol callback error = " + err); 4912 } else { 4913 console.log("getProtocol callback = " + data); 4914 } 4915}); 4916``` 4917 4918### getProtocol<sup>10+</sup> 4919 4920getProtocol():Promise\<string\> 4921 4922Obtains the communication protocol version after a TLS socket server connection is established. This API uses a promise to return the result. 4923 4924> **NOTE** 4925> This API can be called only after **listen** is successfully called. 4926 4927**System capability**: SystemCapability.Communication.NetStack 4928 4929**Return value** 4930 4931| Type | Description | 4932| ----------------- | ------------------------------------------------------- | 4933| Promise\<string\> | Promise used to return the result. If the operation fails, an error message is returned.| 4934 4935**Error codes** 4936 4937| ID| Error Message | 4938| -------- | -------------------------------------- | 4939| 2303501 | SSL is null. | 4940| 2303505 | Error occurred in the tls system call. | 4941| 2300002 | System internal error. | 4942 4943**Example** 4944 4945```js 4946import socket from "@ohos.net.socket"; 4947import { BusinessError } from '@ohos.base'; 4948let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 4949let tlsConnectOptions: socket.TLSConnectOptions = { 4950 address: { 4951 address: '192.168.xx.xxx', 4952 port: 8080 4953 }, 4954 secureOptions: { 4955 key: "xxxx", 4956 cert: "xxxx", 4957 ca: ["xxxx"], 4958 password: "xxxx", 4959 protocols: socket.Protocol.TLSv12, 4960 useRemoteCipherPrefer: true, 4961 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 4962 cipherSuite: "AES256-SHA256" 4963 }, 4964 ALPNProtocols: ["spdy/1", "http/1.1"] 4965} 4966tlsServer.listen(tlsConnectOptions).then(() => { 4967 console.log("listen callback success"); 4968}).catch((err: BusinessError) => { 4969 console.log("failed: " + JSON.stringify(err)); 4970}); 4971tlsServer.getProtocol().then((data: string) => { 4972 console.log(data); 4973}).catch((err: BusinessError) => { 4974 console.error("failed" + err); 4975}); 4976``` 4977 4978### on('connect')<sup>10+</sup> 4979 4980on(type: 'connect', callback: Callback\<TLSSocketConnection\>): void 4981 4982Subscribes to TLS socket server connection events. This API uses an asynchronous callback to return the result. 4983 4984> **NOTE** 4985> This API can be called only after **listen** is successfully called. 4986 4987**System capability**: SystemCapability.Communication.NetStack 4988 4989**Parameters** 4990 4991| Name | Type | Mandatory| Description | 4992| -------- | ------------------------------------------------------- | ---- | ------------------------------------- | 4993| type | string | Yes | Type of the event to subscribe to.<br/> **connect**: connection event.| 4994| callback | Callback<[TLSSocketConnection](#tlssocketconnection10)> | Yes | Callback used to return the result. | 4995 4996**Error codes** 4997 4998| ID| Error Message | 4999| -------- | ---------------- | 5000| 401 | Parameter error. | 5001 5002**Example** 5003 5004```js 5005import socket from "@ohos.net.socket"; 5006import { BusinessError } from '@ohos.base'; 5007let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 5008let tlsConnectOptions: socket.TLSConnectOptions = { 5009 address: { 5010 address: '192.168.xx.xxx', 5011 port: 8080 5012 }, 5013 secureOptions: { 5014 key: "xxxx", 5015 cert: "xxxx", 5016 ca: ["xxxx"], 5017 password: "xxxx", 5018 protocols: socket.Protocol.TLSv12, 5019 useRemoteCipherPrefer: true, 5020 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 5021 cipherSuite: "AES256-SHA256" 5022 }, 5023 ALPNProtocols: ["spdy/1", "http/1.1"] 5024} 5025tlsServer.listen(tlsConnectOptions).then(() => { 5026 console.log("listen callback success"); 5027}).catch((err: BusinessError) => { 5028 console.log("failed: " + JSON.stringify(err)); 5029}); 5030tlsServer.on('connect', (data: socket.TLSSocketConnection) => { 5031 console.log(JSON.stringify(data)) 5032}); 5033``` 5034 5035### off('connect')<sup>10+</sup> 5036 5037off(type: 'connect', callback?: Callback\<TLSSocketConnection\>): void 5038 5039Unsubscribes from TLS socket server connection events. This API uses an asynchronous callback to return the result. 5040 5041> **NOTE** 5042> This API can be called only after **listen** is successfully called. 5043> 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. 5044 5045**System capability**: SystemCapability.Communication.NetStack 5046 5047**Parameters** 5048 5049| Name | Type | Mandatory| Description | 5050| -------- | ------------------------------------------------------- | ---- | ------------------------------------- | 5051| type | string | Yes | Type of the event to subscribe to.<br/> **connect**: connection event.| 5052| callback | Callback<[TLSSocketConnection](#tlssocketconnection10)> | No | Callback used to return the result. | 5053 5054**Error codes** 5055 5056| ID| Error Message | 5057| -------- | ---------------- | 5058| 401 | Parameter error. | 5059 5060**Example** 5061 5062```js 5063import socket from "@ohos.net.socket"; 5064import { BusinessError } from '@ohos.base'; 5065let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 5066let tlsConnectOptions: socket.TLSConnectOptions = { 5067 address: { 5068 address: '192.168.xx.xxx', 5069 port: 8080 5070 }, 5071 secureOptions: { 5072 key: "xxxx", 5073 cert: "xxxx", 5074 ca: ["xxxx"], 5075 password: "xxxx", 5076 protocols: socket.Protocol.TLSv12, 5077 useRemoteCipherPrefer: true, 5078 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 5079 cipherSuite: "AES256-SHA256" 5080 }, 5081 ALPNProtocols: ["spdy/1", "http/1.1"] 5082} 5083tlsServer.listen(tlsConnectOptions).then(() => { 5084 console.log("listen callback success"); 5085}).catch((err: BusinessError) => { 5086 console.log("failed: " + JSON.stringify(err)); 5087}); 5088 5089let callback = (data: socket.TLSSocketConnection) => { 5090 console.log('on connect message: ' + JSON.stringify(data)); 5091} 5092tlsServer.on('connect', callback); 5093// 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. 5094tlsServer.off('connect', callback); 5095tlsServer.off('connect'); 5096``` 5097 5098### on('error')<sup>10+</sup> 5099 5100on(type: 'error', callback: ErrorCallback): void 5101 5102Subscribes to **error** events of a **TLSSocketServer** object. This API uses an asynchronous callback to return the result. 5103 5104> **NOTE** 5105> This API can be called only after **listen** is successfully called. 5106 5107**System capability**: SystemCapability.Communication.NetStack 5108 5109**Parameters** 5110 5111| Name | Type | Mandatory| Description | 5112| -------- | ------------- | ---- | ------------------------------------ | 5113| type | string | Yes | Type of the event to subscribe to.<br/> **error**: error event.| 5114| callback | ErrorCallback | Yes | Callback used to return the result. | 5115 5116**Error codes** 5117 5118| ID| Error Message | 5119| -------- | ---------------- | 5120| 401 | Parameter error. | 5121 5122**Example** 5123 5124```js 5125import socket from "@ohos.net.socket"; 5126import { BusinessError } from '@ohos.base'; 5127let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 5128let tlsConnectOptions: socket.TLSConnectOptions = { 5129 address: { 5130 address: '192.168.xx.xxx', 5131 port: 8080 5132 }, 5133 secureOptions: { 5134 key: "xxxx", 5135 cert: "xxxx", 5136 ca: ["xxxx"], 5137 password: "xxxx", 5138 protocols: socket.Protocol.TLSv12, 5139 useRemoteCipherPrefer: true, 5140 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 5141 cipherSuite: "AES256-SHA256" 5142 }, 5143 ALPNProtocols: ["spdy/1", "http/1.1"] 5144} 5145tlsServer.listen(tlsConnectOptions).then(() => { 5146 console.log("listen callback success"); 5147}).catch((err: BusinessError) => { 5148 console.log("failed: " + JSON.stringify(err)); 5149}); 5150tlsServer.on('error', (err: BusinessError) => { 5151 console.log("on error, err:" + JSON.stringify(err)) 5152}); 5153``` 5154 5155### off('error')<sup>10+</sup> 5156 5157off(type: 'error', callback?: ErrorCallback): void 5158 5159Unsubscribes from **error** events of a **TLSSocketServer** object. This API uses an asynchronous callback to return the result. 5160 5161> **NOTE** 5162> This API can be called only after **listen** is successfully called. 5163> 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. 5164 5165**System capability**: SystemCapability.Communication.NetStack 5166 5167**Parameters** 5168 5169| Name | Type | Mandatory| Description | 5170| -------- | ------------- | ---- | ------------------------------------ | 5171| type | string | Yes | Type of the event to subscribe to.<br/> **error**: error event.| 5172| callback | ErrorCallback | No | Callback used to return the result. | 5173 5174**Error codes** 5175 5176| ID| Error Message | 5177| -------- | ---------------- | 5178| 401 | Parameter error. | 5179 5180**Example** 5181 5182```js 5183import socket from "@ohos.net.socket"; 5184import { BusinessError } from '@ohos.base'; 5185let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 5186let tlsConnectOptions: socket.TLSConnectOptions = { 5187 address: { 5188 address: '192.168.xx.xxx', 5189 port: 8080 5190 }, 5191 secureOptions: { 5192 key: "xxxx", 5193 cert: "xxxx", 5194 ca: ["xxxx"], 5195 password: "xxxx", 5196 protocols: socket.Protocol.TLSv12, 5197 useRemoteCipherPrefer: true, 5198 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 5199 cipherSuite: "AES256-SHA256" 5200 }, 5201 ALPNProtocols: ["spdy/1", "http/1.1"] 5202} 5203tlsServer.listen(tlsConnectOptions).then(() => { 5204 console.log("listen callback success"); 5205}).catch((err: BusinessError) => { 5206 console.log("failed: " + JSON.stringify(err)); 5207}); 5208 5209let callback = (err: BusinessError) => { 5210 console.log("on error, err:" + JSON.stringify(err)); 5211} 5212tlsServer.on('error', callback); 5213// 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. 5214tlsServer.off('error', callback); 5215tlsServer.off('error'); 5216``` 5217 5218## TLSSocketConnection<sup>10+</sup> 5219 5220Defines 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. 5221 5222> **NOTE** 5223> 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. 5224 5225**System capability**: SystemCapability.Communication.NetStack 5226 5227### Attributes 5228 5229| Name | Type | Mandatory| Description | 5230| -------- | ------ | ---- | ------------------------------------- | 5231| clientId | number | Yes | ID of the connection between the client and TLSSocketServer.| 5232 5233### send<sup>10+</sup> 5234 5235send(data: string, callback: AsyncCallback\<void\>): void 5236 5237Sends a message to the client after a TLS socket server connection is established. This API uses an asynchronous callback to return the result. 5238 5239**System capability**: SystemCapability.Communication.NetStack 5240 5241**Parameters** 5242 5243| Name | Type | Mandatory| Description | 5244| -------- | --------------------- | ---- | ------------------------------------------------ | 5245| data | string | Yes | Parameters for sending data over the TLS socket server connection. | 5246| 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.| 5247 5248**Error codes** 5249 5250| ID| Error Message | 5251| -------- | -------------------------------------- | 5252| 401 | Parameter error. | 5253| 2303501 | SSL is null. | 5254| 2303503 | Error in tls writing. | 5255| 2303505 | Error occurred in the tls system call. | 5256| 2303506 | Error clearing tls connection. | 5257| 2300002 | System internal error. | 5258 5259**Example** 5260 5261```js 5262import socket from "@ohos.net.socket"; 5263import { BusinessError } from '@ohos.base'; 5264let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 5265let tlsConnectOptions: socket.TLSConnectOptions = { 5266 address: { 5267 address: '192.168.xx.xxx', 5268 port: 8080 5269 }, 5270 secureOptions: { 5271 key: "xxxx", 5272 cert: "xxxx", 5273 ca: ["xxxx"], 5274 password: "xxxx", 5275 protocols: socket.Protocol.TLSv12, 5276 useRemoteCipherPrefer: true, 5277 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 5278 cipherSuite: "AES256-SHA256" 5279 }, 5280 ALPNProtocols: ["spdy/1", "http/1.1"] 5281} 5282tlsServer.listen(tlsConnectOptions).then(() => { 5283 console.log("listen callback success"); 5284}).catch((err: BusinessError) => { 5285 console.log("failed" + err); 5286}); 5287 5288tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 5289 client.send('Hello, client!', (err: BusinessError) => { 5290 if (err) { 5291 console.log('send fail'); 5292 return; 5293 } 5294 console.log('send success'); 5295 }); 5296}); 5297``` 5298 5299### send<sup>10+</sup> 5300 5301send(data: string): Promise\<void\> 5302 5303Sends a message to the server after a TLS socket server connection is established. This API uses a promise to return the result. 5304 5305**System capability**: SystemCapability.Communication.NetStack 5306 5307**Parameters** 5308 5309| Name| Type | Mandatory| Description | 5310| ------ | ------ | ---- | ------------------------------------- | 5311| data | string | Yes | Parameters for sending data over the TLS socket server connection.| 5312 5313**Return value** 5314 5315| Type | Description | 5316| --------------- | --------------------------------------------------------- | 5317| 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.| 5318 5319**Error codes** 5320 5321| ID| Error Message | 5322| -------- | -------------------------------------- | 5323| 401 | Parameter error. | 5324| 2303501 | SSL is null. | 5325| 2303503 | Error in tls writing. | 5326| 2303505 | Error occurred in the tls system call. | 5327| 2303506 | Error clearing tls connection. | 5328| 2300002 | System internal error. | 5329 5330**Example** 5331 5332```js 5333import socket from "@ohos.net.socket"; 5334import { BusinessError } from '@ohos.base'; 5335let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 5336let tlsConnectOptions: socket.TLSConnectOptions = { 5337 address: { 5338 address: '192.168.xx.xxx', 5339 port: 8080 5340 }, 5341 secureOptions: { 5342 key: "xxxx", 5343 cert: "xxxx", 5344 ca: ["xxxx"], 5345 password: "xxxx", 5346 protocols: socket.Protocol.TLSv12, 5347 useRemoteCipherPrefer: true, 5348 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 5349 cipherSuite: "AES256-SHA256" 5350 }, 5351 ALPNProtocols: ["spdy/1", "http/1.1"] 5352} 5353tlsServer.listen(tlsConnectOptions).then(() => { 5354 console.log("listen callback success"); 5355}).catch((err: BusinessError) => { 5356 console.log("failed" + err); 5357}); 5358 5359tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 5360 client.send('Hello, client!').then(() => { 5361 console.log('send success'); 5362 }).catch((err: BusinessError) => { 5363 console.log('send fail'); 5364 }); 5365}); 5366``` 5367 5368### close<sup>10+</sup> 5369 5370close(callback: AsyncCallback\<void\>): void 5371 5372Closes a TLS socket server connection. This API uses an asynchronous callback to return the result. 5373 5374**System capability**: SystemCapability.Communication.NetStack 5375 5376**Parameters** 5377 5378| Name | Type | Mandatory| Description | 5379| -------- | --------------------- | ---- | ------------------------------------------------ | 5380| 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.| 5381 5382**Error codes** 5383 5384| ID| Error Message | 5385| -------- | -------------------------------------- | 5386| 401 | Parameter error. | 5387| 2303501 | SSL is null. | 5388| 2303505 | Error occurred in the tls system call. | 5389| 2303506 | Error clearing tls connection. | 5390| 2300002 | System internal error. | 5391 5392**Example** 5393 5394```js 5395import socket from "@ohos.net.socket"; 5396import { BusinessError } from '@ohos.base'; 5397let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 5398let tlsConnectOptions: socket.TLSConnectOptions = { 5399 address: { 5400 address: '192.168.xx.xxx', 5401 port: 8080 5402 }, 5403 secureOptions: { 5404 key: "xxxx", 5405 cert: "xxxx", 5406 ca: ["xxxx"], 5407 password: "xxxx", 5408 protocols: socket.Protocol.TLSv12, 5409 useRemoteCipherPrefer: true, 5410 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 5411 cipherSuite: "AES256-SHA256" 5412 }, 5413 ALPNProtocols: ["spdy/1", "http/1.1"] 5414} 5415tlsServer.listen(tlsConnectOptions).then(() => { 5416 console.log("listen callback success"); 5417}).catch((err: BusinessError) => { 5418 console.log("failed" + err); 5419}); 5420 5421tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 5422 client.close((err: BusinessError) => { 5423 if (err) { 5424 console.log('close fail'); 5425 return; 5426 } 5427 console.log('close success'); 5428 }); 5429}); 5430``` 5431 5432### close<sup>10+</sup> 5433 5434close(): Promise\<void\> 5435 5436Closes a TLS socket server connection. This API uses a promise to return the result. 5437 5438**System capability**: SystemCapability.Communication.NetStack 5439 5440**Return value** 5441 5442| Type | Description | 5443| --------------- | --------------------------------------------------------- | 5444| 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.| 5445 5446**Error codes** 5447 5448| ID| Error Message | 5449| -------- | -------------------------------------- | 5450| 2303501 | SSL is null. | 5451| 2303505 | Error occurred in the tls system call. | 5452| 2303506 | Error clearing tls connection. | 5453| 2300002 | System internal error. | 5454 5455**Example** 5456 5457```js 5458import socket from "@ohos.net.socket"; 5459import { BusinessError } from '@ohos.base'; 5460let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 5461let tlsConnectOptions: socket.TLSConnectOptions = { 5462 address: { 5463 address: '192.168.xx.xxx', 5464 port: 8080 5465 }, 5466 secureOptions: { 5467 key: "xxxx", 5468 cert: "xxxx", 5469 ca: ["xxxx"], 5470 password: "xxxx", 5471 protocols: socket.Protocol.TLSv12, 5472 useRemoteCipherPrefer: true, 5473 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 5474 cipherSuite: "AES256-SHA256" 5475 }, 5476 ALPNProtocols: ["spdy/1", "http/1.1"] 5477} 5478tlsServer.listen(tlsConnectOptions).then(() => { 5479 console.log("listen callback success"); 5480}).catch((err: BusinessError) => { 5481 console.log("failed" + err); 5482}); 5483tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 5484 client.close().then(() => { 5485 console.log('close success'); 5486 }).catch((err: BusinessError) => { 5487 console.log('close fail'); 5488 }); 5489}); 5490``` 5491 5492### getRemoteAddress<sup>10+</sup> 5493 5494getRemoteAddress(callback: AsyncCallback\<NetAddress\>): void 5495 5496Obtains the remote address of a TLS socket server connection. This API uses an asynchronous callback to return the result. 5497 5498**System capability**: SystemCapability.Communication.NetStack 5499 5500**Parameters** 5501 5502| Name | Type | Mandatory| Description | 5503| -------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | 5504| callback | AsyncCallback\<[NetAddress](#netaddress7)\> | 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.| 5505 5506**Error codes** 5507 5508| ID| Error Message | 5509| -------- | ------------------------------- | 5510| 401 | Parameter error. | 5511| 2303188 | Socket operation on non-socket. | 5512| 2300002 | System internal error. | 5513 5514**Example** 5515 5516```js 5517import socket from "@ohos.net.socket"; 5518import { BusinessError } from '@ohos.base'; 5519let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 5520let tlsConnectOptions: socket.TLSConnectOptions = { 5521 address: { 5522 address: '192.168.xx.xxx', 5523 port: 8080 5524 }, 5525 secureOptions: { 5526 key: "xxxx", 5527 cert: "xxxx", 5528 ca: ["xxxx"], 5529 password: "xxxx", 5530 protocols: socket.Protocol.TLSv12, 5531 useRemoteCipherPrefer: true, 5532 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 5533 cipherSuite: "AES256-SHA256" 5534 }, 5535 ALPNProtocols: ["spdy/1", "http/1.1"] 5536} 5537tlsServer.listen(tlsConnectOptions).then(() => { 5538 console.log("listen callback success"); 5539}).catch((err: BusinessError) => { 5540 console.log("failed" + err); 5541}); 5542tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 5543 client.getRemoteAddress((err: BusinessError, data: socket.NetAddress) => { 5544 if (err) { 5545 console.log('getRemoteAddress fail'); 5546 return; 5547 } 5548 console.log('getRemoteAddress success:' + JSON.stringify(data)); 5549 }); 5550}); 5551``` 5552 5553### getRemoteAddress<sup>10+</sup> 5554 5555getRemoteAddress(): Promise\<NetAddress\> 5556 5557Obtains the remote address of a TLS socket server connection. This API uses a promise to return the result. 5558 5559**System capability**: SystemCapability.Communication.NetStack 5560 5561**Return value** 5562 5563| Type | Description | 5564| :----------------------------------- | :----------------------------------------------------------- | 5565| Promise\<[NetAddress](#netaddress7)> | Promise used to return the result. If the operation fails, an error message is returned.| 5566 5567**Error codes** 5568 5569| ID| Error Message | 5570| -------- | ------------------------------- | 5571| 2303188 | Socket operation on non-socket. | 5572| 2300002 | System internal error. | 5573 5574**Example** 5575 5576```js 5577import socket from "@ohos.net.socket"; 5578import { BusinessError } from '@ohos.base'; 5579let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 5580let tlsConnectOptions: socket.TLSConnectOptions = { 5581 address: { 5582 address: '192.168.xx.xxx', 5583 port: 8080 5584 }, 5585 secureOptions: { 5586 key: "xxxx", 5587 cert: "xxxx", 5588 ca: ["xxxx"], 5589 password: "xxxx", 5590 protocols: socket.Protocol.TLSv12, 5591 useRemoteCipherPrefer: true, 5592 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 5593 cipherSuite: "AES256-SHA256" 5594 }, 5595 ALPNProtocols: ["spdy/1", "http/1.1"] 5596} 5597tlsServer.listen(tlsConnectOptions).then(() => { 5598 console.log("listen callback success"); 5599}).catch((err: BusinessError) => { 5600 console.log("failed" + err); 5601}); 5602tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 5603 client.getRemoteAddress().then((data: socket.NetAddress) => { 5604 console.log('getRemoteAddress success:' + JSON.stringify(data)); 5605 }).catch((err: BusinessError) => { 5606 console.error("failed" + err); 5607 }); 5608}); 5609``` 5610 5611### getRemoteCertificate<sup>10+</sup> 5612 5613getRemoteCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)\>): void 5614 5615Obtains 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. 5616 5617**System capability**: SystemCapability.Communication.NetStack 5618 5619**Parameters** 5620 5621| Name | Type | Mandatory| Description | 5622| -------- | ----------------------------------------------------- | ---- | ---------------------------------------------------- | 5623| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| 5624 5625**Error codes** 5626 5627| ID| Error Message | 5628| -------- | ---------------------- | 5629| 401 | Parameter error. | 5630| 2303501 | SSL is null. | 5631| 2300002 | System internal error. | 5632 5633**Example** 5634 5635```js 5636import socket from "@ohos.net.socket"; 5637import { BusinessError } from '@ohos.base'; 5638let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 5639let tlsConnectOptions: socket.TLSConnectOptions = { 5640 address: { 5641 address: '192.168.xx.xxx', 5642 port: 8080 5643 }, 5644 secureOptions: { 5645 key: "xxxx", 5646 cert: "xxxx", 5647 ca: ["xxxx"], 5648 password: "xxxx", 5649 protocols: socket.Protocol.TLSv12, 5650 useRemoteCipherPrefer: true, 5651 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 5652 cipherSuite: "AES256-SHA256" 5653 }, 5654 ALPNProtocols: ["spdy/1", "http/1.1"] 5655} 5656tlsServer.listen(tlsConnectOptions).then(() => { 5657 console.log("listen callback success"); 5658}).catch((err: BusinessError) => { 5659 console.log("failed" + err); 5660}); 5661tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 5662 client.getRemoteCertificate((err: BusinessError, data: socket.X509CertRawData) => { 5663 if (err) { 5664 console.log("getRemoteCertificate callback error = " + err); 5665 } else { 5666 console.log("getRemoteCertificate callback = " + data); 5667 } 5668 }); 5669}); 5670``` 5671 5672### getRemoteCertificate<sup>10+</sup> 5673 5674getRemoteCertificate():Promise\<[X509CertRawData](#x509certrawdata9)\> 5675 5676Obtains 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. 5677 5678**System capability**: SystemCapability.Communication.NetStack 5679 5680**Return value** 5681 5682| Type | Description | 5683| ----------------------------------------------- | ------------------------------------------------------------ | 5684| Promise\<[X509CertRawData](#x509certrawdata9)\> | Promise used to return the result. If the operation fails, an error message is returned.| 5685 5686**Error codes** 5687 5688| ID| Error Message | 5689| -------- | ---------------------- | 5690| 2303501 | SSL is null. | 5691| 2300002 | System internal error. | 5692 5693**Example** 5694 5695```js 5696import socket from "@ohos.net.socket"; 5697import { BusinessError } from '@ohos.base'; 5698let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 5699let tlsConnectOptions: socket.TLSConnectOptions = { 5700 address: { 5701 address: '192.168.xx.xxx', 5702 port: 8080 5703 }, 5704 secureOptions: { 5705 key: "xxxx", 5706 cert: "xxxx", 5707 ca: ["xxxx"], 5708 password: "xxxx", 5709 protocols: socket.Protocol.TLSv12, 5710 useRemoteCipherPrefer: true, 5711 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 5712 cipherSuite: "AES256-SHA256" 5713 }, 5714 ALPNProtocols: ["spdy/1", "http/1.1"] 5715} 5716tlsServer.listen(tlsConnectOptions).then(() => { 5717 console.log("listen callback success"); 5718}).catch((err: BusinessError) => { 5719 console.log("failed" + err); 5720}); 5721tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 5722 client.getRemoteCertificate().then((data: socket.X509CertRawData) => { 5723 console.log('getRemoteCertificate success:' + JSON.stringify(data)); 5724 }).catch((err: BusinessError) => { 5725 console.error("failed" + err); 5726 }); 5727}); 5728``` 5729 5730### getCipherSuite<sup>10+</sup> 5731 5732getCipherSuite(callback: AsyncCallback\<Array\<string\>\>): void 5733 5734Obtains 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. 5735 5736**System capability**: SystemCapability.Communication.NetStack 5737 5738**Parameters** 5739 5740| Name | Type | Mandatory| Description | 5741| -------- | -------------------------------- | ---- | ------------------------------------------------------------ | 5742| callback | AsyncCallback\<Array\<string\>\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| 5743 5744**Error codes** 5745 5746| ID| Error Message | 5747| -------- | -------------------------------------- | 5748| 401 | Parameter error. | 5749| 2303501 | SSL is null. | 5750| 2303502 | Error in tls reading. | 5751| 2303505 | Error occurred in the tls system call. | 5752| 2300002 | System internal error. | 5753 5754**Example** 5755 5756```js 5757import socket from "@ohos.net.socket"; 5758import { BusinessError } from '@ohos.base'; 5759let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 5760let tlsConnectOptions: socket.TLSConnectOptions = { 5761 address: { 5762 address: '192.168.xx.xxx', 5763 port: 8080 5764 }, 5765 secureOptions: { 5766 key: "xxxx", 5767 cert: "xxxx", 5768 ca: ["xxxx"], 5769 password: "xxxx", 5770 protocols: socket.Protocol.TLSv12, 5771 useRemoteCipherPrefer: true, 5772 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 5773 cipherSuite: "AES256-SHA256" 5774 }, 5775 ALPNProtocols: ["spdy/1", "http/1.1"] 5776} 5777tlsServer.listen(tlsConnectOptions).then(() => { 5778 console.log("listen callback success"); 5779}).catch((err: BusinessError) => { 5780 console.log("failed" + err); 5781}); 5782tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 5783 client.getCipherSuite((err: BusinessError, data: Array<string>) => { 5784 if (err) { 5785 console.log("getCipherSuite callback error = " + err); 5786 } else { 5787 console.log("getCipherSuite callback = " + data); 5788 } 5789 }); 5790}); 5791``` 5792 5793### getCipherSuite<sup>10+</sup> 5794 5795getCipherSuite(): Promise\<Array\<string\>\> 5796 5797Obtains 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. 5798 5799**System capability**: SystemCapability.Communication.NetStack 5800 5801**Return value** 5802 5803| Type | Description | 5804| -------------------------- | ------------------------------------------------------------ | 5805| Promise\<Array\<string\>\> | Promise used to return the result. If the operation fails, an error message is returned.| 5806 5807**Error codes** 5808 5809| ID| Error Message | 5810| -------- | -------------------------------------- | 5811| 2303501 | SSL is null. | 5812| 2303502 | Error in tls reading. | 5813| 2303505 | Error occurred in the tls system call. | 5814| 2300002 | System internal error. | 5815 5816**Example** 5817 5818```js 5819import socket from "@ohos.net.socket"; 5820import { BusinessError } from '@ohos.base'; 5821let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 5822let tlsConnectOptions: socket.TLSConnectOptions = { 5823 address: { 5824 address: '192.168.xx.xxx', 5825 port: 8080 5826 }, 5827 secureOptions: { 5828 key: "xxxx", 5829 cert: "xxxx", 5830 ca: ["xxxx"], 5831 password: "xxxx", 5832 protocols: socket.Protocol.TLSv12, 5833 useRemoteCipherPrefer: true, 5834 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 5835 cipherSuite: "AES256-SHA256" 5836 }, 5837 ALPNProtocols: ["spdy/1", "http/1.1"] 5838} 5839tlsServer.listen(tlsConnectOptions).then(() => { 5840 console.log("listen callback success"); 5841}).catch((err: BusinessError) => { 5842 console.log("failed" + err); 5843}); 5844tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 5845 client.getCipherSuite().then((data: Array<string>) => { 5846 console.log('getCipherSuite success:' + JSON.stringify(data)); 5847 }).catch((err: BusinessError) => { 5848 console.error("failed" + err); 5849 }); 5850}); 5851``` 5852 5853### getSignatureAlgorithms<sup>10+</sup> 5854 5855getSignatureAlgorithms(callback: AsyncCallback\<Array\<string\>\>): void 5856 5857Obtains 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. 5858 5859**System capability**: SystemCapability.Communication.NetStack 5860 5861**Parameters** 5862 5863| Name | Type | Mandatory| Description | 5864| -------- | -------------------------------- | ---- | ---------------------------------- | 5865| callback | AsyncCallback\<Array\<string\>\> | Yes | Callback used to return the result. | 5866 5867**Error codes** 5868 5869| ID| Error Message | 5870| -------- | ---------------------- | 5871| 401 | Parameter error. | 5872| 2303501 | SSL is null. | 5873| 2300002 | System internal error. | 5874 5875**Example** 5876 5877```js 5878import socket from "@ohos.net.socket"; 5879import { BusinessError } from '@ohos.base'; 5880let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 5881let tlsConnectOptions: socket.TLSConnectOptions = { 5882 address: { 5883 address: '192.168.xx.xxx', 5884 port: 8080 5885 }, 5886 secureOptions: { 5887 key: "xxxx", 5888 cert: "xxxx", 5889 ca: ["xxxx"], 5890 password: "xxxx", 5891 protocols: socket.Protocol.TLSv12, 5892 useRemoteCipherPrefer: true, 5893 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 5894 cipherSuite: "AES256-SHA256" 5895 }, 5896 ALPNProtocols: ["spdy/1", "http/1.1"] 5897} 5898tlsServer.listen(tlsConnectOptions).then(() => { 5899 console.log("listen callback success"); 5900}).catch((err: BusinessError) => { 5901 console.log("failed" + err); 5902}); 5903tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 5904 client.getSignatureAlgorithms((err: BusinessError, data: Array<string>) => { 5905 if (err) { 5906 console.log("getSignatureAlgorithms callback error = " + err); 5907 } else { 5908 console.log("getSignatureAlgorithms callback = " + data); 5909 } 5910 }); 5911}); 5912``` 5913 5914### getSignatureAlgorithms<sup>10+</sup> 5915 5916getSignatureAlgorithms(): Promise\<Array\<string\>\> 5917 5918Obtains 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. 5919 5920**System capability**: SystemCapability.Communication.NetStack 5921 5922**Return value** 5923 5924| Type | Description | 5925| -------------------------- | --------------------------------------------- | 5926| Promise\<Array\<string\>\> | Promise used to return the result.| 5927 5928**Error codes** 5929 5930| ID| Error Message | 5931| -------- | ---------------------- | 5932| 2303501 | SSL is null. | 5933| 2300002 | System internal error. | 5934 5935**Example** 5936 5937```js 5938import socket from "@ohos.net.socket"; 5939import { BusinessError } from '@ohos.base'; 5940let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 5941let tlsConnectOptions: socket.TLSConnectOptions = { 5942 address: { 5943 address: '192.168.xx.xxx', 5944 port: 8080 5945 }, 5946 secureOptions: { 5947 key: "xxxx", 5948 cert: "xxxx", 5949 ca: ["xxxx"], 5950 password: "xxxx", 5951 protocols: socket.Protocol.TLSv12, 5952 useRemoteCipherPrefer: true, 5953 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 5954 cipherSuite: "AES256-SHA256" 5955 }, 5956 ALPNProtocols: ["spdy/1", "http/1.1"] 5957} 5958tlsServer.listen(tlsConnectOptions).then(() => { 5959 console.log("listen callback success"); 5960}).catch((err: BusinessError) => { 5961 console.log("failed" + err); 5962}); 5963tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 5964 client.getSignatureAlgorithms().then((data: Array<string>) => { 5965 console.log("getSignatureAlgorithms success" + data); 5966 }).catch((err: BusinessError) => { 5967 console.error("failed" + err); 5968 }); 5969}); 5970``` 5971 5972### on('message')<sup>10+</sup> 5973 5974on(type: 'message', callback: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void 5975 5976Subscribes to **message** events of a **TLSSocketConnection** object. This API uses an asynchronous callback to return the result. 5977 5978**System capability**: SystemCapability.Communication.NetStack 5979 5980**Parameters** 5981 5982| Name | Type | Mandatory| Description | 5983| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 5984| type | string | Yes | Type of the event to subscribe to.<br/> **message**: message receiving event.| 5985| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo7)}> | Yes | Callback used to return the result. | 5986 5987**Error codes** 5988 5989| ID| Error Message | 5990| -------- | ---------------- | 5991| 401 | Parameter error. | 5992 5993**Example** 5994 5995```js 5996import socket from "@ohos.net.socket"; 5997import { BusinessError } from '@ohos.base'; 5998let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 5999let tlsConnectOptions: socket.TLSConnectOptions = { 6000 address: { 6001 address: '192.168.xx.xxx', 6002 port: 8080 6003 }, 6004 secureOptions: { 6005 key: "xxxx", 6006 cert: "xxxx", 6007 ca: ["xxxx"], 6008 password: "xxxx", 6009 protocols: socket.Protocol.TLSv12, 6010 useRemoteCipherPrefer: true, 6011 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 6012 cipherSuite: "AES256-SHA256" 6013 }, 6014 ALPNProtocols: ["spdy/1", "http/1.1"] 6015} 6016tlsServer.listen(tlsConnectOptions).then(() => { 6017 console.log("listen callback success"); 6018}).catch((err: BusinessError) => { 6019 console.log("failed" + err); 6020}); 6021 6022class SocketInfo { 6023 message: ArrayBuffer = new ArrayBuffer(1); 6024 remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 6025} 6026tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 6027 client.on('message', (value: SocketInfo) => { 6028 let messageView = ''; 6029 for (let i: number = 0; i < value.message.byteLength; i++) { 6030 let messages: number = value.message[i] 6031 let message = String.fromCharCode(messages); 6032 messageView += message; 6033 } 6034 console.log('on message message: ' + JSON.stringify(messageView)); 6035 console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo)); 6036 }); 6037}); 6038``` 6039 6040### off('message')<sup>10+</sup> 6041 6042off(type: 'message', callback?: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void 6043 6044Unsubscribes from **message** events of a **TLSSocketConnection** object. This API uses an asynchronous callback to return the result. 6045 6046> **NOTE** 6047> 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. 6048 6049**System capability**: SystemCapability.Communication.NetStack 6050 6051**Parameters** 6052 6053| Name | Type | Mandatory| Description | 6054| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 6055| type | string | Yes | Type of the event to subscribe to.<br/> **message**: message receiving event.| 6056| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo7)}> | No | Callback used to return the result. | 6057 6058**Error codes** 6059 6060| ID| Error Message | 6061| -------- | ---------------- | 6062| 401 | Parameter error. | 6063 6064**Example** 6065 6066```js 6067import socket from "@ohos.net.socket"; 6068import { BusinessError } from '@ohos.base'; 6069let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 6070let tlsConnectOptions: socket.TLSConnectOptions = { 6071 address: { 6072 address: '192.168.xx.xxx', 6073 port: 8080 6074 }, 6075 secureOptions: { 6076 key: "xxxx", 6077 cert: "xxxx", 6078 ca: ["xxxx"], 6079 password: "xxxx", 6080 protocols: socket.Protocol.TLSv12, 6081 useRemoteCipherPrefer: true, 6082 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 6083 cipherSuite: "AES256-SHA256" 6084 }, 6085 ALPNProtocols: ["spdy/1", "http/1.1"] 6086} 6087tlsServer.listen(tlsConnectOptions).then(() => { 6088 console.log("listen callback success"); 6089}).catch((err: BusinessError) => { 6090 console.log("failed" + err); 6091}); 6092 6093class SocketInfo { 6094 message: ArrayBuffer = new ArrayBuffer(1); 6095 remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 6096} 6097let callback = (value: SocketInfo) => { 6098 let messageView = ''; 6099 for (let i: number = 0; i < value.message.byteLength; i++) { 6100 let messages: number = value.message[i] 6101 let message = String.fromCharCode(messages); 6102 messageView += message; 6103 } 6104 console.log('on message message: ' + JSON.stringify(messageView)); 6105 console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo)); 6106} 6107tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 6108 client.on('message', callback); 6109 // 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. 6110 client.off('message', callback); 6111 client.off('message'); 6112}); 6113``` 6114 6115### on('close')<sup>10+</sup> 6116 6117on(type: 'close', callback: Callback\<void\>): void 6118 6119Subscribes to **close** events of a **TLSSocketConnection** object. This API uses an asynchronous callback to return the result. 6120 6121**System capability**: SystemCapability.Communication.NetStack 6122 6123**Parameters** 6124 6125| Name | Type | Mandatory| Description | 6126| -------- | ---------------- | ---- | ----------------------------------- | 6127| type | string | Yes | Type of the event to subscribe to.<br/> **close**: close event.| 6128| callback | Callback\<void\> | Yes | Callback used to return the result. | 6129 6130**Error codes** 6131 6132| ID| Error Message | 6133| -------- | ---------------- | 6134| 401 | Parameter error. | 6135 6136**Example** 6137 6138```js 6139import socket from "@ohos.net.socket"; 6140import { BusinessError } from '@ohos.base'; 6141let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 6142let tlsConnectOptions: socket.TLSConnectOptions = { 6143 address: { 6144 address: '192.168.xx.xxx', 6145 port: 8080 6146 }, 6147 secureOptions: { 6148 key: "xxxx", 6149 cert: "xxxx", 6150 ca: ["xxxx"], 6151 password: "xxxx", 6152 protocols: socket.Protocol.TLSv12, 6153 useRemoteCipherPrefer: true, 6154 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 6155 cipherSuite: "AES256-SHA256" 6156 }, 6157 ALPNProtocols: ["spdy/1", "http/1.1"] 6158} 6159tlsServer.listen(tlsConnectOptions).then(() => { 6160 console.log("listen callback success"); 6161}).catch((err: BusinessError) => { 6162 console.log("failed" + err); 6163}); 6164tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 6165 client.on('close', () => { 6166 console.log("on close success") 6167 }); 6168}); 6169``` 6170 6171### off('close')<sup>10+</sup> 6172 6173off(type: 'close', callback?: Callback\<void\>): void 6174 6175Unsubscribes from **close** events of a **TLSSocketConnection** object. This API uses an asynchronous callback to return the result. 6176 6177> **NOTE** 6178> 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. 6179 6180**System capability**: SystemCapability.Communication.NetStack 6181 6182**Parameters** 6183 6184| Name | Type | Mandatory| Description | 6185| -------- | ---------------- | ---- | ----------------------------------- | 6186| type | string | Yes | Type of the event to subscribe to.<br/> **close**: close event.| 6187| callback | Callback\<void\> | No | Callback used to return the result. | 6188 6189**Error codes** 6190 6191| ID| Error Message | 6192| -------- | ---------------- | 6193| 401 | Parameter error. | 6194 6195**Example** 6196 6197```js 6198import socket from "@ohos.net.socket"; 6199import { BusinessError } from '@ohos.base'; 6200let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 6201let tlsConnectOptions: socket.TLSConnectOptions = { 6202 address: { 6203 address: '192.168.xx.xxx', 6204 port: 8080 6205 }, 6206 secureOptions: { 6207 key: "xxxx", 6208 cert: "xxxx", 6209 ca: ["xxxx"], 6210 password: "xxxx", 6211 protocols: socket.Protocol.TLSv12, 6212 useRemoteCipherPrefer: true, 6213 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 6214 cipherSuite: "AES256-SHA256" 6215 }, 6216 ALPNProtocols: ["spdy/1", "http/1.1"] 6217} 6218tlsServer.listen(tlsConnectOptions).then(() => { 6219 console.log("listen callback success"); 6220}).catch((err: BusinessError) => { 6221 console.log("failed" + err); 6222}); 6223 6224let callback = () => { 6225 console.log("on close success"); 6226} 6227tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 6228 client.on('close', callback); 6229 // 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. 6230 client.off('close', callback); 6231 client.off('close'); 6232}); 6233``` 6234 6235### on('error')<sup>10+</sup> 6236 6237on(type: 'error', callback: ErrorCallback): void 6238 6239Subscribes to **error** events of a **TLSSocketConnection** object. This API uses an asynchronous callback to return the result. 6240 6241**System capability**: SystemCapability.Communication.NetStack 6242 6243**Parameters** 6244 6245| Name | Type | Mandatory| Description | 6246| -------- | ------------- | ---- | ------------------------------------ | 6247| type | string | Yes | Type of the event to subscribe to.<br/> **error**: error event.| 6248| callback | ErrorCallback | Yes | Callback used to return the result. | 6249 6250**Error codes** 6251 6252| ID| Error Message | 6253| -------- | ---------------- | 6254| 401 | Parameter error. | 6255 6256**Example** 6257 6258```js 6259import socket from "@ohos.net.socket"; 6260import { BusinessError } from '@ohos.base'; 6261let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 6262let tlsConnectOptions: socket.TLSConnectOptions = { 6263 address: { 6264 address: '192.168.xx.xxx', 6265 port: 8080 6266 }, 6267 secureOptions: { 6268 key: "xxxx", 6269 cert: "xxxx", 6270 ca: ["xxxx"], 6271 password: "xxxx", 6272 protocols: socket.Protocol.TLSv12, 6273 useRemoteCipherPrefer: true, 6274 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 6275 cipherSuite: "AES256-SHA256" 6276 }, 6277 ALPNProtocols: ["spdy/1", "http/1.1"] 6278} 6279tlsServer.listen(tlsConnectOptions).then(() => { 6280 console.log("listen callback success"); 6281}).catch((err: BusinessError) => { 6282 console.log("failed" + err); 6283}); 6284 6285tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 6286 client.on('error', (err: BusinessError) => { 6287 console.log("on error, err:" + JSON.stringify(err)) 6288 }); 6289}); 6290``` 6291 6292### off('error')<sup>10+</sup> 6293 6294off(type: 'error', callback?: ErrorCallback): void 6295 6296Unsubscribes from **error** events of a **TLSSocketConnection** object. This API uses an asynchronous callback to return the result. 6297 6298> **NOTE** 6299> 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. 6300 6301**System capability**: SystemCapability.Communication.NetStack 6302 6303**Parameters** 6304 6305| Name | Type | Mandatory| Description | 6306| -------- | ------------- | ---- | ------------------------------------ | 6307| type | string | Yes | Type of the event to subscribe to.<br/> **error**: error event.| 6308| callback | ErrorCallback | No | Callback used to return the result. | 6309 6310**Error codes** 6311 6312| ID| Error Message | 6313| -------- | ---------------- | 6314| 401 | Parameter error. | 6315 6316**Example** 6317 6318```js 6319import socket from "@ohos.net.socket"; 6320import { BusinessError } from '@ohos.base'; 6321let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 6322let tlsConnectOptions: socket.TLSConnectOptions = { 6323 address: { 6324 address: '192.168.xx.xxx', 6325 port: 8080 6326 }, 6327 secureOptions: { 6328 key: "xxxx", 6329 cert: "xxxx", 6330 ca: ["xxxx"], 6331 password: "xxxx", 6332 protocols: socket.Protocol.TLSv12, 6333 useRemoteCipherPrefer: true, 6334 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 6335 cipherSuite: "AES256-SHA256" 6336 }, 6337 ALPNProtocols: ["spdy/1", "http/1.1"] 6338} 6339tlsServer.listen(tlsConnectOptions).then(() => { 6340 console.log("listen callback success"); 6341}).catch((err: BusinessError) => { 6342 console.log("failed" + err); 6343}); 6344 6345let callback = (err: BusinessError) => { 6346 console.log("on error, err:" + JSON.stringify(err)); 6347} 6348tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 6349 client.on('error', callback); 6350 // 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. 6351 client.off('error', callback); 6352 client.off('error'); 6353}); 6354``` 6355