1# @ohos.net.socket (Socket连接) 2 3本模块提供利用Socket进行数据传输的能力,支持TCPSocket、UDPSocket、WebSocket和TLSSocket。 4 5> **说明:** 6> 7> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 8 9## 导入模块 10 11```js 12import socket from '@ohos.net.socket'; 13``` 14 15## socket.constructUDPSocketInstance<sup>7+</sup> 16 17constructUDPSocketInstance(): UDPSocket 18 19创建一个UDPSocket对象。 20 21**系统能力**:SystemCapability.Communication.NetStack 22 23**返回值:** 24 25| 类型 | 说明 | 26| :--------------------------------- | :---------------------- | 27| [UDPSocket](#udpsocket) | 返回一个UDPSocket对象。 | 28 29**示例:** 30 31```js 32import socket from '@ohos.net.socket'; 33let udp: socket.UDPSocket = socket.constructUDPSocketInstance(); 34``` 35 36## UDPSocket<sup>7+</sup> 37 38UDPSocket连接。在调用UDPSocket的方法前,需要先通过[socket.constructUDPSocketInstance](#socketconstructudpsocketinstance)创建UDPSocket对象。 39 40### bind<sup>7+</sup> 41 42bind(address: NetAddress, callback: AsyncCallback\<void\>): void 43 44绑定IP地址和端口,端口可以指定或由系统随机分配。使用callback方式作为异步方法。 45 46**需要权限**:ohos.permission.INTERNET 47 48**系统能力**:SystemCapability.Communication.NetStack 49 50**参数:** 51 52| 参数名 | 类型 | 必填 | 说明 | 53| -------- | ---------------------------------- | ---- | ------------------------------------------------------ | 54| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 | 55| callback | AsyncCallback\<void\> | 是 | 回调函数。 | 56 57**错误码:** 58 59| 错误码ID | 错误信息 | 60| ------- | ----------------------- | 61| 401 | Parameter error. | 62| 201 | Permission denied. | 63 64**示例:** 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 88绑定IP地址和端口,端口可以指定或由系统随机分配。使用Promise方式作为异步方法。 89 90**需要权限**:ohos.permission.INTERNET 91 92**系统能力**:SystemCapability.Communication.NetStack 93 94**参数:** 95 96| 参数名 | 类型 | 必填 | 说明 | 97| ------- | ---------------------------------- | ---- | ------------------------------------------------------ | 98| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 | 99 100**错误码:** 101 102| 错误码ID | 错误信息 | 103| ------- | ----------------------- | 104| 401 | Parameter error. | 105| 201 | Permission denied. | 106 107**返回值:** 108 109| 类型 | 说明 | 110| :-------------- | :----------------------------------------- | 111| Promise\<void\> | 以Promise形式异步返回UDPSocket绑定的结果。 | 112 113**示例:** 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 135通过UDPSocket连接发送数据。使用callback方式作为异步方法。 136 137发送数据前,需要先调用[UDPSocket.bind()](#bind)绑定IP地址和端口。 138 139**需要权限**:ohos.permission.INTERNET 140 141**系统能力**:SystemCapability.Communication.NetStack 142 143**参数:** 144 145| 参数名 | 类型 | 必填 | 说明 | 146| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | 147| options | [UDPSendOptions](#udpsendoptions) | 是 | UDPSocket发送参数,参考[UDPSendOptions](#udpsendoptions)。 | 148| callback | AsyncCallback\<void\> | 是 | 回调函数。 | 149 150**错误码:** 151 152| 错误码ID | 错误信息 | 153| ------- | ----------------------- | 154| 401 | Parameter error. | 155| 201 | Permission denied. | 156 157**示例:** 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 185通过UDPSocket连接发送数据。使用Promise方式作为异步方法。 186 187发送数据前,需要先调用[UDPSocket.bind()](#bind)绑定IP地址和端口。 188 189**需要权限**:ohos.permission.INTERNET 190 191**系统能力**:SystemCapability.Communication.NetStack 192 193**参数:** 194 195| 参数名 | 类型 | 必填 | 说明 | 196| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | 197| options | [UDPSendOptions](#udpsendoptions) | 是 | UDPSocket发送参数,参考[UDPSendOptions](#udpsendoptions)。 | 198 199**错误码:** 200 201| 错误码ID | 错误信息 | 202| ------- | ----------------------- | 203| 401 | Parameter error. | 204| 201 | Permission denied. | 205 206**返回值:** 207 208| 类型 | 说明 | 209| :-------------- | :--------------------------------------------- | 210| Promise\<void\> | 以Promise形式返回UDPSocket连接发送数据的结果。 | 211 212**示例:** 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 238关闭UDPSocket连接。使用callback方式作为异步方法。 239 240**需要权限**:ohos.permission.INTERNET 241 242**系统能力**:SystemCapability.Communication.NetStack 243 244**参数:** 245 246| 参数名 | 类型 | 必填 | 说明 | 247| -------- | --------------------- | ---- | ---------- | 248| callback | AsyncCallback\<void\> | 是 | 回调函数。 | 249 250**示例:** 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 270关闭UDPSocket连接。使用Promise方式作为异步方法。 271 272**需要权限**:ohos.permission.INTERNET 273 274**系统能力**:SystemCapability.Communication.NetStack 275 276**返回值:** 277 278| 类型 | 说明 | 279| :-------------- | :----------------------------------------- | 280| Promise\<void\> | 以Promise形式返回关闭UDPSocket连接的结果。 | 281 282**示例:** 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 300获取UDPSocket状态。使用callback方式作为异步方法。 301 302> **说明:** 303> bind方法调用成功后,才可调用此方法。 304 305**需要权限**:ohos.permission.INTERNET 306 307**系统能力**:SystemCapability.Communication.NetStack 308 309**参数:** 310 311| 参数名 | 类型 | 必填 | 说明 | 312| -------- | ------------------------------------------------------ | ---- | ---------- | 313| callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | 是 | 回调函数。 | 314 315**错误码:** 316 317| 错误码ID | 错误信息 | 318| ------- | ----------------------- | 319| 201 | Permission denied. | 320 321**示例:** 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 352获取UDPSocket状态。使用Promise方式作为异步方法。 353 354> **说明:** 355> bind方法调用成功后,才可调用此方法。 356 357**需要权限**:ohos.permission.INTERNET 358 359**系统能力**:SystemCapability.Communication.NetStack 360 361**返回值:** 362 363| 类型 | 说明 | 364| :----------------------------------------------- | :----------------------------------------- | 365| Promise\<[SocketStateBase](#socketstatebase)\> | 以Promise形式返回获取UDPSocket状态的结果。 | 366 367**示例:** 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 396设置UDPSocket连接的其他属性。使用callback方式作为异步方法。 397 398> **说明:** 399> bind方法调用成功后,才可调用此方法。 400 401**需要权限**:ohos.permission.INTERNET 402 403**系统能力**:SystemCapability.Communication.NetStack 404 405**参数:** 406 407| 参数名 | 类型 | 必填 | 说明 | 408| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | 409| options | [UDPExtraOptions](#udpextraoptions) | 是 | UDPSocket连接的其他属性,参考[UDPExtraOptions](#udpextraoptions)。 | 410| callback | AsyncCallback\<void\> | 是 | 回调函数。 | 411 412**错误码:** 413 414| 错误码ID | 错误信息 | 415| ------- | ----------------------- | 416| 401 | Parameter error. | 417| 201 | Permission denied. | 418 419**示例:** 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 458设置UDPSocket连接的其他属性。使用Promise方式作为异步方法。 459 460> **说明:** 461> bind方法调用成功后,才可调用此方法。 462 463**需要权限**:ohos.permission.INTERNET 464 465**系统能力**:SystemCapability.Communication.NetStack 466 467**参数:** 468 469| 参数名 | 类型 | 必填 | 说明 | 470| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | 471| options | [UDPExtraOptions](#udpextraoptions) | 是 | UDPSocket连接的其他属性,参考[UDPExtraOptions](#udpextraoptions)。 | 472 473**返回值:** 474 475| 类型 | 说明 | 476| :-------------- | :--------------------------------------------------- | 477| Promise\<void\> | 以Promise形式返回设置UDPSocket连接的其他属性的结果。 | 478 479**错误码:** 480 481| 错误码ID | 错误信息 | 482| ------- | ----------------------- | 483| 401 | Parameter error. | 484| 201 | Permission denied. | 485 486**示例:** 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 523订阅UDPSocket连接的接收消息事件。使用callback方式作为异步方法。 524 525**系统能力**:SystemCapability.Communication.NetStack 526 527**参数:** 528 529| 参数名 | 类型 | 必填 | 说明 | 530| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 531| type | string | 是 | 订阅的事件类型。'message':接收消息事件。 | 532| callback | Callback\<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}\> | 是 | 回调函数。 | 533 534**示例:** 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 561取消订阅UDPSocket连接的接收消息事件。使用callback方式作为异步方法。 562 563> **说明:** 564> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 565 566**系统能力**:SystemCapability.Communication.NetStack 567 568**参数:** 569 570| 参数名 | 类型 | 必填 | 说明 | 571| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 572| type | string | 是 | 订阅的事件类型。'message':接收消息事件。 | 573| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | 否 | 回调函数。 | 574 575**示例:** 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// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 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 605订阅UDPSocket连接的数据包消息事件或关闭事件。使用callback方式作为异步方法。 606 607**系统能力**:SystemCapability.Communication.NetStack 608 609**参数:** 610 611| 参数名 | 类型 | 必填 | 说明 | 612| -------- | ---------------- | ---- | ------------------------------------------------------------ | 613| type | string | 是 | 订阅的事件类型。<br />- 'listening':数据包消息事件。<br />- 'close':关闭事件。 | 614| callback | Callback\<void\> | 是 | 回调函数。 | 615 616**示例:** 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 634取消订阅UDPSocket连接的数据包消息事件或关闭事件。使用callback方式作为异步方法。 635 636> **说明:** 637> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 638 639**系统能力**:SystemCapability.Communication.NetStack 640 641**参数:** 642 643| 参数名 | 类型 | 必填 | 说明 | 644| -------- | ---------------- | ---- | ------------------------------------------------------------ | 645| type | string | 是 | 订阅事件类型。<br />- 'listening':数据包消息事件。<br />- 'close':关闭事件。 | 646| callback | Callback\<void\> | 否 | 回调函数。 | 647 648**示例:** 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// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 659udp.off('listening', callback1); 660udp.off('listening'); 661let callback2 = () => { 662 console.log("on close, success"); 663} 664udp.on('close', callback2); 665// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 666udp.off('close', callback2); 667udp.off('close'); 668``` 669 670### on('error')<sup>7+</sup> 671 672on(type: 'error', callback: ErrorCallback): void 673 674订阅UDPSocket连接的error事件。使用callback方式作为异步方法。 675 676**系统能力**:SystemCapability.Communication.NetStack 677 678**参数:** 679 680| 参数名 | 类型 | 必填 | 说明 | 681| -------- | ------------- | ---- | ------------------------------------ | 682| type | string | 是 | 订阅的事件类型。'error':error事件。 | 683| callback | ErrorCallback | 是 | 回调函数。 | 684 685**示例:** 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 700取消订阅UDPSocket连接的error事件。使用callback方式作为异步方法。 701 702> **说明:** 703> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 704 705**系统能力**:SystemCapability.Communication.NetStack 706 707**参数:** 708 709| 参数名 | 类型 | 必填 | 说明 | 710| -------- | ------------- | ---- | ------------------------------------ | 711| type | string | 是 | 订阅的事件类型。'error':error事件。 | 712| callback | ErrorCallback | 否 | 回调函数。 | 713 714**示例:** 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// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 725udp.off('error', callback); 726udp.off('error'); 727``` 728 729## NetAddress<sup>7+</sup> 730 731目标地址信息。 732 733**系统能力**:SystemCapability.Communication.NetStack 734 735| 名称 | 类型 | 必填 | 说明 | 736| ------- | ------ | ---- | ------------------------------------------------------------ | 737| address | string | 是 | 本地绑定的ip地址。 | 738| port | number | 否 | 端口号 ,范围0~65535。如果不指定系统随机分配端口。 | 739| family | number | 否 | 网络协议类型,可选类型:<br />- 1:IPv4<br />- 2:IPv6<br />默认为1。 | 740 741## UDPSendOptions<sup>7+</sup> 742 743UDPSocket发送参数。 744 745**系统能力**:SystemCapability.Communication.NetStack 746 747| 名称 | 类型 | 必填 | 说明 | 748| ------- | ---------------------------------- | ---- | -------------- | 749| data | string \| ArrayBuffer<sup>7+</sup> | 是 | 发送的数据。 | 750| address | [NetAddress](#netaddress) | 是 | 目标地址信息。 | 751 752## UDPExtraOptions<sup>7+</sup> 753 754UDPSocket连接的其他属性。 755 756**系统能力**:SystemCapability.Communication.NetStack 757 758| 名称 | 类型 | 必填 | 说明 | 759| ----------------- | ------- | ---- | -------------------------------- | 760| broadcast | boolean | 否 | 是否可以发送广播。默认为false。 | 761| receiveBufferSize | number | 否 | 接收缓冲区大小(单位:Byte),默认为0。 | 762| sendBufferSize | number | 否 | 发送缓冲区大小(单位:Byte),默认为0。 | 763| reuseAddress | boolean | 否 | 是否重用地址。默认为false。 | 764| socketTimeout | number | 否 | 套接字超时时间,单位毫秒(ms),默认为0。 | 765 766## SocketStateBase<sup>7+</sup> 767 768Socket的状态信息。 769 770**系统能力**:SystemCapability.Communication.NetStack 771 772| 名称 | 类型 | 必填 | 说明 | 773| ----------- | ------- | ---- | ---------- | 774| isBound | boolean | 是 | 是否绑定。 | 775| isClose | boolean | 是 | 是否关闭。 | 776| isConnected | boolean | 是 | 是否连接。 | 777 778## SocketRemoteInfo<sup>7+</sup> 779 780Socket的连接信息。 781 782**系统能力**:SystemCapability.Communication.NetStack 783 784| 名称 | 类型 | 必填 | 说明 | 785| ------- | ------ | ---- | ------------------------------------------------------------ | 786| address | string | 是 | 本地绑定的ip地址。 | 787| family | string | 是 | 网络协议类型,可选类型:<br />- IPv4<br />- IPv6<br />默认为IPv4。 | 788| port | number | 是 | 端口号,范围0~65535。 | 789| size | number | 是 | 服务器响应信息的字节长度。 | 790 791## UDP 错误码说明 792 793UDP 其余错误码映射形式为:2301000 + Linux内核错误码。 794 795错误码的详细介绍参见[Socket错误码](../errorcodes/errorcode-net-socket.md) 796 797## socket.constructTCPSocketInstance<sup>7+</sup> 798 799constructTCPSocketInstance(): TCPSocket 800 801创建一个TCPSocket对象。 802 803**系统能力**:SystemCapability.Communication.NetStack 804 805**返回值:** 806 807| 类型 | 说明 | 808 | :--------------------------------- | :---------------------- | 809| [TCPSocket](#tcpsocket) | 返回一个TCPSocket对象。 | 810 811**示例:** 812 813```js 814import socket from "@ohos.net.socket"; 815let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 816``` 817 818## TCPSocket<sup>7+</sup> 819 820TCPSocket连接。在调用TCPSocket的方法前,需要先通过[socket.constructTCPSocketInstance](#socketconstructtcpsocketinstance)创建TCPSocket对象。 821 822### bind<sup>7+</sup> 823 824bind(address: NetAddress, callback: AsyncCallback\<void\>): void 825 826绑定IP地址和端口,端口可以指定为0由系统随机分配或指定为其它非0端口。使用callback方法作为异步方法。 827 828> **说明:** 829> bind方法如果因为端口冲突而执行失败,则会由系统随机分配端口号。 830> TCP客户端可先调用该接口(tcp.bind)显式绑定IP地址和端口号,再调用tcp.connect完成与服务端的连接;也可直接调用tcp.connect由系统自动绑定IP地址和端口号,完成与服务端的连接。 831> bind的IP为'localhost'或'127.0.0.1'时,只允许本地回环接口的连接,即服务端和客户端运行在同一台机器上。 832 833**需要权限**:ohos.permission.INTERNET 834 835**系统能力**:SystemCapability.Communication.NetStack 836 837**参数:** 838 839| 参数名 | 类型 | 必填 | 说明 | 840| -------- | ---------------------------------- | ---- | ------------------------------------------------------ | 841| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 | 842| callback | AsyncCallback\<void\> | 是 | 回调函数。 | 843 844**错误码:** 845 846| 错误码ID | 错误信息 | 847| ------- | ----------------------- | 848| 401 | Parameter error. | 849| 201 | Permission denied. | 850 851**示例:** 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 874绑定IP地址和端口,端口可以指定为0由系统随机分配或指定为其它非0端口。使用Promise方法作为异步方法。 875 876> **说明:** 877> bind方法如果因为端口冲突而执行失败,则会由系统随机分配端口号。 878> TCP客户端可先调用该接口(tcp.bind)显式绑定IP地址和端口号,再调用tcp.connect完成与服务端的连接;也可直接调用tcp.connect由系统自动绑定IP地址和端口号,完成与服务端的连接。 879> bind的IP为'localhost'或'127.0.0.1'时,只允许本地回环接口的连接,即服务端和客户端运行在同一台机器上。 880 881**需要权限**:ohos.permission.INTERNET 882 883**系统能力**:SystemCapability.Communication.NetStack 884 885**参数:** 886 887| 参数名 | 类型 | 必填 | 说明 | 888| ------- | ---------------------------------- | ---- | ------------------------------------------------------ | 889| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 | 890 891**返回值:** 892 893| 类型 | 说明 | 894| :-------------- | :------------------------------------------------------- | 895| Promise\<void\> | 以Promise形式返回TCPSocket绑定本机的IP地址和端口的结果。 | 896 897**错误码:** 898 899| 错误码ID | 错误信息 | 900| ------- | ----------------------- | 901| 401 | Parameter error. | 902| 201 | Permission denied. | 903 904**示例:** 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 925连接到指定的IP地址和端口。使用callback方法作为异步方法。 926 927> **说明:** 928> 在没有执行tcp.bind的情况下,也可以直接调用该接口完成与TCP服务端的连接 929 930**需要权限**:ohos.permission.INTERNET 931 932**系统能力**:SystemCapability.Communication.NetStack 933 934**参数:** 935 936| 参数名 | 类型 | 必填 | 说明 | 937| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | 938| options | [TCPConnectOptions](#tcpconnectoptions) | 是 | TCPSocket连接的参数,参考[TCPConnectOptions](#tcpconnectoptions)。 | 939| callback | AsyncCallback\<void\> | 是 | 回调函数。 | 940 941**错误码:** 942 943| 错误码ID | 错误信息 | 944| ------- | ----------------------- | 945| 401 | Parameter error. | 946| 201 | Permission denied. | 947 948**示例:** 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 975连接到指定的IP地址和端口。使用promise方法作为异步方法。 976 977> **说明:** 978> 在没有执行tcp.bind的情况下,也可以直接调用该接口完成与TCP服务端的连接。 979 980**需要权限**:ohos.permission.INTERNET 981 982**系统能力**:SystemCapability.Communication.NetStack 983 984**参数:** 985 986| 参数名 | 类型 | 必填 | 说明 | 987| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | 988| options | [TCPConnectOptions](#tcpconnectoptions) | 是 | TCPSocket连接的参数,参考[TCPConnectOptions](#tcpconnectoptions)。 | 989 990**返回值:** 991 992| 类型 | 说明 | 993| :-------------- | :--------------------------------------------------------- | 994| Promise\<void\> | 以Promise形式返回TCPSocket连接到指定的IP地址和端口的结果。 | 995 996**错误码:** 997 998| 错误码ID | 错误信息 | 999| ------- | ----------------------- | 1000| 401 | Parameter error. | 1001| 201 | Permission denied. | 1002 1003**示例:** 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 1028通过TCPSocket连接发送数据。使用callback方式作为异步方法。 1029 1030> **说明:** 1031> connect方法调用成功后,才可调用此方法。 1032 1033**需要权限**:ohos.permission.INTERNET 1034 1035**系统能力**:SystemCapability.Communication.NetStack 1036 1037**参数:** 1038 1039| 参数名 | 类型 | 必填 | 说明 | 1040| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | 1041| options | [TCPSendOptions](#tcpsendoptions) | 是 | TCPSocket发送请求的参数,参考[TCPSendOptions](#tcpsendoptions)。 | 1042| callback | AsyncCallback\<void\> | 是 | 回调函数。 | 1043 1044**错误码:** 1045 1046| 错误码ID | 错误信息 | 1047| ------- | ----------------------- | 1048| 401 | Parameter error. | 1049| 201 | Permission denied. | 1050 1051**示例:** 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 1084通过TCPSocket连接发送数据。使用Promise方式作为异步方法。 1085 1086> **说明:** 1087> connect方法调用成功后,才可调用此方法。 1088 1089**需要权限**:ohos.permission.INTERNET 1090 1091**系统能力**:SystemCapability.Communication.NetStack 1092 1093**参数:** 1094 1095| 参数名 | 类型 | 必填 | 说明 | 1096| ------- | --------------------------------------- | ---- | ------------------------------------------------------------ | 1097| options | [TCPSendOptions](#tcpsendoptions) | 是 | TCPSocket发送请求的参数,参考[TCPSendOptions](#tcpsendoptions)。 | 1098 1099**返回值:** 1100 1101| 类型 | 说明 | 1102| :-------------- | :------------------------------------------------- | 1103| Promise\<void\> | 以Promise形式返回通过TCPSocket连接发送数据的结果。 | 1104 1105**错误码:** 1106 1107| 错误码ID | 错误信息 | 1108| ------- | ----------------------- | 1109| 401 | Parameter error. | 1110| 201 | Permission denied. | 1111 1112**示例:** 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 1143关闭TCPSocket连接。使用callback方式作为异步方法。 1144 1145**需要权限**:ohos.permission.INTERNET 1146 1147**系统能力**:SystemCapability.Communication.NetStack 1148 1149**参数:** 1150 1151| 参数名 | 类型 | 必填 | 说明 | 1152| -------- | --------------------- | ---- | ---------- | 1153| callback | AsyncCallback\<void\> | 是 | 回调函数。 | 1154 1155**错误码:** 1156 1157| 错误码ID | 错误信息 | 1158| ------- | ----------------------- | 1159| 201 | Permission denied. | 1160 1161**示例:** 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 1181关闭TCPSocket连接。使用Promise方式作为异步方法。 1182 1183**需要权限**:ohos.permission.INTERNET 1184 1185**系统能力**:SystemCapability.Communication.NetStack 1186 1187**返回值:** 1188 1189| 类型 | 说明 | 1190| :-------------- | :----------------------------------------- | 1191| Promise\<void\> | 以Promise形式返回关闭TCPSocket连接的结果。 | 1192 1193**错误码:** 1194 1195| 错误码ID | 错误信息 | 1196| ------- | ----------------------- | 1197| 201 | Permission denied. | 1198 1199**示例:** 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 1216获取对端Socket地址。使用callback方式作为异步方法。 1217 1218> **说明:** 1219> connect方法调用成功后,才可调用此方法。 1220 1221**需要权限**:ohos.permission.INTERNET 1222 1223**系统能力**:SystemCapability.Communication.NetStack 1224 1225**参数:** 1226 1227| 参数名 | 类型 | 必填 | 说明 | 1228| -------- | ------------------------------------------------- | ---- | ---------- | 1229| callback | AsyncCallback<[NetAddress](#netaddress)> | 是 | 回调函数。 | 1230 1231**错误码:** 1232 1233| 错误码ID | 错误信息 | 1234| ------- | ----------------------- | 1235| 201 | Permission denied. | 1236 1237**示例:** 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 1267获取对端Socket地址。使用Promise方式作为异步方法。 1268 1269> **说明:** 1270> connect方法调用成功后,才可调用此方法。 1271 1272**需要权限**:ohos.permission.INTERNET 1273 1274**系统能力**:SystemCapability.Communication.NetStack 1275 1276**返回值:** 1277 1278| 类型 | 说明 | 1279| :------------------------------------------ | :------------------------------------------ | 1280| Promise<[NetAddress](#netaddress)> | 以Promise形式返回获取对端socket地址的结果。 | 1281 1282**错误码:** 1283 1284| 错误码ID | 错误信息 | 1285| ------- | ----------------------- | 1286| 201 | Permission denied. | 1287 1288**示例:** 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 1318获取TCPSocket状态。使用callback方式作为异步方法。 1319 1320> **说明:** 1321> bind或connect方法调用成功后,才可调用此方法。 1322 1323**需要权限**:ohos.permission.INTERNET 1324 1325**系统能力**:SystemCapability.Communication.NetStack 1326 1327**参数:** 1328 1329| 参数名 | 类型 | 必填 | 说明 | 1330| -------- | ------------------------------------------------------ | ---- | ---------- | 1331| callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | 是 | 回调函数。 | 1332 1333**错误码:** 1334 1335| 错误码ID | 错误信息 | 1336| ------- | ----------------------- | 1337| 201 | Permission denied. | 1338 1339**示例:** 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 1369获取TCPSocket状态。使用Promise方式作为异步方法。 1370 1371> **说明:** 1372> bind或connect方法调用成功后,才可调用此方法。 1373 1374**需要权限**:ohos.permission.INTERNET 1375 1376**系统能力**:SystemCapability.Communication.NetStack 1377 1378**返回值:** 1379 1380| 类型 | 说明 | 1381| :----------------------------------------------- | :----------------------------------------- | 1382| Promise<[SocketStateBase](#socketstatebase)> | 以Promise形式返回获取TCPSocket状态的结果。 | 1383 1384**错误码:** 1385 1386| 错误码ID | 错误信息 | 1387| ------- | ----------------------- | 1388| 201 | Permission denied. | 1389 1390**示例:** 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 1420获取TCPSocket的文件描述符。使用callback方式作为异步方法。 1421 1422> **说明:** 1423> bind或connect方法调用成功后,才可调用此方法。 1424 1425**系统能力**:SystemCapability.Communication.NetStack 1426 1427**参数:** 1428 1429| 参数名 | 类型 | 必填 | 说明 | 1430| -------- | ------------------------------------------------------ | ---- | ---------- | 1431| callback | AsyncCallback\<number\> | 是 | 回调函数,当成功时,返回socket的文件描述符,失败时,返回undefined。 | 1432 1433**示例:** 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 1460获取TCPSocket的文件描述符。使用Promise方式作为异步方法。 1461 1462> **说明:** 1463> bind或connect方法调用成功后,才可调用此方法。 1464 1465**系统能力**:SystemCapability.Communication.NetStack 1466 1467**返回值:** 1468 1469| 类型 | 说明 | 1470| :----------------------------------------------- | :----------------------------------------- | 1471| Promise\<number\> | 以Promise形式返回socket的文件描述符。 | 1472 1473**示例:** 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 1500设置TCPSocket连接的其他属性。使用callback方式作为异步方法。 1501 1502> **说明:** 1503> bind或connect方法调用成功后,才可调用此方法。 1504 1505**需要权限**:ohos.permission.INTERNET 1506 1507**系统能力**:SystemCapability.Communication.NetStack 1508 1509**参数:** 1510 1511| 参数名 | 类型 | 必填 | 说明 | 1512| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | 1513| options | [TCPExtraOptions](#tcpextraoptions) | 是 | TCPSocket连接的其他属性,参考[TCPExtraOptions](#tcpextraoptions)。 | 1514| callback | AsyncCallback\<void\> | 是 | 回调函数。 | 1515 1516**错误码:** 1517 1518| 错误码ID | 错误信息 | 1519| ------- | ----------------------- | 1520| 401 | Parameter error. | 1521| 201 | Permission denied. | 1522 1523**示例:** 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 1562设置TCPSocket连接的其他属性,使用Promise方式作为异步方法。 1563 1564> **说明:** 1565> bind或connect方法调用成功后,才可调用此方法。 1566 1567**需要权限**:ohos.permission.INTERNET 1568 1569**系统能力**:SystemCapability.Communication.NetStack 1570 1571**参数:** 1572 1573| 参数名 | 类型 | 必填 | 说明 | 1574| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | 1575| options | [TCPExtraOptions](#tcpextraoptions) | 是 | TCPSocket连接的其他属性,参考[TCPExtraOptions](#tcpextraoptions)。 | 1576 1577**返回值:** 1578 1579| 类型 | 说明 | 1580| :-------------- | :--------------------------------------------------- | 1581| Promise\<void\> | 以Promise形式返回设置TCPSocket连接的其他属性的结果。 | 1582 1583**错误码:** 1584 1585| 错误码ID | 错误信息 | 1586| ------- | ----------------------- | 1587| 401 | Parameter error. | 1588| 201 | Permission denied. | 1589 1590**示例:** 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 1627订阅TCPSocket连接的接收消息事件。使用callback方式作为异步方法。 1628 1629**系统能力**:SystemCapability.Communication.NetStack 1630 1631**参数:** 1632 1633| 参数名 | 类型 | 必填 | 说明 | 1634| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 1635| type | string | 是 | 订阅的事件类型。'message':接收消息事件。 | 1636| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | 是 | 回调函数。 | 1637 1638**示例:** 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 1664取消订阅TCPSocket连接的接收消息事件。使用callback方式作为异步方法。 1665 1666> **说明:** 1667> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 1668 1669**系统能力**:SystemCapability.Communication.NetStack 1670 1671**参数:** 1672 1673| 参数名 | 类型 | 必填 | 说明 | 1674| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 1675| type | string | 是 | 订阅的事件类型。'message':接收消息事件。 | 1676| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | 否 | 回调函数。 | 1677 1678**示例:** 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// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 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 1708订阅TCPSocket的连接事件或关闭事件。使用callback方式作为异步方法。 1709 1710**系统能力**:SystemCapability.Communication.NetStack 1711 1712**参数:** 1713 1714| 参数名 | 类型 | 必填 | 说明 | 1715| -------- | ---------------- | ---- | ------------------------------------------------------------ | 1716| type | string | 是 | 订阅的事件类型。<br />- 'connect':连接事件。<br />- 'close':关闭事件。 | 1717| callback | Callback\<void\> | 是 | 回调函数。 | 1718 1719**示例:** 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 1737取消订阅TCPSocket的连接事件或关闭事件。使用callback方式作为异步方法。 1738 1739> **说明:** 1740> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 1741 1742**系统能力**:SystemCapability.Communication.NetStack 1743 1744**参数:** 1745 1746| 参数名 | 类型 | 必填 | 说明 | 1747| -------- | ---------------- | ---- | ------------------------------------------------------------ | 1748| type | string | 是 | 订阅的事件类型。<br />- 'connect':连接事件。<br />- 'close':关闭事件。 | 1749| callback | Callback\<void\> | 否 | 回调函数。 | 1750 1751**示例:** 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// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 1762tcp.off('connect', callback1); 1763tcp.off('connect'); 1764let callback2 = () => { 1765 console.log("on close success"); 1766} 1767tcp.on('close', callback2); 1768// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 1769tcp.off('close', callback2); 1770tcp.off('close'); 1771``` 1772 1773### on('error')<sup>7+</sup> 1774 1775on(type: 'error', callback: ErrorCallback): void 1776 1777订阅TCPSocket连接的error事件。使用callback方式作为异步方法。 1778 1779**系统能力**:SystemCapability.Communication.NetStack 1780 1781**参数:** 1782 1783| 参数名 | 类型 | 必填 | 说明 | 1784| -------- | ------------- | ---- | ------------------------------------ | 1785| type | string | 是 | 订阅的事件类型。'error':error事件。 | 1786| callback | ErrorCallback | 是 | 回调函数。 | 1787 1788**示例:** 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 1803取消订阅TCPSocket连接的error事件。使用callback方式作为异步方法。 1804 1805> **说明:** 1806> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 1807 1808**系统能力**:SystemCapability.Communication.NetStack 1809 1810**参数:** 1811 1812| 参数名 | 类型 | 必填 | 说明 | 1813| -------- | ------------- | ---- | ------------------------------------ | 1814| type | string | 是 | 订阅的事件类型。'error':error事件。 | 1815| callback | ErrorCallback | 否 | 回调函数。 | 1816 1817**示例:** 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// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 1828tcp.off('error', callback); 1829tcp.off('error'); 1830``` 1831 1832## TCPConnectOptions<sup>7+</sup> 1833 1834TCPSocket连接的参数。 1835 1836**系统能力**:SystemCapability.Communication.NetStack 1837 1838| 名称 | 类型 | 必填 | 说明 | 1839| ------- | ---------------------------------- | ---- | -------------------------- | 1840| address | [NetAddress](#netaddress) | 是 | 绑定的地址以及端口。 | 1841| timeout | number | 否 | 超时时间,单位毫秒(ms)。 | 1842 1843## TCPSendOptions<sup>7+</sup> 1844 1845TCPSocket发送请求的参数。 1846 1847**系统能力**:SystemCapability.Communication.NetStack 1848 1849| 名称 | 类型 | 必填 | 说明 | 1850| -------- | ------ | ---- | ------------------------------------------------------------ | 1851| data | string\| ArrayBuffer<sup>7+</sup> | 是 | 发送的数据。 | 1852| encoding | string | 否 | 字符编码(UTF-8,UTF-16BE,UTF-16LE,UTF-16,US-AECII,ISO-8859-1),默认为UTF-8。 | 1853 1854## TCPExtraOptions<sup>7+</sup> 1855 1856TCPSocket连接的其他属性。 1857 1858**系统能力**:SystemCapability.Communication.NetStack 1859 1860| 名称 | 类型 | 必填 | 说明 | 1861| ----------------- | ------- | ---- | ------------------------------------------------------------ | 1862| keepAlive | boolean | 否 | 是否保持连接。默认为false。 | 1863| OOBInline | boolean | 否 | 是否为OOB内联。默认为false。 | 1864| TCPNoDelay | boolean | 否 | TCPSocket连接是否无时延。默认为false。 | 1865| socketLinger | Object | 是 | socket是否继续逗留。<br />- on:是否逗留(true:逗留;false:不逗留)。<br />- linger:逗留时长,单位毫秒(ms),取值范围为0~65535。<br />当入参on设置为true时,才需要设置。 | 1866| receiveBufferSize | number | 否 | 接收缓冲区大小(单位:Byte),默认为0。 | 1867| sendBufferSize | number | 否 | 发送缓冲区大小(单位:Byte),默认为0。 | 1868| reuseAddress | boolean | 否 | 是否重用地址。默认为false。 | 1869| socketTimeout | number | 否 | 套接字超时时间,单位毫秒(ms),默认为0。 | 1870 1871## socket.constructTCPSocketServerInstance<sup>10+</sup> 1872 1873constructTCPSocketServerInstance(): TCPSocketServer 1874 1875创建一个TCPSocketServer对象。 1876 1877**系统能力**:SystemCapability.Communication.NetStack 1878 1879**返回值:** 1880 1881| 类型 | 说明 | 1882| :---------------------------------- | :---------------------------- | 1883| [TCPSocketServer](#tcpsocketserver10) | 返回一个TCPSocketServer对象。 | 1884 1885**示例:** 1886 1887```js 1888import socket from "@ohos.net.socket"; 1889let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 1890``` 1891 1892## TCPSocketServer<sup>10+</sup> 1893 1894TCPSocketServer连接。在调用TCPSocketServer的方法前,需要先通过[socket.constructTCPSocketServerInstance](#socketconstructtcpsocketserverinstance10)创建TCPSocketServer对象。 1895 1896### listen<sup>10+</sup> 1897 1898listen(address: NetAddress, callback: AsyncCallback\<void\>): void 1899 1900绑定IP地址和端口,端口可以指定或由系统随机分配。监听并接受与此套接字建立的TCPSocket连接。该接口使用多线程并发处理客户端的数据。使用callback方法作为异步方法。 1901 1902> **说明:** 1903> 服务端使用该方法完成bind,listen,accept操作,bind方法失败会由系统随机分配端口号。 1904 1905**需要权限**:ohos.permission.INTERNET 1906 1907**系统能力**:SystemCapability.Communication.NetStack 1908 1909**参数:** 1910 1911| 参数名 | 类型 | 必填 | 说明 | 1912| -------- | ------------------------- | ---- | --------------------------------------------- | 1913| address | [NetAddress](#netaddress7) | 是 | 目标地址信息。 | 1914| callback | AsyncCallback\<void\> | 是 | 回调函数。 | 1915 1916**错误码:** 1917 1918| 错误码ID | 错误信息 | 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**示例:** 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 1952绑定IP地址和端口,端口可以指定或由系统随机分配。监听并接受与此套接字建立的TCPSocket连接。该接口使用多线程并发处理客户端的数据。使用Promise方法作为异步方法。 1953 1954> **说明:** 1955> 服务端使用该方法完成bind,listen,accept操作,bind方法失败会由系统随机分配端口号。 1956 1957**需要权限**:ohos.permission.INTERNET 1958 1959**系统能力**:SystemCapability.Communication.NetStack 1960 1961**参数:** 1962 1963| 参数名 | 类型 | 必填 | 说明 | 1964| ------- | ------------------------- | ---- | --------------------------------------------- | 1965| address | [NetAddress](#netaddress7) | 是 | 目标地址信息。 | 1966 1967**返回值:** 1968 1969| 类型 | 说明 | 1970| :-------------- | :----------------------------------------------------------- | 1971| Promise\<void\> | 以Promise形式返回, 成功返回空,失败返回错误码错误信息。| 1972 1973**错误码:** 1974 1975| 错误码ID | 错误信息 | 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**示例:** 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 2007获取TCPSocketServer状态。使用callback方式作为异步方法。 2008 2009> **说明:** 2010> listen方法调用成功后,才可调用此方法。 2011 2012**需要权限**:ohos.permission.INTERNET 2013 2014**系统能力**:SystemCapability.Communication.NetStack 2015 2016**参数:** 2017 2018| 参数名 | 类型 | 必填 | 说明 | 2019| -------- | -------------------------------------------------- | ---- | ---------- | 2020| callback | AsyncCallback<[SocketStateBase](#socketstatebase7)> | 是 | 回调函数。 | 2021 2022**错误码:** 2023 2024| 错误码ID | 错误信息 | 2025| -------- | ------------------------------- | 2026| 401 | Parameter error. | 2027| 201 | Permission denied. | 2028| 2300002 | System internal error. | 2029| 2303188 | Socket operation on non-socket. | 2030 2031**示例:** 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 2062获取TCPSocketServer状态。使用Promise方式作为异步方法。 2063 2064> **说明:** 2065> listen方法调用成功后,才可调用此方法。 2066 2067**需要权限**:ohos.permission.INTERNET 2068 2069**系统能力**:SystemCapability.Communication.NetStack 2070 2071**返回值:** 2072 2073| 类型 | 说明 | 2074| :------------------------------------------- | :----------------------------------------- | 2075| Promise<[SocketStateBase](#socketstatebase7)> | 以Promise形式返回获取TCPSocket状态的结果。 | 2076 2077**错误码:** 2078 2079| 错误码ID | 错误信息 | 2080| -------- | ------------------------------- | 2081| 201 | Permission denied. | 2082| 2300002 | System internal error. | 2083| 2303188 | Socket operation on non-socket. | 2084 2085**示例:** 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 2114设置TCPSocketServer连接的其他属性。使用callback方式作为异步方法。 2115 2116> **说明:** 2117> listen方法调用成功后,才可调用此方法。 2118 2119**需要权限**:ohos.permission.INTERNET 2120 2121**系统能力**:SystemCapability.Communication.NetStack 2122 2123**参数:** 2124 2125| 参数名 | 类型 | 必填 | 说明 | 2126| -------- | ----------------------------------- | ---- | ------------------------------------------------------------ | 2127| options | [TCPExtraOptions](#tcpextraoptions7) | 是 | TCPSocketServer连接的其他属性。 | 2128| callback | AsyncCallback\<void\> | 是 | 回调函数。 | 2129 2130**错误码:** 2131 2132| 错误码ID | 错误信息 | 2133| -------- | ------------------------------- | 2134| 401 | Parameter error. | 2135| 201 | Permission denied. | 2136| 2300002 | System internal error. | 2137| 2303188 | Socket operation on non-socket. | 2138 2139**示例:** 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 2181设置TCPSocketServer连接的其他属性,使用Promise方式作为异步方法。 2182 2183> **说明:** 2184> listen方法调用成功后,才可调用此方法。 2185 2186**需要权限**:ohos.permission.INTERNET 2187 2188**系统能力**:SystemCapability.Communication.NetStack 2189 2190**参数:** 2191 2192| 参数名 | 类型 | 必填 | 说明 | 2193| ------- | ----------------------------------- | ---- | ------------------------------------------------------------ | 2194| options | [TCPExtraOptions](#tcpextraoptions7) | 是 | TCPSocketServer连接的其他属性。 | 2195 2196**返回值:** 2197 2198| 类型 | 说明 | 2199| :-------------- | :--------------------------------------------------------- | 2200| Promise\<void\> | 以Promise形式返回,成功返回空,失败返回错误码错误信息。 | 2201 2202**错误码:** 2203 2204| 错误码ID | 错误信息 | 2205| -------- | ------------------------------- | 2206| 401 | Parameter error. | 2207| 201 | Permission denied. | 2208| 2300002 | System internal error. | 2209| 2303188 | Socket operation on non-socket. | 2210 2211**示例:** 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 2251订阅TCPSocketServer的连接事件。使用callback方式作为异步方法。 2252 2253> **说明:** 2254> listen方法调用成功后,才可调用此方法。 2255 2256**系统能力**:SystemCapability.Communication.NetStack 2257 2258**参数:** 2259 2260| 参数名 | 类型 | 必填 | 说明 | 2261| -------- | ------------------------------- | ---- | ------------------------------------- | 2262| type | string | 是 | 订阅的事件类型。'connect':连接事件。 | 2263| callback | Callback<[TCPSocketConnection](#tcpsocketconnection10)> | 是 | 回调函数。 | 2264 2265**错误码:** 2266 2267| 错误码ID | 错误信息 | 2268| -------- | ---------------- | 2269| 401 | Parameter error. | 2270 2271**示例:** 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 2285取消订阅TCPSocketServer的连接事件。使用callback方式作为异步方法。 2286 2287> **说明:** 2288> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 2289 2290**系统能力**:SystemCapability.Communication.NetStack 2291 2292**参数:** 2293 2294| 参数名 | 类型 | 必填 | 说明 | 2295| -------- | ------------------------------- | ---- | ------------------------------------- | 2296| type | string | 是 | 订阅的事件类型。'connect':连接事件。 | 2297| callback | Callback<[TCPSocketConnection](#tcpsocketconnection10)> | 否 | 回调函数。 | 2298 2299**错误码:** 2300 2301| 错误码ID | 错误信息 | 2302| -------- | ---------------- | 2303| 401 | Parameter error. | 2304 2305**示例:** 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// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 2315tcpServer.off('connect', callback); 2316tcpServer.off('connect'); 2317``` 2318 2319### on('error')<sup>10+</sup> 2320 2321on(type: 'error', callback: ErrorCallback): void 2322 2323订阅TCPSocketServer连接的error事件。使用callback方式作为异步方法。 2324 2325> **说明:** 2326> listen方法调用成功后,才可调用此方法。 2327 2328**系统能力**:SystemCapability.Communication.NetStack 2329 2330**参数:** 2331 2332| 参数名 | 类型 | 必填 | 说明 | 2333| -------- | ------------- | ---- | ------------------------------------ | 2334| type | string | 是 | 订阅的事件类型。'error':error事件。 | 2335| callback | ErrorCallback | 是 | 回调函数。 | 2336 2337**错误码:** 2338 2339| 错误码ID | 错误信息 | 2340| -------- | ---------------- | 2341| 401 | Parameter error. | 2342 2343**示例:** 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 2358取消订阅TCPSocketServer连接的error事件。使用callback方式作为异步方法。 2359 2360> **说明:** 2361> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 2362 2363**系统能力**:SystemCapability.Communication.NetStack 2364 2365**参数:** 2366 2367| 参数名 | 类型 | 必填 | 说明 | 2368| -------- | ------------- | ---- | ------------------------------------ | 2369| type | string | 是 | 订阅的事件类型。'error':error事件。 | 2370| callback | ErrorCallback | 否 | 回调函数。 | 2371 2372**错误码:** 2373 2374| 错误码ID | 错误信息 | 2375| -------- | ---------------- | 2376| 401 | Parameter error. | 2377 2378**示例:** 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// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 2389tcpServer.off('error', callback); 2390tcpServer.off('error'); 2391``` 2392 2393## TCPSocketConnection<sup>10+</sup> 2394 2395TCPSocketConnection连接,即TCPSocket客户端与服务端的连接。在调用TCPSocketConnection的方法前,需要先获取TCPSocketConnection对象。 2396 2397> **说明:** 2398> 客户端与服务端成功建立连接后,才能通过返回的TCPSocketConnection对象调用相应的接口。 2399 2400**系统能力**:SystemCapability.Communication.NetStack 2401 2402### 属性 2403 2404| 名称 | 类型 | 必填 | 说明 | 2405| -------- | ------ | ---- | ----------------------------------------- | 2406| clientId | number | 是 | 客户端与TCPSocketServer建立连接的id。 | 2407 2408### send<sup>10+</sup> 2409 2410send(options: TCPSendOptions, callback: AsyncCallback\<void\>): void 2411 2412通过TCPSocketConnection连接发送数据。使用callback方式作为异步方法。 2413 2414> **说明:** 2415> 与客户端建立连接后,才可调用此方法。 2416 2417**需要权限**:ohos.permission.INTERNET 2418 2419**系统能力**:SystemCapability.Communication.NetStack 2420 2421**参数:** 2422 2423| 参数名 | 类型 | 必填 | 说明 | 2424| -------- | --------------------------------- | ---- | ------------------------------------------------------------ | 2425| options | [TCPSendOptions](#tcpsendoptions7) | 是 | TCPSocketConnection发送请求的参数。 | 2426| callback | AsyncCallback\<void\> | 是 | 回调函数。 | 2427 2428**错误码:** 2429 2430| 错误码ID | 错误信息 | 2431| -------- | ---------------------- | 2432| 401 | Parameter error. | 2433| 201 | Permission denied. | 2434| 2300002 | System internal error. | 2435 2436**示例:** 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 2456通过TCPSocketConnection连接发送数据。使用Promise方式作为异步方法。 2457 2458> **说明:** 2459> 与客户端建立连接后,才可调用此方法。 2460 2461**需要权限**:ohos.permission.INTERNET 2462 2463**系统能力**:SystemCapability.Communication.NetStack 2464 2465**参数:** 2466 2467| 参数名 | 类型 | 必填 | 说明 | 2468| ------- | --------------------------------- | ---- | ------------------------------------------------------------ | 2469| options | [TCPSendOptions](#tcpsendoptions7) | 是 | TCPSocketConnection发送请求的参数。 | 2470 2471**返回值:** 2472 2473| 类型 | 说明 | 2474| :-------------- | :----------------------------------------------------------- | 2475| Promise\<void\> | 以Promise形式返回,成功返回空,失败返回错误码错误信息。 | 2476 2477**错误码:** 2478 2479| 错误码ID | 错误信息 | 2480| -------- | ---------------------- | 2481| 401 | Parameter error. | 2482| 201 | Permission denied. | 2483| 2300002 | System internal error. | 2484 2485**示例:** 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 2508关闭一个与TCPSocket建立的连接。使用callback方式作为异步方法。 2509 2510**需要权限**:ohos.permission.INTERNET 2511 2512**系统能力**:SystemCapability.Communication.NetStack 2513 2514**参数:** 2515 2516| 参数名 | 类型 | 必填 | 说明 | 2517| -------- | --------------------- | ---- | ---------- | 2518| callback | AsyncCallback\<void\> | 是 | 回调函数。 | 2519 2520**错误码:** 2521 2522| 错误码ID | 错误信息 | 2523| -------- | ---------------------- | 2524| 401 | Parameter error. | 2525| 201 | Permission denied. | 2526| 2300002 | System internal error. | 2527 2528**示例:** 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 2550关闭一个与TCPSocket建立的连接。使用Promise方式作为异步方法。 2551 2552**需要权限**:ohos.permission.INTERNET 2553 2554**系统能力**:SystemCapability.Communication.NetStack 2555 2556**返回值:** 2557 2558| 类型 | 说明 | 2559| :-------------- | :------------------------------------------- | 2560| Promise\<void\> | 以Promise形式返回,成功返回空,失败返回错误码错误信息。 | 2561 2562**错误码:** 2563 2564| 错误码ID | 错误信息 | 2565| -------- | ---------------------- | 2566| 201 | Permission denied. | 2567| 2300002 | System internal error. | 2568 2569**示例:** 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 2587获取对端Socket地址。使用callback方式作为异步方法。 2588 2589> **说明:** 2590> 与客户端建立连接后,才可调用此方法。 2591 2592**需要权限**:ohos.permission.INTERNET 2593 2594**系统能力**:SystemCapability.Communication.NetStack 2595 2596**参数:** 2597 2598| 参数名 | 类型 | 必填 | 说明 | 2599| -------- | ---------------------------------------- | ---- | ---------- | 2600| callback | AsyncCallback<[NetAddress](#netaddress7)> | 是 | 回调函数。 | 2601 2602**错误码:** 2603 2604| 错误码ID | 错误信息 | 2605| -------- | ------------------------------- | 2606| 401 | Parameter error. | 2607| 201 | Permission denied. | 2608| 2300002 | System internal error. | 2609| 2303188 | Socket operation on non-socket. | 2610 2611**示例:** 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 2632获取对端Socket地址。使用Promise方式作为异步方法。 2633 2634> **说明:** 2635> 与客户端建立连接后,才可调用此方法。 2636 2637**需要权限**:ohos.permission.INTERNET 2638 2639**系统能力**:SystemCapability.Communication.NetStack 2640 2641**返回值:** 2642 2643| 类型 | 说明 | 2644| :--------------------------------- | :------------------------------------------ | 2645| Promise<[NetAddress](#netaddress7)> | 以Promise形式返回获取对端socket地址的结果。 | 2646 2647**错误码:** 2648 2649| 错误码ID | 错误信息 | 2650| -------- | ------------------------------- | 2651| 201 | Permission denied. | 2652| 2300002 | System internal error. | 2653| 2303188 | Socket operation on non-socket. | 2654 2655**示例:** 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 2674订阅TCPSocketConnection连接的接收消息事件。使用callback方式作为异步方法。 2675 2676**系统能力**:SystemCapability.Communication.NetStack 2677 2678**参数:** 2679 2680| 参数名 | 类型 | 必填 | 说明 | 2681| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 2682| type | string | 是 | 订阅的事件类型。'message':接收消息事件。 | 2683| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo7)}> | 是 | 回调函数。message:接收到的消息;remoteInfo:socket连接信息。 | 2684 2685**错误码:** 2686 2687| 错误码ID | 错误信息 | 2688| -------- | ---------------- | 2689| 401 | Parameter error. | 2690 2691**示例:** 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 2720取消订阅TCPSocketConnection连接的接收消息事件。使用callback方式作为异步方法。 2721 2722> **说明:** 2723> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 2724 2725**系统能力**:SystemCapability.Communication.NetStack 2726 2727**参数:** 2728 2729| 参数名 | 类型 | 必填 | 说明 | 2730| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 2731| type | string | 是 | 订阅的事件类型。'message':接收消息事件。 | 2732| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo7)}> | 否 | 回调函数。message:接收到的消息;remoteInfo:socket连接信息。 | 2733 2734**错误码:** 2735 2736| 错误码ID | 错误信息 | 2737| -------- | ---------------- | 2738| 401 | Parameter error. | 2739 2740**示例:** 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 // 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 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 2772订阅TCPSocketConnection的关闭事件。使用callback方式作为异步方法。 2773 2774**系统能力**:SystemCapability.Communication.NetStack 2775 2776**参数:** 2777 2778| 参数名 | 类型 | 必填 | 说明 | 2779| -------- | ---------------- | ---- | ----------------------------------- | 2780| type | string | 是 | 订阅的事件类型。'close':关闭事件。 | 2781| callback | Callback\<void\> | 是 | 回调函数。 | 2782 2783**错误码:** 2784 2785| 错误码ID | 错误信息 | 2786| -------- | ---------------- | 2787| 401 | Parameter error. | 2788 2789**示例:** 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 2806取消订阅TCPSocketConnection的关闭事件。使用callback方式作为异步方法。 2807 2808> **说明:** 2809> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 2810 2811**系统能力**:SystemCapability.Communication.NetStack 2812 2813**参数:** 2814 2815| 参数名 | 类型 | 必填 | 说明 | 2816| -------- | ---------------- | ---- | ----------------------------------- | 2817| type | string | 是 | 订阅的事件类型。'close':关闭事件。 | 2818| callback | Callback\<void\> | 否 | 回调函数。 | 2819 2820**错误码:** 2821 2822| 错误码ID | 错误信息 | 2823| -------- | ---------------- | 2824| 401 | Parameter error. | 2825 2826**示例:** 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 // 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 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 2846订阅TCPSocketConnection连接的error事件。使用callback方式作为异步方法。 2847 2848**系统能力**:SystemCapability.Communication.NetStack 2849 2850**参数:** 2851 2852| 参数名 | 类型 | 必填 | 说明 | 2853| -------- | ------------- | ---- | ------------------------------------ | 2854| type | string | 是 | 订阅的事件类型。'error':error事件。 | 2855| callback | ErrorCallback | 是 | 回调函数。 | 2856 2857**错误码:** 2858 2859| 错误码ID | 错误信息 | 2860| -------- | ---------------- | 2861| 401 | Parameter error. | 2862 2863**示例:** 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 2880取消订阅TCPSocketConnection连接的error事件。使用callback方式作为异步方法。 2881 2882> **说明:** 2883> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 2884 2885**系统能力**:SystemCapability.Communication.NetStack 2886 2887**参数:** 2888 2889| 参数名 | 类型 | 必填 | 说明 | 2890| -------- | ------------- | ---- | ------------------------------------ | 2891| type | string | 是 | 订阅的事件类型。'error':error事件。 | 2892| callback | ErrorCallback | 否 | 回调函数。 | 2893 2894**错误码:** 2895 2896| 错误码ID | 错误信息 | 2897| -------- | ---------------- | 2898| 401 | Parameter error. | 2899 2900**示例:** 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 // 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 2912 client.off('error', callback); 2913 client.off('error'); 2914}); 2915``` 2916 2917## TCP 错误码说明 2918 2919TCP 其余错误码映射形式为:2301000 + Linux内核错误码。 2920 2921错误码的详细介绍参见[Socket错误码](../errorcodes/errorcode-net-socket.md) 2922 2923## socket.constructTLSSocketInstance<sup>9+</sup> 2924 2925constructTLSSocketInstance(): TLSSocket 2926 2927创建并返回一个TLSSocket对象。 2928 2929**系统能力**:SystemCapability.Communication.NetStack 2930 2931**返回值:** 2932 2933| 类型 | 说明 | 2934| :--------------------------------- | :---------------------- | 2935| [TLSSocket](#tlssocket9) | 返回一个TLSSocket对象。 | 2936 2937**示例:** 2938 2939```js 2940import socket from "@ohos.net.socket"; 2941let tls: socket.TLSSocket = socket.constructTLSSocketInstance(); 2942``` 2943 2944## TLSSocket<sup>9+</sup> 2945 2946TLSSocket连接。在调用TLSSocket的方法前,需要先通过[socket.constructTLSSocketInstance](#socketconstructtlssocketinstance9)创建TLSSocket对象。 2947 2948### bind<sup>9+</sup> 2949 2950bind(address: NetAddress, callback: AsyncCallback\<void\>): void 2951 2952绑定IP地址和端口。使用callback方法作为异步方法。 2953 2954**需要权限**:ohos.permission.INTERNET 2955 2956**系统能力**:SystemCapability.Communication.NetStack 2957 2958**参数:** 2959 2960| 参数名 | 类型 | 必填 | 说明 | 2961| -------- | ---------------------------------- | ---- | ------------------------------------------------------ | 2962| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 | 2963| callback | AsyncCallback\<void\> | 是 | 回调函数。成功返回TLSSocket绑定本机的IP地址和端口的结果。 失败返回错误码,错误信息。| 2964 2965**错误码:** 2966 2967| 错误码ID | 错误信息 | 2968| ------- | ----------------------- | 2969| 401 | Parameter error. | 2970| 201 | Permission denied. | 2971| 2303198 | Address already in use. | 2972| 2300002 | System internal error. | 2973 2974**示例:** 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 2997绑定IP地址和端口。使用Promise方法作为异步方法。 2998 2999**需要权限**:ohos.permission.INTERNET 3000 3001**系统能力**:SystemCapability.Communication.NetStack 3002 3003**参数:** 3004 3005| 参数名 | 类型 | 必填 | 说明 | 3006| ------- | ---------------------------------- | ---- | ------------------------------------------------------ | 3007| address | [NetAddress](#netaddress) | 是 | 目标地址信息,参考[NetAddress](#netaddress)。 | 3008 3009**返回值:** 3010 3011| 类型 | 说明 | 3012| :-------------- | :------------------------------------------------------- | 3013| Promise\<void\> | 以Promise形式返回TLSSocket绑定本机的IP地址和端口的结果。失败返回错误码,错误信息。 | 3014 3015**错误码:** 3016 3017| 错误码ID | 错误信息 | 3018| ------- | ----------------------- | 3019| 401 | Parameter error. | 3020| 201 | Permission denied. | 3021| 2303198 | Address already in use. | 3022| 2300002 | System internal error. | 3023 3024**示例:** 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 3045在TLSSocket的bind成功之后,获取TLSSocket状态。使用callback方式作为异步方法。 3046 3047**系统能力**:SystemCapability.Communication.NetStack 3048 3049**参数:** 3050 3051| 参数名 | 类型 | 必填 | 说明 | 3052| -------- | ------------------------------------------------------ | ---- | ---------- | 3053| callback | AsyncCallback\<[SocketStateBase](#socketstatebase)> | 是 | 回调函数。成功返回TLSSocket状态,失败返回错误码,错误信息。 | 3054 3055**错误码:** 3056 3057| 错误码ID | 错误信息 | 3058| ------- | ------------------------------ | 3059| 2303188 | Socket operation on non-socket.| 3060| 2300002 | System internal error. | 3061 3062**示例:** 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 3092在TLSSocket的bind成功之后,获取TLSSocket状态。使用Promise方式作为异步方法。 3093 3094**系统能力**:SystemCapability.Communication.NetStack 3095 3096**返回值:** 3097 3098| 类型 | 说明 | 3099| :----------------------------------------------- | :----------------------------------------- | 3100| Promise\<[SocketStateBase](#socketstatebase)> | 以Promise形式返回获取TLSSocket状态的结果。失败返回错误码,错误信息。| 3101 3102**错误码:** 3103 3104| 错误码ID | 错误信息 | 3105| ------- | ------------------------------ | 3106| 2303188 | Socket operation on non-socket.| 3107| 2300002 | System internal error. | 3108 3109**示例:** 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 3137在TLSSocket的bind成功之后,设置TCPSocket连接的其他属性。使用callback方式作为异步方法。 3138 3139**系统能力**:SystemCapability.Communication.NetStack 3140 3141**参数:** 3142 3143| 参数名 | 类型 | 必填 | 说明 | 3144| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | 3145| options | [TCPExtraOptions](#tcpextraoptions) | 是 | TCPSocket连接的其他属性,参考[TCPExtraOptions](#tcpextraoptions)。 | 3146| callback | AsyncCallback\<void\> | 是 | 回调函数。成功返回设置TCPSocket连接的其他属性的结果,失败返回错误码,错误信息。| 3147 3148**错误码:** 3149 3150| 错误码ID | 错误信息 | 3151| ------- | ----------------------------- | 3152| 401 | Parameter error. | 3153| 2303188 | Socket operation on non-socket.| 3154| 2300002 | System internal error. | 3155 3156**示例:** 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 3197在TLSSocket的bind成功之后,设置TCPSocket连接的其他属性,使用Promise方式作为异步方法。 3198 3199**系统能力**:SystemCapability.Communication.NetStack 3200 3201**参数:** 3202 3203| 参数名 | 类型 | 必填 | 说明 | 3204| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | 3205| options | [TCPExtraOptions](#tcpextraoptions) | 是 | TCPSocket连接的其他属性,参考[TCPExtraOptions](#tcpextraoptions)。 | 3206 3207**返回值:** 3208 3209| 类型 | 说明 | 3210| :-------------- | :--------------------------------------------------- | 3211| Promise\<void\> | 以Promise形式返回设置TCPSocket连接的其他属性的结果。失败返回错误码,错误信息。 | 3212 3213**错误码:** 3214 3215| 错误码ID | 错误信息 | 3216| ------- | ------------------------------ | 3217| 401 | Parameter error. | 3218| 2303188 | Socket operation on non-socket.| 3219| 2300002 | System internal error. | 3220 3221**示例:** 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 3260订阅TLSSocket连接的接收消息事件。使用callback方式作为异步方法。 3261 3262**系统能力**:SystemCapability.Communication.NetStack 3263 3264**参数:** 3265 3266| 参数名 | 类型 | 必填 | 说明 | 3267| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 3268| type | string | 是 | 订阅的事件类型。'message':接收消息事件。 | 3269| callback | Callback\<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}\> | 是 | 回调函数。message:接收到的消息;remoteInfo:socket连接信息。 | 3270 3271**示例:** 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 3297取消订阅TLSSocket连接的接收消息事件。使用callback方式作为异步方法。 3298 3299> **说明:** 3300> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 3301 3302**系统能力**:SystemCapability.Communication.NetStack 3303 3304**参数:** 3305 3306| 参数名 | 类型 | 必填 | 说明 | 3307| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 3308| type | string | 是 | 订阅的事件类型。'message':接收消息事件。 | 3309| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | 否 | 回调函数。message:接收到的消息;remoteInfo:socket连接信息。 | 3310 3311**示例:** 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// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 3333tls.off('message', callback); 3334``` 3335### on('connect' | 'close')<sup>9+</sup> 3336 3337on(type: 'connect' | 'close', callback: Callback\<void\>): void 3338 3339订阅TLSSocket的连接事件或关闭事件。使用callback方式作为异步方法。 3340 3341**系统能力**:SystemCapability.Communication.NetStack 3342 3343**参数:** 3344 3345| 参数名 | 类型 | 必填 | 说明 | 3346| -------- | ---------------- | ---- | ------------------------------------------------------------ | 3347| type | string | 是 | 订阅的事件类型。<br />- 'connect':连接事件。<br />- 'close':关闭事件。 | 3348| callback | Callback\<void\> | 是 | 回调函数。 | 3349 3350**示例:** 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 3368取消订阅TLSSocket的连接事件或关闭事件。使用callback方式作为异步方法。 3369 3370> **说明:** 3371> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 3372 3373**系统能力**:SystemCapability.Communication.NetStack 3374 3375**参数:** 3376 3377| 参数名 | 类型 | 必填 | 说明 | 3378| -------- | ---------------- | ---- | ------------------------------------------------------------ | 3379| type | string | 是 | 订阅的事件类型。<br />- 'connect':连接事件。<br />- 'close':关闭事件。 | 3380| callback | Callback\<void\> | 否 | 回调函数。 | 3381 3382**示例:** 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// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 3393tls.off('connect', callback1); 3394tls.off('connect'); 3395let callback2 = () => { 3396 console.log("on close success"); 3397} 3398tls.on('close', callback2); 3399// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 3400tls.off('close', callback2); 3401``` 3402 3403### on('error')<sup>9+</sup> 3404 3405on(type: 'error', callback: ErrorCallback): void 3406 3407订阅TLSSocket连接的error事件。使用callback方式作为异步方法。 3408 3409**系统能力**:SystemCapability.Communication.NetStack 3410 3411**参数:** 3412 3413| 参数名 | 类型 | 必填 | 说明 | 3414| -------- | ------------- | ---- | ------------------------------------ | 3415| type | string | 是 | 订阅的事件类型。'error':error事件。 | 3416| callback | ErrorCallback | 是 | 回调函数。 | 3417 3418**示例:** 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 3433取消订阅TLSSocket连接的error事件。使用callback方式作为异步方法。 3434 3435> **说明:** 3436> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 3437 3438**系统能力**:SystemCapability.Communication.NetStack 3439 3440**参数:** 3441 3442| 参数名 | 类型 | 必填 | 说明 | 3443| -------- | ------------- | ---- | ------------------------------------ | 3444| type | string | 是 | 订阅的事件类型。'error':error事件。 | 3445| callback | ErrorCallback | 否 | 回调函数。 | 3446 3447**示例:** 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// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 3458tls.off('error', callback); 3459``` 3460 3461### connect<sup>9+</sup> 3462 3463connect(options: TLSConnectOptions, callback: AsyncCallback\<void\>): void 3464 3465在TLSSocket上bind成功之后,进行通信连接,并创建和初始化TLS会话,实现建立连接过程,启动与服务器的TLS/SSL握手,实现数据传输功能,使用callback方式作为异步方法。 3466 3467**系统能力**:SystemCapability.Communication.NetStack 3468 3469**参数:** 3470 3471| 参数名 | 类型 | 必填 | 说明 | 3472| -------- | ---------------------------------------| ----| --------------- | 3473| options | [TLSConnectOptions](#tlsconnectoptions9) | 是 | TLSSocket连接所需要的参数。| 3474| callback | AsyncCallback\<void> | 是 | 回调函数,成功无返回,失败返回错误码,错误信息。| 3475 3476**错误码:** 3477 3478| 错误码ID | 错误信息 | 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**示例:** 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 3563在TLSSocket上bind成功之后,进行通信连接,并创建和初始化TLS会话,实现建立连接过程,启动与服务器的TLS/SSL握手,实现数据传输功能,该连接包括两种认证方式,单向认证与双向认证,使用Promise方式作为异步方法。 3564 3565**系统能力**:SystemCapability.Communication.NetStack 3566 3567**参数:** 3568 3569| 参数名 | 类型 | 必填 | 说明 | 3570| -------- | --------------------------------------| ----| --------------- | 3571| options | [TLSConnectOptions](#tlsconnectoptions9) | 是 | 连接所需要的参数。| 3572 3573**返回值:** 3574 3575| 类型 | 说明 | 3576| ------------------------------------------- | ----------------------------- | 3577| Promise\<void\> | 以Promise形式返回,成功无返回,失败返回错误码,错误信息。| 3578 3579**错误码:** 3580 3581| 错误码ID | 错误信息 | 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**示例:** 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 3670在TLSSocket通信连接成功之后,获取对端Socket地址。使用callback方式作为异步方法。 3671 3672**系统能力**:SystemCapability.Communication.NetStack 3673 3674**参数:** 3675 3676| 参数名 | 类型 | 必填 | 说明 | 3677| -------- | ------------------------------------------------- | ---- | ---------- | 3678| callback | AsyncCallback\<[NetAddress](#netaddress)\> | 是 | 回调函数。成功返回对端的socket地址,失败返回错误码,错误信息。 | 3679 3680**错误码:** 3681 3682| 错误码ID | 错误信息 | 3683| ------- | ----------------------------- | 3684| 2303188 | Socket operation on non-socket.| 3685| 2300002 | System internal error. | 3686 3687**示例:** 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 3706在TLSSocket通信连接成功之后,获取对端Socket地址。使用Promise方式作为异步方法。 3707 3708**系统能力**:SystemCapability.Communication.NetStack 3709 3710**返回值:** 3711 3712| 类型 | 说明 | 3713| :------------------------------------------ | :------------------------------------------ | 3714| Promise\<[NetAddress](#netaddress)> | 以Promise形式返回获取对端socket地址的结果。失败返回错误码,错误信息。 | 3715 3716**错误码:** 3717 3718| 错误码ID | 错误信息 | 3719| ------- | ------------------------------ | 3720| 2303188 | Socket operation on non-socket.| 3721| 2300002 | System internal error. | 3722 3723**示例:** 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 3740在TLSSocket通信连接成功之后,获取本地的数字证书,该接口只适用于双向认证时,使用callback方式作为异步方法。 3741 3742**系统能力**:SystemCapability.Communication.NetStack 3743 3744**参数:** 3745 3746| 参数名 | 类型 | 必填 | 说明 | 3747| -------- | ----------------------------------------| ---- | ---------------| 3748| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)\> | 是 | 回调函数,成功返回本地的证书,失败返回错误码,错误信息。| 3749 3750**错误码:** 3751 3752| 错误码ID | 错误信息 | 3753| ------- | ------------------------------ | 3754| 2303501 | SSL is null. | 3755| 2303504 | Error looking up x509. | 3756| 2300002 | System internal error. | 3757 3758**示例:** 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 3777在TLSSocket通信连接之后,获取本地的数字证书,该接口只适用于双向认证时,使用Promise方式作为异步方法。 3778 3779**系统能力**:SystemCapability.Communication.NetStack 3780 3781**返回值:** 3782 3783| 类型 | 说明 | 3784| -------------- | -------------------- | 3785| Promise\<[X509CertRawData](#x509certrawdata9)\> | 以Promise形式返回本地的数字证书的结果。失败返回错误码,错误信息。 | 3786 3787**错误码:** 3788 3789| 错误码ID | 错误信息 | 3790| ------- | ------------------------------ | 3791| 2303501 | SSL is null. | 3792| 2303504 | Error looking up x509. | 3793| 2300002 | System internal error. | 3794 3795**示例:** 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 3812在TLSSocket通信连接成功之后,获取服务端的数字证书,使用callback方式作为异步方法。 3813 3814**系统能力**:SystemCapability.Communication.NetStack 3815 3816**参数:** 3817 3818| 参数名 | 类型 | 必填 | 说明 | 3819| -------- | ----------------------------------------| ---- | ---------------| 3820| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)\> | 是 | 回调函数,返回服务端的证书。失败返回错误码,错误信息。 | 3821 3822**错误码:** 3823 3824| 错误码ID | 错误信息 | 3825| ------- | ------------------------------ | 3826| 2303501 | SSL is null. | 3827| 2300002 | System internal error. | 3828 3829**示例:** 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 3848在TLSSocket通信连接成功之后,获取服务端的数字证书,使用Promise方式作为异步方法。 3849 3850**系统能力**:SystemCapability.Communication.NetStack 3851 3852**返回值:** 3853 3854| 类型 | 说明 | 3855| -------------- | -------------------- | 3856| Promise\<[X509CertRawData](#x509certrawdata9)\> | 以Promise形式返回服务端的数字证书的结果。失败返回错误码,错误信息。 | 3857 3858**错误码:** 3859 3860| 错误码ID | 错误信息 | 3861| ------- | ------------------------------ | 3862| 2303501 | SSL is null. | 3863| 2300002 | System internal error. | 3864 3865**示例:** 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 3882在TLSSocket通信连接成功之后,获取通信的协议版本,使用callback方式作为异步方法。 3883 3884**系统能力**:SystemCapability.Communication.NetStack 3885 3886**参数:** 3887 3888| 参数名 | 类型 | 必填 | 说明 | 3889| -------- | ----------------------------------------| ---- | ---------------| 3890| callback | AsyncCallback\<string\> | 是 | 回调函数,返回通信的协议。失败返回错误码,错误信息。| 3891 3892**错误码:** 3893 3894| 错误码ID | 错误信息 | 3895| ------- | ----------------------------- | 3896| 2303501 | SSL is null. | 3897| 2303505 | Error occurred in the tls system call. | 3898| 2300002 | System internal error. | 3899 3900**示例:** 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 3919在TLSSocket通信连接成功之后,获取通信的协议版本,使用Promise方式作为异步方法。 3920 3921**系统能力**:SystemCapability.Communication.NetStack 3922 3923**返回值:** 3924 3925| 类型 | 说明 | 3926| -------------- | -------------------- | 3927| Promise\<string\> | 以Promise形式返回通信的协议。失败返回错误码,错误信息。 | 3928 3929**错误码:** 3930 3931| 错误码ID | 错误信息 | 3932| ------- | ------------------------------ | 3933| 2303501 | SSL is null. | 3934| 2303505 | Error occurred in the tls system call. | 3935| 2300002 | System internal error. | 3936 3937**示例:** 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 3954在TLSSocket通信连接成功之后,获取通信双方协商后的加密套件,使用callback方式作为异步方法。 3955 3956**系统能力**:SystemCapability.Communication.NetStack 3957 3958**参数:** 3959 3960| 参数名 | 类型 | 必填 | 说明 | 3961| -------- | ----------------------------------------| ---- | ---------------| 3962| callback | AsyncCallback\<Array\<string\>\> | 是 | 回调函数,返回通信双方支持的加密套件。 失败返回错误码,错误信息。 | 3963 3964**错误码:** 3965 3966| 错误码ID | 错误信息 | 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**示例:** 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 3992在TLSSocket通信连接成功之后,获取通信双方协商后的加密套件,使用Promise方式作为异步方法。 3993 3994**系统能力**:SystemCapability.Communication.NetStack 3995 3996**返回值:** 3997 3998| 类型 | 说明 | 3999| ---------------------- | --------------------- | 4000| Promise\<Array\<string\>\> | 以Promise形式返回通信双方支持的加密套件。失败返回错误码,错误信息。 | 4001 4002**错误码:** 4003 4004| 错误码ID | 错误信息 | 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**示例:** 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 4028在TLSSocket通信连接成功之后,获取通信双方协商后签名算法,该接口只适配双向认证模式下,使用callback方式作为异步方法。 4029 4030**系统能力**:SystemCapability.Communication.NetStack 4031 4032**参数:** 4033 4034| 参数名 | 类型 | 必填 | 说明 | 4035| -------- | -------------------------------------| ---- | ---------------| 4036| callback | AsyncCallback\<Array\<string\>\> | 是 | 回调函数,返回双方支持的签名算法。 | 4037 4038**错误码:** 4039 4040| 错误码ID | 错误信息 | 4041| ------- | ------------------------------ | 4042| 2303501 | SSL is null. | 4043| 2300002 | System internal error. | 4044 4045**示例:** 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 4064在TLSSocket通信连接成功之后,获取通信双方协商后的签名算法,该接口只适配双向认证模式下,使用Promise方式作为异步方法。 4065 4066**系统能力**:SystemCapability.Communication.NetStack 4067 4068**返回值:** 4069 4070| 类型 | 说明 | 4071| ---------------------- | -------------------- | 4072| Promise\<Array\<string\>\> | 以Promise形式返回获取到的双方支持的签名算法。 | 4073 4074**错误码:** 4075 4076| 错误码ID | 错误信息 | 4077| ------- | ------------------------------ | 4078| 2303501 | SSL is null. | 4079| 2300002 | System internal error. | 4080 4081**示例:** 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 4098在TLSSocket通信连接成功之后,向服务端发送消息,使用callback方式作为异步方法。 4099 4100**系统能力**:SystemCapability.Communication.NetStack 4101 4102**参数:** 4103 4104| 参数名 | 类型 | 必填 | 说明 | 4105| -------- | -----------------------------| ---- | ---------------| 4106| data | string | 是 | 发送的数据内容。 | 4107| callback | AsyncCallback\<void\> | 是 | 回调函数,返回TLSSocket发送数据的结果。失败返回错误码,错误信息。 | 4108 4109**错误码:** 4110 4111| 错误码ID | 错误信息 | 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**示例:** 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 4139在TLSSocket通信连接成功之后,向服务端发送消息,使用Promise方式作为异步方法。 4140 4141**系统能力**:SystemCapability.Communication.NetStack 4142 4143**参数:** 4144 4145| 参数名 | 类型 | 必填 | 说明 | 4146| -------- | -----------------------------| ---- | ---------------| 4147| data | string | 是 | 发送的数据内容。 | 4148 4149**错误码:** 4150 4151| 错误码ID | 错误信息 | 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**返回值:** 4161 4162| 类型 | 说明 | 4163| -------------- | -------------------- | 4164| Promise\<void\> | 以Promise形式返回,返回TLSSocket发送数据的结果。失败返回错误码,错误信息。 | 4165 4166**示例:** 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 4183在TLSSocket通信连接成功之后,断开连接,使用callback方式作为异步方法。 4184 4185**系统能力**:SystemCapability.Communication.NetStack 4186 4187**参数:** 4188 4189| 参数名 | 类型 | 必填 | 说明 | 4190| -------- | -----------------------------| ---- | ---------------| 4191| callback | AsyncCallback\<void\> | 是 | 回调函数,成功返回TLSSocket关闭连接的结果。 失败返回错误码,错误信息。 | 4192 4193**错误码:** 4194 4195| 错误码ID | 错误信息 | 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**示例:** 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 4222在TLSSocket通信连接成功之后,断开连接,使用Promise方式作为异步方法。 4223 4224**系统能力**:SystemCapability.Communication.NetStack 4225 4226**返回值:** 4227 4228| 类型 | 说明 | 4229| -------------- | -------------------- | 4230| Promise\<void\> | 以Promise形式返回,返回TLSSocket关闭连接的结果。失败返回错误码,错误信息。 | 4231 4232**错误码:** 4233 4234| 错误码ID | 错误信息 | 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**示例:** 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 4257TLS连接的操作。 4258 4259**系统能力**:SystemCapability.Communication.NetStack 4260 4261| 名称 | 类型 | 必填 | 说明 | 4262| -------------- | ------------------------------------- | --- |-------------- | 4263| address | [NetAddress](#netaddress) | 是 | 网关地址。 | 4264| secureOptions | [TLSSecureOptions](#tlssecureoptions9) | 是 | TLS安全相关操作。| 4265| ALPNProtocols | Array\<string\> | 否 | ALPN协议,支持["spdy/1", "http/1.1"],默认为[]。 | 4266 4267## TLSSecureOptions<sup>9+</sup> 4268 4269TLS安全相关操作,其中ca证书为必选参数,其他参数为可选参数。当本地证书cert和私钥key不为空时,开启双向验证模式。cert和key其中一项为空时,开启单向验证模式。 4270 4271**系统能力**:SystemCapability.Communication.NetStack 4272 4273| 名称 | 类型 | 必填 | 说明 | 4274| --------------------- | ------------------------------------------------------ | --- |----------------------------------- | 4275| ca | string \| Array\<string\> | 是 | 服务端的ca证书,用于认证校验服务端的数字证书。| 4276| cert | string | 否 | 本地客户端的数字证书。 | 4277| key | string | 否 | 本地数字证书的私钥。 | 4278| password | string | 否 | 读取私钥的密码。 | 4279| protocols | [Protocol](#protocol9) \|Array\<[Protocol](#protocol9)\> | 否 | TLS的协议版本,默认为"TLSv1.2"。 | 4280| useRemoteCipherPrefer | boolean | 否 | 优先使用对等方的密码套件。 | 4281| signatureAlgorithms | string | 否 | 通信过程中的签名算法,默认为"" 。 | 4282| cipherSuite | string | 否 | 通信过程中的加密套件,默认为"" 。 | 4283 4284## Protocol<sup>9+</sup> 4285 4286TLS通信的协议版本。 4287 4288**系统能力**:SystemCapability.Communication.NetStack 4289 4290| 名称 | 值 | 说明 | 4291| --------- | --------- |------------------ | 4292| TLSv12 | "TLSv1.2" | 使用TLSv1.2协议通信。 | 4293| TLSv13 | "TLSv1.3" | 使用TLSv1.3协议通信。 | 4294 4295## X509CertRawData<sup>9+</sup> 4296 4297存储证书的数据。 4298 4299**系统能力**:SystemCapability.Communication.NetStack 4300 4301## socket.constructTLSSocketServerInstance<sup>10+</sup> 4302 4303constructTLSSocketServerInstance(): TLSSocketServer 4304 4305创建并返回一个TLSSocketServer对象。 4306 4307**系统能力**:SystemCapability.Communication.NetStack 4308 4309**返回值:** 4310 4311| 类型 | 说明 | 4312| :------------------------------------ | :---------------------------- | 4313| [TLSSocketServer](#tlssocketserver10) | 返回一个TLSSocketServer对象。 | 4314 4315**示例:** 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 4325TLSSocketServer连接。在调用TLSSocketServer的方法前,需要先通过[socket.constructTLSSocketServerInstance](#socketconstructtlssocketserverinstance10)创建TLSSocketServer对象。 4326 4327### listen<sup>10+</sup> 4328 4329listen(options: TLSConnectOptions, callback: AsyncCallback\<void\>): void 4330 4331绑定IP地址和端口,在TLSSocketServer上bind成功之后,监听客户端的连接,创建和初始化TLS会话,实现建立连接过程,加载证书秘钥并验证,使用callback方式作为异步方法。 4332 4333**需要权限**:ohos.permission.INTERNET 4334 4335**系统能力**:SystemCapability.Communication.NetStack 4336 4337**参数:** 4338 4339| 参数名 | 类型 | 必填 | 说明 | 4340| -------- | ---------------------------------------- | ---- | ------------------------------------------------ | 4341| options | [TLSConnectOptions](#tlsconnectoptions9) | 是 | TLSSocketServer连接所需要的参数。 | 4342| callback | AsyncCallback\<void> | 是 | 回调函数,成功返回空,失败返回错误码,错误信息。 | 4343 4344**错误码:** 4345 4346| 错误码ID | 错误信息 | 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**示例:** 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 4394绑定IP地址和端口,在TLSSocketServer上bind成功之后,监听客户端的连接,并创建和初始化TLS会话,实现建立连接过程,加载证书秘钥并验证,使用Promise方式作为异步方法。 4395 4396**需要权限**:ohos.permission.INTERNET 4397 4398**系统能力**:SystemCapability.Communication.NetStack 4399 4400**参数:** 4401 4402| 参数名 | 类型 | 必填 | 说明 | 4403| ------- | ---------------------------------------- | ---- | ------------------ | 4404| options | [TLSConnectOptions](#tlsconnectoptions9) | 是 | 连接所需要的参数。 | 4405 4406**返回值:** 4407 4408| 类型 | 说明 | 4409| --------------- | --------------------------------------------------------- | 4410| Promise\<void\> | 以Promise形式返回,成功返回空,失败返回错误码,错误信息。 | 4411 4412**错误码:** 4413 4414| 错误码ID | 错误信息 | 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**示例:** 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 4464在TLSSocketServer的listen成功之后,获取TLSSocketServer状态。使用callback方式作为异步方法。 4465 4466> **说明:** 4467> listen方法调用成功后,才可调用此方法。 4468 4469**系统能力**:SystemCapability.Communication.NetStack 4470 4471**参数:** 4472 4473| 参数名 | 类型 | 必填 | 说明 | 4474| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | 4475| callback | AsyncCallback\<[SocketStateBase](#socketstatebase7)> | 是 | 回调函数。成功返回TLSSocketServer状态,失败返回错误码,错误信息。 | 4476 4477**错误码:** 4478 4479| 错误码ID | 错误信息 | 4480| -------- | ------------------------------- | 4481| 401 | Parameter error. | 4482| 2303188 | Socket operation on non-socket. | 4483| 2300002 | System internal error. | 4484 4485**示例:** 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 4526在TLSSocketServer的listen成功之后,获取TLSSocketServer状态。使用Promise方式作为异步方法。 4527 4528> **说明:** 4529> listen方法调用成功后,才可调用此方法。 4530 4531**系统能力**:SystemCapability.Communication.NetStack 4532 4533**返回值:** 4534 4535| 类型 | 说明 | 4536| :--------------------------------------------- | :----------------------------------------------------------- | 4537| Promise\<[SocketStateBase](#socketstatebase7)> | 以Promise形式返回获取TLSSocketServer状态的结果。失败返回错误码,错误信息。 | 4538 4539**错误码:** 4540 4541| 错误码ID | 错误信息 | 4542| -------- | ------------------------------- | 4543| 2303188 | Socket operation on non-socket. | 4544| 2300002 | System internal error. | 4545 4546**示例:** 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 4585在TLSSocketServer的listen成功之后,设置TLSSocketServer连接的其他属性。使用callback方式作为异步方法。 4586 4587> **说明:** 4588> listen方法调用成功后,才可调用此方法。 4589 4590**系统能力**:SystemCapability.Communication.NetStack 4591 4592**参数:** 4593 4594| 参数名 | 类型 | 必填 | 说明 | 4595| -------- | ------------------------------------ | ---- | ------------------------------------------------ | 4596| options | [TCPExtraOptions](#tcpextraoptions7) | 是 | TLSSocketServer连接的其他属性。 | 4597| callback | AsyncCallback\<void\> | 是 | 回调函数。成功返回空,失败返回错误码,错误信息。 | 4598 4599**错误码:** 4600 4601| 错误码ID | 错误信息 | 4602| -------- | ------------------------------- | 4603| 401 | Parameter error. | 4604| 2303188 | Socket operation on non-socket. | 4605| 2300002 | System internal error. | 4606 4607**示例:** 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 4659在TLSSocketServer的listen成功之后,设置TLSSocketServer连接的其他属性,使用Promise方式作为异步方法。 4660 4661> **说明:** 4662> listen方法调用成功后,才可调用此方法。 4663 4664**系统能力**:SystemCapability.Communication.NetStack 4665 4666**参数:** 4667 4668| 参数名 | 类型 | 必填 | 说明 | 4669| ------- | ------------------------------------ | ---- | ------------------------------- | 4670| options | [TCPExtraOptions](#tcpextraoptions7) | 是 | TLSSocketServer连接的其他属性。 | 4671 4672**返回值:** 4673 4674| 类型 | 说明 | 4675| :-------------- | :-------------------------------------------------------- | 4676| Promise\<void\> | 以Promise形式返回,成功返回空,失败返回错误码,错误信息。 | 4677 4678**错误码:** 4679 4680| 错误码ID | 错误信息 | 4681| -------- | ------------------------------- | 4682| 401 | Parameter error. | 4683| 2303188 | Socket operation on non-socket. | 4684| 2300002 | System internal error. | 4685 4686**示例:** 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 4736在TLSSocketServer通信连接成功之后,获取本地的数字证书,使用callback方式作为异步方法。 4737 4738> **说明:** 4739> listen方法调用成功后,才可调用此方法。 4740 4741**系统能力**:SystemCapability.Communication.NetStack 4742 4743**参数:** 4744 4745| 参数名 | 类型 | 必填 | 说明 | 4746| -------- | ----------------------------------------------------- | ---- | -------------------------------------------------------- | 4747| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)\> | 是 | 回调函数,成功返回本地的证书,失败返回错误码,错误信息。 | 4748 4749**错误码:** 4750 4751| 错误码ID | 错误信息 | 4752| -------- | ---------------------- | 4753| 401 | Parameter error. | 4754| 2303501 | SSL is null. | 4755| 2303504 | Error looking up x509. | 4756| 2300002 | System internal error. | 4757 4758**示例:** 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 4799在TLSSocketServer通信连接之后,获取本地的数字证书,使用Promise方式作为异步方法。 4800 4801> **说明:** 4802> listen方法调用成功后,才可调用此方法。 4803 4804**系统能力**:SystemCapability.Communication.NetStack 4805 4806**返回值:** 4807 4808| 类型 | 说明 | 4809| ----------------------------------------------- | ------------------------------------------------------------ | 4810| Promise\<[X509CertRawData](#x509certrawdata9)\> | 以Promise形式返回本地的数字证书的结果。失败返回错误码,错误信息。 | 4811 4812**错误码:** 4813 4814| 错误码ID | 错误信息 | 4815| -------- | ---------------------- | 4816| 2303501 | SSL is null. | 4817| 2303504 | Error looking up x509. | 4818| 2300002 | System internal error. | 4819 4820**示例:** 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 4859在TLSSocketServer通信连接成功之后,获取通信的协议版本,使用callback方式作为异步方法。 4860 4861> **说明:** 4862> listen方法调用成功后,才可调用此方法。 4863 4864**系统能力**:SystemCapability.Communication.NetStack 4865 4866**参数:** 4867 4868| 参数名 | 类型 | 必填 | 说明 | 4869| -------- | ----------------------- | ---- | ---------------------------------------------------- | 4870| callback | AsyncCallback\<string\> | 是 | 回调函数,返回通信的协议。失败返回错误码,错误信息。 | 4871 4872**错误码:** 4873 4874| 错误码ID | 错误信息 | 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**示例:** 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 4922在TLSSocketServer通信连接成功之后,获取通信的协议版本,使用Promise方式作为异步方法。 4923 4924> **说明:** 4925> listen方法调用成功后,才可调用此方法。 4926 4927**系统能力**:SystemCapability.Communication.NetStack 4928 4929**返回值:** 4930 4931| 类型 | 说明 | 4932| ----------------- | ------------------------------------------------------- | 4933| Promise\<string\> | 以Promise形式返回通信的协议。失败返回错误码,错误信息。 | 4934 4935**错误码:** 4936 4937| 错误码ID | 错误信息 | 4938| -------- | -------------------------------------- | 4939| 2303501 | SSL is null. | 4940| 2303505 | Error occurred in the tls system call. | 4941| 2300002 | System internal error. | 4942 4943**示例:** 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 4982订阅TLSSocketServer的连接事件。使用callback方式作为异步方法。 4983 4984> **说明:** 4985> listen方法调用成功后,才可调用此方法。 4986 4987**系统能力**:SystemCapability.Communication.NetStack 4988 4989**参数:** 4990 4991| 参数名 | 类型 | 必填 | 说明 | 4992| -------- | ------------------------------------------------------- | ---- | ------------------------------------- | 4993| type | string | 是 | 订阅的事件类型。'connect':连接事件。 | 4994| callback | Callback<[TLSSocketConnection](#tlssocketconnection10)> | 是 | 回调函数。 | 4995 4996**错误码:** 4997 4998| 错误码ID | 错误信息 | 4999| -------- | ---------------- | 5000| 401 | Parameter error. | 5001 5002**示例:** 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 5039取消订阅TLSSocketServer的连接事件。使用callback方式作为异步方法。 5040 5041> **说明:** 5042> listen方法调用成功后,才可调用此方法。 5043> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 5044 5045**系统能力**:SystemCapability.Communication.NetStack 5046 5047**参数:** 5048 5049| 参数名 | 类型 | 必填 | 说明 | 5050| -------- | ------------------------------------------------------- | ---- | ------------------------------------- | 5051| type | string | 是 | 订阅的事件类型。'connect':连接事件。 | 5052| callback | Callback<[TLSSocketConnection](#tlssocketconnection10)> | 否 | 回调函数。 | 5053 5054**错误码:** 5055 5056| 错误码ID | 错误信息 | 5057| -------- | ---------------- | 5058| 401 | Parameter error. | 5059 5060**示例:** 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// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 5094tlsServer.off('connect', callback); 5095tlsServer.off('connect'); 5096``` 5097 5098### on('error')<sup>10+</sup> 5099 5100on(type: 'error', callback: ErrorCallback): void 5101 5102订阅TLSSocketServer连接的error事件。使用callback方式作为异步方法。 5103 5104> **说明:** 5105> listen方法调用成功后,才可调用此方法。 5106 5107**系统能力**:SystemCapability.Communication.NetStack 5108 5109**参数:** 5110 5111| 参数名 | 类型 | 必填 | 说明 | 5112| -------- | ------------- | ---- | ------------------------------------ | 5113| type | string | 是 | 订阅的事件类型。'error':error事件。 | 5114| callback | ErrorCallback | 是 | 回调函数。 | 5115 5116**错误码:** 5117 5118| 错误码ID | 错误信息 | 5119| -------- | ---------------- | 5120| 401 | Parameter error. | 5121 5122**示例:** 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 5159取消订阅TLSSocketServer连接的error事件。使用callback方式作为异步方法。 5160 5161> **说明:** 5162> listen方法调用成功后,才可调用此方法。 5163> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 5164 5165**系统能力**:SystemCapability.Communication.NetStack 5166 5167**参数:** 5168 5169| 参数名 | 类型 | 必填 | 说明 | 5170| -------- | ------------- | ---- | ------------------------------------ | 5171| type | string | 是 | 订阅的事件类型。'error':error事件。 | 5172| callback | ErrorCallback | 否 | 回调函数。 | 5173 5174**错误码:** 5175 5176| 错误码ID | 错误信息 | 5177| -------- | ---------------- | 5178| 401 | Parameter error. | 5179 5180**示例:** 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// 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 5214tlsServer.off('error', callback); 5215tlsServer.off('error'); 5216``` 5217 5218## TLSSocketConnection<sup>10+</sup> 5219 5220TLSSocketConnection连接,即TLSSocket客户端与服务端的连接。在调用TLSSocketConnection的方法前,需要先获取TLSSocketConnection对象。 5221 5222> **说明:** 5223> 客户端与服务端成功建立连接后,才能通过返回的TLSSocketConnection对象调用相应的接口。 5224 5225**系统能力**:SystemCapability.Communication.NetStack 5226 5227### 属性 5228 5229| 名称 | 类型 | 必填 | 说明 | 5230| -------- | ------ | ---- | ------------------------------------- | 5231| clientId | number | 是 | 客户端与TLSSocketServer建立连接的id。 | 5232 5233### send<sup>10+</sup> 5234 5235send(data: string, callback: AsyncCallback\<void\>): void 5236 5237在TLSSocketServer通信连接成功之后,向客户端发送消息,使用callback方式作为异步方法。 5238 5239**系统能力**:SystemCapability.Communication.NetStack 5240 5241**参数:** 5242 5243| 参数名 | 类型 | 必填 | 说明 | 5244| -------- | --------------------- | ---- | ------------------------------------------------ | 5245| data | string | 是 | TLSSocketServer发送数据所需要的参数。 | 5246| callback | AsyncCallback\<void\> | 是 | 回调函数,成功返回空,失败返回错误码,错误信息。 | 5247 5248**错误码:** 5249 5250| 错误码ID | 错误信息 | 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**示例:** 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 5303在TLSSocketServer通信连接成功之后,向服务端发送消息,使用Promise方式作为异步方法。 5304 5305**系统能力**:SystemCapability.Communication.NetStack 5306 5307**参数:** 5308 5309| 参数名 | 类型 | 必填 | 说明 | 5310| ------ | ------ | ---- | ------------------------------------- | 5311| data | string | 是 | TLSSocketServer发送数据所需要的参数。 | 5312 5313**返回值:** 5314 5315| 类型 | 说明 | 5316| --------------- | --------------------------------------------------------- | 5317| Promise\<void\> | 以Promise形式返回,成功返回空,失败返回错误码,错误信息。 | 5318 5319**错误码:** 5320 5321| 错误码ID | 错误信息 | 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**示例:** 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 5372在与TLSSocketServer通信连接成功之后,断开连接,使用callback方式作为异步方法。 5373 5374**系统能力**:SystemCapability.Communication.NetStack 5375 5376**参数:** 5377 5378| 参数名 | 类型 | 必填 | 说明 | 5379| -------- | --------------------- | ---- | ------------------------------------------------ | 5380| callback | AsyncCallback\<void\> | 是 | 回调函数,成功返回空,失败返回错误码,错误信息。 | 5381 5382**错误码:** 5383 5384| 错误码ID | 错误信息 | 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**示例:** 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 5436在与TLSSocketServer通信连接成功之后,断开连接,使用Promise方式作为异步方法。 5437 5438**系统能力**:SystemCapability.Communication.NetStack 5439 5440**返回值:** 5441 5442| 类型 | 说明 | 5443| --------------- | --------------------------------------------------------- | 5444| Promise\<void\> | 以Promise形式返回,成功返回空。失败返回错误码,错误信息。 | 5445 5446**错误码:** 5447 5448| 错误码ID | 错误信息 | 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**示例:** 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 5496在TLSSocketServer通信连接成功之后,获取对端Socket地址。使用callback方式作为异步方法。 5497 5498**系统能力**:SystemCapability.Communication.NetStack 5499 5500**参数:** 5501 5502| 参数名 | 类型 | 必填 | 说明 | 5503| -------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | 5504| callback | AsyncCallback\<[NetAddress](#netaddress7)\> | 是 | 回调函数。成功返回对端的socket地址,失败返回错误码,错误信息。 | 5505 5506**错误码:** 5507 5508| 错误码ID | 错误信息 | 5509| -------- | ------------------------------- | 5510| 401 | Parameter error. | 5511| 2303188 | Socket operation on non-socket. | 5512| 2300002 | System internal error. | 5513 5514**示例:** 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 5557在TLSSocketServer通信连接成功之后,获取对端Socket地址。使用Promise方式作为异步方法。 5558 5559**系统能力**:SystemCapability.Communication.NetStack 5560 5561**返回值:** 5562 5563| 类型 | 说明 | 5564| :----------------------------------- | :----------------------------------------------------------- | 5565| Promise\<[NetAddress](#netaddress7)> | 以Promise形式返回获取对端socket地址的结果。失败返回错误码,错误信息。 | 5566 5567**错误码:** 5568 5569| 错误码ID | 错误信息 | 5570| -------- | ------------------------------- | 5571| 2303188 | Socket operation on non-socket. | 5572| 2300002 | System internal error. | 5573 5574**示例:** 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 5615在TLSSocketServer通信连接成功之后,获取对端的数字证书,该接口只适用于客户端向服务端发送证书时,使用callback方式作为异步方法。 5616 5617**系统能力**:SystemCapability.Communication.NetStack 5618 5619**参数:** 5620 5621| 参数名 | 类型 | 必填 | 说明 | 5622| -------- | ----------------------------------------------------- | ---- | ---------------------------------------------------- | 5623| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)\> | 是 | 回调函数,返回对端的证书。失败返回错误码,错误信息。 | 5624 5625**错误码:** 5626 5627| 错误码ID | 错误信息 | 5628| -------- | ---------------------- | 5629| 401 | Parameter error. | 5630| 2303501 | SSL is null. | 5631| 2300002 | System internal error. | 5632 5633**示例:** 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 5676在TLSSocketServer通信连接成功之后,获取对端的数字证书,该接口只适用于客户端向服务端发送证书时,使用Promise方式作为异步方法。 5677 5678**系统能力**:SystemCapability.Communication.NetStack 5679 5680**返回值:** 5681 5682| 类型 | 说明 | 5683| ----------------------------------------------- | ------------------------------------------------------------ | 5684| Promise\<[X509CertRawData](#x509certrawdata9)\> | 以Promise形式返回对端的数字证书的结果。失败返回错误码,错误信息。 | 5685 5686**错误码:** 5687 5688| 错误码ID | 错误信息 | 5689| -------- | ---------------------- | 5690| 2303501 | SSL is null. | 5691| 2300002 | System internal error. | 5692 5693**示例:** 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 5734在TLSSocketServer通信连接成功之后,获取通信双方协商后的加密套件,使用callback方式作为异步方法。 5735 5736**系统能力**:SystemCapability.Communication.NetStack 5737 5738**参数:** 5739 5740| 参数名 | 类型 | 必填 | 说明 | 5741| -------- | -------------------------------- | ---- | ------------------------------------------------------------ | 5742| callback | AsyncCallback\<Array\<string\>\> | 是 | 回调函数,返回通信双方支持的加密套件。 失败返回错误码,错误信息。 | 5743 5744**错误码:** 5745 5746| 错误码ID | 错误信息 | 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**示例:** 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 5797在TLSSocketServer通信连接成功之后,获取通信双方协商后的加密套件,使用Promise方式作为异步方法。 5798 5799**系统能力**:SystemCapability.Communication.NetStack 5800 5801**返回值:** 5802 5803| 类型 | 说明 | 5804| -------------------------- | ------------------------------------------------------------ | 5805| Promise\<Array\<string\>\> | 以Promise形式返回通信双方支持的加密套件。失败返回错误码,错误信息。 | 5806 5807**错误码:** 5808 5809| 错误码ID | 错误信息 | 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**示例:** 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 5857在TLSSocketServer通信连接成功之后,获取通信双方协商后签名算法,使用callback方式作为异步方法。 5858 5859**系统能力**:SystemCapability.Communication.NetStack 5860 5861**参数:** 5862 5863| 参数名 | 类型 | 必填 | 说明 | 5864| -------- | -------------------------------- | ---- | ---------------------------------- | 5865| callback | AsyncCallback\<Array\<string\>\> | 是 | 回调函数,返回双方支持的签名算法。 | 5866 5867**错误码:** 5868 5869| 错误码ID | 错误信息 | 5870| -------- | ---------------------- | 5871| 401 | Parameter error. | 5872| 2303501 | SSL is null. | 5873| 2300002 | System internal error. | 5874 5875**示例:** 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 5918在TLSSocketServer通信连接成功之后,获取通信双方协商后的签名算法,使用Promise方式作为异步方法。 5919 5920**系统能力**:SystemCapability.Communication.NetStack 5921 5922**返回值:** 5923 5924| 类型 | 说明 | 5925| -------------------------- | --------------------------------------------- | 5926| Promise\<Array\<string\>\> | 以Promise形式返回获取到的双方支持的签名算法。 | 5927 5928**错误码:** 5929 5930| 错误码ID | 错误信息 | 5931| -------- | ---------------------- | 5932| 2303501 | SSL is null. | 5933| 2300002 | System internal error. | 5934 5935**示例:** 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 5976订阅TLSSocketConnection连接的接收消息事件。使用callback方式作为异步方法。 5977 5978**系统能力**:SystemCapability.Communication.NetStack 5979 5980**参数:** 5981 5982| 参数名 | 类型 | 必填 | 说明 | 5983| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 5984| type | string | 是 | 订阅的事件类型。'message':接收消息事件。 | 5985| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo7)}> | 是 | 回调函数。 | 5986 5987**错误码:** 5988 5989| 错误码ID | 错误信息 | 5990| -------- | ---------------- | 5991| 401 | Parameter error. | 5992 5993**示例:** 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 6044取消订阅TLSSocketConnection连接的接收消息事件。使用callback方式作为异步方法。 6045 6046> **说明:** 6047> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 6048 6049**系统能力**:SystemCapability.Communication.NetStack 6050 6051**参数:** 6052 6053| 参数名 | 类型 | 必填 | 说明 | 6054| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | 6055| type | string | 是 | 订阅的事件类型。'message':接收消息事件。 | 6056| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo7)}> | 否 | 回调函数。 | 6057 6058**错误码:** 6059 6060| 错误码ID | 错误信息 | 6061| -------- | ---------------- | 6062| 401 | Parameter error. | 6063 6064**示例:** 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 // 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 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 6119订阅TLSSocketConnection的关闭事件。使用callback方式作为异步方法。 6120 6121**系统能力**:SystemCapability.Communication.NetStack 6122 6123**参数:** 6124 6125| 参数名 | 类型 | 必填 | 说明 | 6126| -------- | ---------------- | ---- | ----------------------------------- | 6127| type | string | 是 | 订阅的事件类型。'close':关闭事件。 | 6128| callback | Callback\<void\> | 是 | 回调函数。 | 6129 6130**错误码:** 6131 6132| 错误码ID | 错误信息 | 6133| -------- | ---------------- | 6134| 401 | Parameter error. | 6135 6136**示例:** 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 6175取消订阅TLSSocketConnection的关闭事件。使用callback方式作为异步方法。 6176 6177> **说明:** 6178> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 6179 6180**系统能力**:SystemCapability.Communication.NetStack 6181 6182**参数:** 6183 6184| 参数名 | 类型 | 必填 | 说明 | 6185| -------- | ---------------- | ---- | ----------------------------------- | 6186| type | string | 是 | 订阅的事件类型。'close':关闭事件。 | 6187| callback | Callback\<void\> | 否 | 回调函数。 | 6188 6189**错误码:** 6190 6191| 错误码ID | 错误信息 | 6192| -------- | ---------------- | 6193| 401 | Parameter error. | 6194 6195**示例:** 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 // 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 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 6239订阅TLSSocketConnection连接的error事件。使用callback方式作为异步方法。 6240 6241**系统能力**:SystemCapability.Communication.NetStack 6242 6243**参数:** 6244 6245| 参数名 | 类型 | 必填 | 说明 | 6246| -------- | ------------- | ---- | ------------------------------------ | 6247| type | string | 是 | 订阅的事件类型。'error':error事件。 | 6248| callback | ErrorCallback | 是 | 回调函数。 | 6249 6250**错误码:** 6251 6252| 错误码ID | 错误信息 | 6253| -------- | ---------------- | 6254| 401 | Parameter error. | 6255 6256**示例:** 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 6296取消订阅TLSSocketConnection连接的error事件。使用callback方式作为异步方法。 6297 6298> **说明:** 6299> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 6300 6301**系统能力**:SystemCapability.Communication.NetStack 6302 6303**参数:** 6304 6305| 参数名 | 类型 | 必填 | 说明 | 6306| -------- | ------------- | ---- | ------------------------------------ | 6307| type | string | 是 | 订阅的事件类型。'error':error事件。 | 6308| callback | ErrorCallback | 否 | 回调函数。 | 6309 6310**错误码:** 6311 6312| 错误码ID | 错误信息 | 6313| -------- | ---------------- | 6314| 401 | Parameter error. | 6315 6316**示例:** 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 // 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 6351 client.off('error', callback); 6352 client.off('error'); 6353}); 6354``` 6355 6356