• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.net.socket (Socket Connection)
2
3The **socket** module implements data transfer over TCP, UDP, Web, and TLS socket connections.
4
5> **NOTE**
6>
7> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8> You are advised to call the APIs of this module in the worker thread or taskpool to perform network-related operations. Otherwise, the UI thread may be suspended.
9
10## Modules to Import
11
12```ts
13import { socket } from '@kit.NetworkKit';
14```
15
16## socket.constructUDPSocketInstance
17
18constructUDPSocketInstance(): UDPSocket
19
20Creates a **UDPSocket** object.
21
22**System capability**: SystemCapability.Communication.NetStack
23
24**Return value**
25
26| Type                              | Description                   |
27|  --------------------------------- |  ---------------------- |
28| [UDPSocket](#udpsocket) | **UDPSocket** object.|
29
30**Example**
31
32```ts
33import { socket } from '@kit.NetworkKit';
34let udp: socket.UDPSocket = socket.constructUDPSocketInstance();
35```
36
37## UDPSocket
38
39Defines a UDP socket connection. Before calling UDPSocket APIs, you need to call [socket.constructUDPSocketInstance](#socketconstructudpsocketinstance) to create a **UDPSocket** object.
40
41### bind
42
43bind(address: NetAddress, callback: AsyncCallback\<void\>): void
44
45Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result.
46
47**Required permissions**: ohos.permission.INTERNET
48
49**System capability**: SystemCapability.Communication.NetStack
50
51**Parameters**
52
53| Name  | Type                              | Mandatory| Description                                                  |
54| -------- | ---------------------------------- | ---- | ------------------------------------------------------ |
55| address  | [NetAddress](#netaddress) | Yes  | Destination address. For details, see [NetAddress](#netaddress).|
56| callback | AsyncCallback\<void\>              | Yes  | Callback used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.       |
57
58**Error codes**
59
60| ID| Error Message                |
61| ------- | ----------------------- |
62| 401     | Parameter error.        |
63| 201     | Permission denied.      |
64
65**Example**
66
67```ts
68import { socket } from '@kit.NetworkKit';
69import { BusinessError } from '@kit.BasicServicesKit';
70
71let udp: socket.UDPSocket = socket.constructUDPSocketInstance();
72let bindAddr: socket.NetAddress = {
73  address: '192.168.xx.xxx',
74  port: 1234
75}
76udp.bind(bindAddr, (err: BusinessError) => {
77  if (err) {
78    console.log('bind fail');
79    return;
80  }
81  console.log('bind success');
82});
83```
84
85### bind
86
87bind(address: NetAddress): Promise\<void\>
88
89Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result.
90
91**Required permissions**: ohos.permission.INTERNET
92
93**System capability**: SystemCapability.Communication.NetStack
94
95**Parameters**
96
97| Name | Type                              | Mandatory| Description                                                  |
98| ------- | ---------------------------------- | ---- | ------------------------------------------------------ |
99| address | [NetAddress](#netaddress) | Yes  | Destination address. For details, see [NetAddress](#netaddress).|
100
101**Error codes**
102
103| ID| Error Message                |
104| ------- | ----------------------- |
105| 401     | Parameter error.        |
106| 201     | Permission denied.      |
107
108**Return value**
109
110| Type           | Description                                      |
111|  -------------- |  ----------------------------------------- |
112| Promise\<void\> | Promise used to return the result.|
113
114**Example**
115
116```ts
117import { socket } from '@kit.NetworkKit';
118import { BusinessError } from '@kit.BasicServicesKit';
119
120let udp: socket.UDPSocket = socket.constructUDPSocketInstance();
121let bindAddr: socket.NetAddress = {
122  address: '192.168.xx.xxx',
123  port: 8080
124}
125udp.bind(bindAddr).then(() => {
126  console.log('bind success');
127}).catch((err: BusinessError) => {
128  console.log('bind fail');
129});
130```
131
132### send
133
134send(options: UDPSendOptions, callback: AsyncCallback\<void\>): void
135
136Sends data over a UDP socket connection. This API uses an asynchronous callback to return the result.
137
138Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and port. Call the API in the worker thread or taskpool thread as this operation is time-consuming.
139
140**Required permissions**: ohos.permission.INTERNET
141
142**System capability**: SystemCapability.Communication.NetStack
143
144**Parameters**
145
146| Name  | Type                                    | Mandatory| Description                                                        |
147| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
148| options  | [UDPSendOptions](#udpsendoptions) | Yes  | Parameters for sending data over a UDP socket connection. For details, see [UDPSendOptions](#udpsendoptions).|
149| callback | AsyncCallback\<void\>                    | Yes  | Callback used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.                                                 |
150
151**Error codes**
152
153| ID| Error Message                |
154| ------- | ----------------------- |
155| 401     | Parameter error.        |
156| 201     | Permission denied.      |
157| 2301206 | Socks5 failed to connect to the proxy server.  |
158| 2301207 | Socks5 username or password is invalid.        |
159| 2301208 | Socks5 failed to connect to the remote server. |
160| 2301209 | Socks5 failed to negotiate the authentication method. |
161| 2301210 | Socks5 failed to send the message.             |
162| 2301211 | Socks5 failed to receive the message.          |
163| 2301212 | Socks5 serialization error.                    |
164| 2301213 | Socks5 deserialization error.                  |
165
166**Example**
167
168```ts
169import { socket } from '@kit.NetworkKit';
170import { BusinessError } from '@kit.BasicServicesKit';
171
172let udp: socket.UDPSocket = socket.constructUDPSocketInstance();
173let netAddress: socket.NetAddress = {
174  address: '192.168.xx.xxx',
175  port: 8080
176}
177let sendOptions: socket.UDPSendOptions = {
178  data: 'Hello, server!',
179  address: netAddress
180}
181udp.send(sendOptions, (err: BusinessError) => {
182  if (err) {
183    console.log('send fail');
184    return;
185  }
186  console.log('send success');
187});
188```
189
190**Example (with socket proxy):**
191
192```ts
193import { socket } from '@kit.NetworkKit';
194import { BusinessError } from '@kit.BasicServicesKit';
195
196let udp: socket.UDPSocket = socket.constructUDPSocketInstance();
197let netAddress: socket.NetAddress = {
198  address: '192.168.xx.xxx',
199  port: 8080
200}
201let socks5Server: socket.NetAddress = {
202  address: '192.168.xx.xxx',
203  port: 8080
204}
205let sendOptions: socket.UDPSendOptions = {
206  data: 'Hello, server!',
207  address: netAddress,
208  proxy: socket.ProxyOptions = {
209    type : 1,
210    address: socks5Server,
211    username: "xxx",
212    password: "xxx"
213  }
214}
215udp.send(sendOptions, (err: BusinessError) => {
216  if (err) {
217    console.log('send fail');
218    return;
219  }
220  console.log('send success');
221});
222```
223
224### send
225
226send(options: UDPSendOptions): Promise\<void\>
227
228Sends data over a UDP socket connection. This API uses a promise to return the result.
229
230Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and port. Call the API in the worker thread or taskpool thread as this operation is time-consuming.
231
232**Required permissions**: ohos.permission.INTERNET
233
234**System capability**: SystemCapability.Communication.NetStack
235
236**Parameters**
237
238| Name | Type                                    | Mandatory| Description                                                        |
239| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
240| options | [UDPSendOptions](#udpsendoptions) | Yes  | Parameters for sending data over a UDP socket connection. For details, see [UDPSendOptions](#udpsendoptions).|
241
242**Error codes**
243
244| ID| Error Message                |
245| ------- | ----------------------- |
246| 401     | Parameter error.        |
247| 201     | Permission denied.      |
248| 2301206 | Socks5 failed to connect to the proxy server.  |
249| 2301207 | Socks5 username or password is invalid.        |
250| 2301208 | Socks5 failed to connect to the remote server. |
251| 2301209 | Socks5 failed to negotiate the authentication method. |
252| 2301210 | Socks5 failed to send the message.             |
253| 2301211 | Socks5 failed to receive the message.          |
254| 2301212 | Socks5 serialization error.                    |
255| 2301213 | Socks5 deserialization error.                  |
256
257**Return value**
258
259| Type           | Description                                          |
260|  -------------- |  --------------------------------------------- |
261| Promise\<void\> | Promise used to return the result.|
262
263**Example**
264
265```ts
266import { socket } from '@kit.NetworkKit';
267import { BusinessError } from '@kit.BasicServicesKit';
268
269let udp: socket.UDPSocket = socket.constructUDPSocketInstance();
270let netAddress: socket.NetAddress = {
271  address: '192.168.xx.xxx',
272  port: 8080
273}
274let sendOptions: socket.UDPSendOptions = {
275  data: 'Hello, server!',
276  address: netAddress
277}
278udp.send(sendOptions).then(() => {
279  console.log('send success');
280}).catch((err: BusinessError) => {
281  console.log('send fail');
282});
283```
284
285**Example (with socket proxy):**
286
287```ts
288import { socket } from '@kit.NetworkKit';
289import { BusinessError } from '@kit.BasicServicesKit';
290
291let udp: socket.UDPSocket = socket.constructUDPSocketInstance();
292let netAddress: socket.NetAddress = {
293  address: '192.168.xx.xxx',
294  port: 8080
295}
296let socks5Server: socket.NetAddress = {
297  address: '192.168.xx.xxx',
298  port: 8080
299}
300let sendOptions: socket.UDPSendOptions = {
301  data: 'Hello, server!',
302  address: netAddress,
303  proxy: socket.ProxyOptions = {
304    type : 1,
305    address: socks5Server,
306    username: "xxx",
307    password: "xxx"
308  }
309}
310udp.send(sendOptions).then(() => {
311  console.log('send success');
312}).catch((err: BusinessError) => {
313  console.log('send fail');
314});
315```
316
317### close
318
319close(callback: AsyncCallback\<void\>): void
320
321Closes a UDP socket connection. This API uses an asynchronous callback to return the result.
322
323**Required permissions**: ohos.permission.INTERNET
324
325**System capability**: SystemCapability.Communication.NetStack
326
327**Parameters**
328
329| Name  | Type                 | Mandatory| Description      |
330| -------- | --------------------- | ---- | ---------- |
331| callback | AsyncCallback\<void\> | Yes  | Callback used to return the result.  |
332
333**Error codes**
334
335| ID| Error Message                |
336| ------- | ----------------------- |
337| 201     | Permission denied.      |
338
339**Example**
340
341```ts
342import { socket } from '@kit.NetworkKit';
343import { BusinessError } from '@kit.BasicServicesKit';
344
345let udp: socket.UDPSocket = socket.constructUDPSocketInstance();
346udp.close((err: BusinessError) => {
347  if (err) {
348    console.log('close fail');
349    return;
350  }
351  console.log('close success');
352})
353```
354
355### close
356
357close(): Promise\<void\>
358
359Closes a UDP socket connection. This API uses a promise to return the result.
360
361**Required permissions**: ohos.permission.INTERNET
362
363**System capability**: SystemCapability.Communication.NetStack
364
365**Error codes**
366
367| ID| Error Message                |
368| ------- | ----------------------- |
369| 201     | Permission denied.      |
370
371**Return value**
372
373| Type           | Description                                      |
374|  -------------- |  ----------------------------------------- |
375| Promise\<void\> | Promise used to return the result.|
376
377**Example**
378
379```ts
380import { socket } from '@kit.NetworkKit';
381import { BusinessError } from '@kit.BasicServicesKit';
382
383let udp: socket.UDPSocket = socket.constructUDPSocketInstance();
384udp.close().then(() => {
385  console.log('close success');
386}).catch((err: BusinessError) => {
387  console.log('close fail');
388});
389```
390
391### getState
392
393getState(callback: AsyncCallback\<SocketStateBase\>): void
394
395Obtains the status of the UDP socket connection. This API uses an asynchronous callback to return the result.
396
397> **NOTE**
398> This API can be called only after **bind** is successfully called.
399
400**Required permissions**: ohos.permission.INTERNET
401
402**System capability**: SystemCapability.Communication.NetStack
403
404**Parameters**
405
406| Name  | Type                                                  | Mandatory| Description      |
407| -------- | ------------------------------------------------------ | ---- | ---------- |
408| callback | AsyncCallback\<[SocketStateBase](#socketstatebase)\> | Yes  | Callback used to return the result. If the operation is successful, the status of the TLS socket server connection is returned. If the operation fails, an error message is returned.|
409
410**Error codes**
411
412| ID| Error Message                |
413| ------- | ----------------------- |
414| 201     | Permission denied.      |
415
416**Example**
417
418```ts
419import { socket } from '@kit.NetworkKit';
420import { BusinessError } from '@kit.BasicServicesKit';
421
422let udp: socket.UDPSocket = socket.constructUDPSocketInstance();
423let bindAddr: socket.NetAddress = {
424  address: '192.168.xx.xxx',
425  port: 8080
426}
427udp.bind(bindAddr, (err: BusinessError) => {
428  if (err) {
429    console.log('bind fail');
430    return;
431  }
432  console.log('bind success');
433  udp.getState((err: BusinessError, data: socket.SocketStateBase) => {
434    if (err) {
435      console.log('getState fail');
436      return;
437    }
438    console.log('getState success:' + JSON.stringify(data));
439  })
440})
441```
442
443### getState
444
445getState(): Promise\<SocketStateBase\>
446
447Obtains the status of the UDP socket connection. This API uses a promise to return the result.
448
449> **NOTE**
450> This API can be called only after **bind** is successfully called.
451
452**Required permissions**: ohos.permission.INTERNET
453
454**System capability**: SystemCapability.Communication.NetStack
455
456**Error codes**
457
458| ID| Error Message                |
459| ------- | ----------------------- |
460| 201     | Permission denied.      |
461
462**Return value**
463
464| Type                                            | Description                                      |
465|  ----------------------------------------------- |  ----------------------------------------- |
466| Promise\<[SocketStateBase](#socketstatebase)\> | Promise used to return the result.|
467
468**Example**
469
470```ts
471import { socket } from '@kit.NetworkKit';
472import { BusinessError } from '@kit.BasicServicesKit';
473
474let udp: socket.UDPSocket = socket.constructUDPSocketInstance();
475let bindAddr: socket.NetAddress = {
476  address: '192.168.xx.xxx',
477  port: 8080
478}
479udp.bind(bindAddr, (err: BusinessError) => {
480  if (err) {
481    console.log('bind fail');
482    return;
483  }
484  console.log('bind success');
485  udp.getState().then((data: socket.SocketStateBase) => {
486    console.log('getState success:' + JSON.stringify(data));
487  }).catch((err: BusinessError) => {
488    console.log('getState fail' + JSON.stringify(err));
489  });
490});
491```
492
493### setExtraOptions
494
495setExtraOptions(options: UDPExtraOptions, callback: AsyncCallback\<void\>): void
496
497Sets other properties of the UDP socket connection. This API uses an asynchronous callback to return the result.
498
499> **NOTE**
500> This API can be called only after **bind** is successfully called.
501
502**Required permissions**: ohos.permission.INTERNET
503
504**System capability**: SystemCapability.Communication.NetStack
505
506**Parameters**
507
508| Name  | Type                                    | Mandatory| Description                                                        |
509| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
510| options  | [UDPExtraOptions](#udpextraoptions) | Yes  | Other properties of the UDP socket connection. For details, see [UDPExtraOptions](#udpextraoptions).|
511| callback | AsyncCallback\<void\>                    | Yes  | Callback used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.                   |
512
513**Error codes**
514
515| ID| Error Message                |
516| ------- | ----------------------- |
517| 401     | Parameter error.        |
518| 201     | Permission denied.      |
519
520**Example**
521
522```ts
523import { socket } from '@kit.NetworkKit';
524import { BusinessError } from '@kit.BasicServicesKit';
525
526let udp: socket.UDPSocket = socket.constructUDPSocketInstance();
527
528let bindAddr: socket.NetAddress = {
529  address: '192.168.xx.xxx',
530  port: 8080
531}
532udp.bind(bindAddr, (err: BusinessError) => {
533  if (err) {
534    console.log('bind fail');
535    return;
536  }
537  console.log('bind success');
538  let udpextraoptions: socket.UDPExtraOptions = {
539    receiveBufferSize: 6000000,
540    sendBufferSize: 2000000,
541    reuseAddress: false,
542    socketTimeout: 6000,
543    broadcast: true
544  }
545  udp.setExtraOptions(udpextraoptions, (err: BusinessError) => {
546    if (err) {
547      console.log('setExtraOptions fail');
548      return;
549    }
550    console.log('setExtraOptions success');
551  })
552})
553```
554
555### setExtraOptions
556
557setExtraOptions(options: UDPExtraOptions): Promise\<void\>
558
559Sets other properties of the UDP socket connection. This API uses a promise to return the result.
560
561> **NOTE**
562> This API can be called only after **bind** is successfully called.
563
564**Required permissions**: ohos.permission.INTERNET
565
566**System capability**: SystemCapability.Communication.NetStack
567
568**Parameters**
569
570| Name | Type                                    | Mandatory| Description                                                        |
571| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
572| options | [UDPExtraOptions](#udpextraoptions) | Yes  | Other properties of the UDP socket connection. For details, see [UDPExtraOptions](#udpextraoptions).|
573
574**Return value**
575
576| Type           | Description                                                |
577|  -------------- |  --------------------------------------------------- |
578| Promise\<void\> | Promise used to return the result.|
579
580**Error codes**
581
582| ID| Error Message                |
583| ------- | ----------------------- |
584| 401     | Parameter error.        |
585| 201     | Permission denied.      |
586
587**Example**
588
589```ts
590import { socket } from '@kit.NetworkKit';
591import { BusinessError } from '@kit.BasicServicesKit';
592
593let udp: socket.UDPSocket = socket.constructUDPSocketInstance();
594
595let bindAddr: socket.NetAddress = {
596  address: '192.168.xx.xxx',
597  port: 8080
598}
599udp.bind(bindAddr, (err: BusinessError) => {
600  if (err) {
601    console.log('bind fail');
602    return;
603  }
604  console.log('bind success');
605  let udpextraoptions: socket.UDPExtraOptions = {
606    receiveBufferSize: 6000000,
607    sendBufferSize: 2000000,
608    reuseAddress: false,
609    socketTimeout: 6000,
610    broadcast: true
611  }
612  udp.setExtraOptions(udpextraoptions).then(() => {
613    console.log('setExtraOptions success');
614  }).catch((err: BusinessError) => {
615    console.log('setExtraOptions fail');
616  });
617})
618```
619
620### getLocalAddress<sup>12+</sup>
621
622getLocalAddress(): Promise\<NetAddress\>
623
624Obtains the local socket address of a **UDPSocket** connection. This API uses a promise to return the result.
625
626> **NOTE**
627> This API can be called only after **bind** is successfully called.
628
629**System capability**: SystemCapability.Communication.NetStack
630
631**Return value**
632
633| Type           | Description                                                |
634|  -------------- |  --------------------------------------------------- |
635| Promise\<[NetAddress](#netaddress)\> | Promise used to return the result.|
636
637**Error codes**
638
639| ID| Error Message                                   |
640| -------- | ------------------------------------------- |
641| 2300002  | System internal error.                      |
642| 2301009  | Bad file descriptor.                            |
643| 2303188  | Socket operation on non-socket. |
644
645**Example**
646
647```ts
648import { socket } from '@kit.NetworkKit';
649import { BusinessError } from '@kit.BasicServicesKit';
650
651let udp: socket.UDPSocket = socket.constructUDPSocketInstance();
652
653let bindAddr: socket.NetAddress = {
654  address: '192.168.xx.xxx',
655  port: 8080
656}
657udp.bind(bindAddr).then(() => {
658  console.info('bind success');
659  udp.getLocalAddress().then((localAddress: socket.NetAddress) => {
660        console.info("UDP_Socket get SUCCESS! Address: " + JSON.stringify(localAddress));
661      }).catch((err: BusinessError) => {
662        console.error("UDP_Socket get FAILED! Error: " + JSON.stringify(err));
663      })
664}).catch((err: BusinessError) => {
665  console.error('bind fail');
666});
667```
668
669### on('message')
670
671on(type: 'message', callback: Callback\<SocketMessageInfo\>): void
672
673Subscribes to **message** events of the UDP socket connection. This API uses an asynchronous callback to return the result.
674
675**System capability**: SystemCapability.Communication.NetStack
676
677**Parameters**
678
679| Name  | Type                                                        | Mandatory| Description                                     |
680| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
681| type     | string                                                       | Yes  | Event type.<br/> **message**: message receiving event.|
682| callback | Callback\<[SocketMessageInfo](#socketmessageinfo11)\> | Yes  | Callback used to return the result.        |
683
684**Example**
685
686```ts
687import { socket } from '@kit.NetworkKit';
688import { BusinessError } from '@kit.BasicServicesKit';
689
690let udp: socket.UDPSocket = socket.constructUDPSocketInstance();
691
692let messageView = '';
693udp.on('message', (value: socket.SocketMessageInfo) => {
694  for (let i: number = 0; i < value.message.byteLength; i++) {
695    let uint8Array = new Uint8Array(value.message)
696    let messages = uint8Array[i]
697    let message = String.fromCharCode(messages);
698    messageView += message;
699  }
700  console.log('on message message: ' + JSON.stringify(messageView));
701  console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo));
702});
703```
704
705### off('message')
706
707off(type: 'message', callback?: Callback\<SocketMessageInfo\>): void
708
709Unsubscribes from **message** events of the UDP socket connection. This API uses an asynchronous callback to return the result.
710
711**System capability**: SystemCapability.Communication.NetStack
712
713**Parameters**
714
715| Name  | Type                                                        | Mandatory| Description                                     |
716| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
717| type     | string                                                       | Yes  | Event type.<br/> **message**: message receiving event.|
718| callback | Callback\<[SocketMessageInfo](#socketmessageinfo11)\> | No  | Callback used to return the result.                               |
719
720**Example**
721
722```ts
723import { socket } from '@kit.NetworkKit';
724import { BusinessError } from '@kit.BasicServicesKit';
725
726let udp: socket.UDPSocket = socket.constructUDPSocketInstance();
727let messageView = '';
728let callback = (value: socket.SocketMessageInfo) => {
729  for (let i: number = 0; i < value.message.byteLength; i++) {
730    let uint8Array = new Uint8Array(value.message)
731    let messages = uint8Array[i]
732    let message = String.fromCharCode(messages);
733    messageView += message;
734  }
735  console.log('on message message: ' + JSON.stringify(messageView));
736  console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo));
737}
738udp.on('message', callback);
739// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
740udp.off('message', callback);
741udp.off('message');
742```
743
744### on('listening' | 'close')
745
746on(type: 'listening' | 'close', callback: Callback\<void\>): void
747
748Subscribes to **listening** events or **close** events of the UDP socket connection. This API uses an asynchronous callback to return the result.
749
750**System capability**: SystemCapability.Communication.NetStack
751
752**Parameters**
753
754| Name  | Type            | Mandatory| Description                                                        |
755| -------- | ---------------- | ---- | ------------------------------------------------------------ |
756| type     | string           | Yes  | Event type.<br>- **listening**: data packet message event.<br>- **close**: close event.|
757| callback | Callback\<void\> | Yes  | Callback used to return the result.            |
758
759**Example**
760
761```ts
762import { socket } from '@kit.NetworkKit';
763import { BusinessError } from '@kit.BasicServicesKit';
764
765let udp: socket.UDPSocket = socket.constructUDPSocketInstance();
766udp.on('listening', () => {
767  console.log("on listening success");
768});
769udp.on('close', () => {
770  console.log("on close success");
771});
772```
773
774### off('listening' | 'close')
775
776off(type: 'listening' | 'close', callback?: Callback\<void\>): void
777
778Unsubscribes from **listening** events or **close** events of the UDP socket connection. This API uses an asynchronous callback to return the result.
779
780**System capability**: SystemCapability.Communication.NetStack
781
782**Parameters**
783
784| Name  | Type            | Mandatory| Description                                                        |
785| -------- | ---------------- | ---- | ------------------------------------------------------------ |
786| type     | string           | Yes  | Event type.<br>- **listening**: data packet message event.<br>- **close**: close event.|
787| callback | Callback\<void\> | No  | Callback used to return the result.      |
788
789**Example**
790
791```ts
792import { socket } from '@kit.NetworkKit';
793import { BusinessError } from '@kit.BasicServicesKit';
794
795let udp: socket.UDPSocket = socket.constructUDPSocketInstance();
796let callback1 = () => {
797  console.log("on listening, success");
798}
799udp.on('listening', callback1);
800// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
801udp.off('listening', callback1);
802udp.off('listening');
803let callback2 = () => {
804  console.log("on close, success");
805}
806udp.on('close', callback2);
807// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
808udp.off('close', callback2);
809udp.off('close');
810```
811
812### on('error')
813
814on(type: 'error', callback: ErrorCallback): void
815
816Subscribes to **error** events of the UDP socket connection. This API uses an asynchronous callback to return the result.
817
818**System capability**: SystemCapability.Communication.NetStack
819
820**Parameters**
821
822| Name  | Type         | Mandatory| Description                                |
823| -------- | ------------- | ---- | ------------------------------------ |
824| type     | string        | Yes  | Event type.<br/> **error**: error event.|
825| callback | ErrorCallback | Yes  | Callback used to return the result.                       |
826
827**Example**
828
829```ts
830import { socket } from '@kit.NetworkKit';
831import { BusinessError } from '@kit.BasicServicesKit';
832
833let udp: socket.UDPSocket = socket.constructUDPSocketInstance();
834udp.on('error', (err: BusinessError) => {
835  console.log("on error, err:" + JSON.stringify(err))
836});
837```
838
839### off('error')
840
841off(type: 'error', callback?: ErrorCallback): void
842
843Unsubscribes from **error** events of the UDP socket connection. This API uses an asynchronous callback to return the result.
844
845**System capability**: SystemCapability.Communication.NetStack
846
847**Parameters**
848
849| Name  | Type         | Mandatory| Description                                |
850| -------- | ------------- | ---- | ------------------------------------ |
851| type     | string        | Yes  | Event type.<br/> **error**: error event.|
852| callback | ErrorCallback | No  | Callback used to return the result.       |
853
854**Example**
855
856```ts
857import { socket } from '@kit.NetworkKit';
858import { BusinessError } from '@kit.BasicServicesKit';
859
860let udp: socket.UDPSocket = socket.constructUDPSocketInstance();
861let callback = (err: BusinessError) => {
862  console.log("on error, err:" + JSON.stringify(err));
863}
864udp.on('error', callback);
865// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
866udp.off('error', callback);
867udp.off('error');
868```
869
870## NetAddress
871
872Defines the destination address.
873
874**System capability**: SystemCapability.Communication.NetStack
875
876| Name | Type  | Mandatory| Description                                                        |
877| ------- | ------ | ---- | ------------------------------------------------------------ |
878| address<sup>11+</sup> | string | Yes  | Bound IP address.                                          |
879| port    | number | No  | Port number. The value ranges from **0** to **65535**. If this parameter is not specified, the system randomly allocates a port.          |
880| family  | number | No  | Network protocol type.<br>- **1**: IPv4 The default value is **1**.<br>- **2**: IPv6 For an IPv6 address, this field must be explicitly set to **2**.<br>- **3**: domain address<sup>18+</sup> For a domain address, this field must be explicitly set to **3**.|
881
882## ProxyOptions<sup>18+</sup>
883
884Defines the socket proxy information.
885
886**System capability**: SystemCapability.Communication.NetStack
887
888| Name | Type  | Mandatory| Description                                                        |
889| ------- | ------ | ---- | ------------------------------------------------------------ |
890| type    | [ProxyTypes](#proxytypes18) | Yes  | Proxy type.                                |
891| address | [NetAddress](#netaddress) | Yes  | Proxy address.                            |
892| username  | string | No  | User name. This field must be specified if the user password authentication mode is used. |
893| password  | string | No  | Password. This field must be specified if the user password authentication mode is used.|
894
895## ProxyTypes<sup>18+</sup>
896
897Enumerates socket proxy types.
898
899**System capability**: SystemCapability.Communication.NetStack
900
901| Name     |    Value   | Description               |
902| --------- | --------- |------------------ |
903| NONE    | 0 | No proxy.|
904| SOCKS5  | 1 | SOCKS5 proxy.|
905
906## UDPSendOptions
907
908Defines the parameters for sending data over a UDP socket connection.
909
910**System capability**: SystemCapability.Communication.NetStack
911
912| Name | Type                              | Mandatory| Description          |
913| ------- | ---------------------------------- | ---- | -------------- |
914| data    | string \| ArrayBuffer                          | Yes  | Data to send.  |
915| address | [NetAddress](#netaddress) | Yes  | Destination address.|
916| proxy<sup>18+</sup>   | [ProxyOptions](#proxyoptions18) | No  | Proxy option. By default, no proxy is used.|
917
918## UDPExtraOptions
919
920Defines other properties of the UDP socket connection. This API inherits from [ExtraOptionsBase](#extraoptionsbase7).
921
922**System capability**: SystemCapability.Communication.NetStack
923
924| Name           | Type   | Mandatory| Description                            |
925| ----------------- | ------- | ---- | -------------------------------- |
926| broadcast         | boolean | No  | Whether to send broadcast messages. The default value is **false**. The value **true** means to send broadcast messages, and the value **false** means the opposite. |
927
928## SocketMessageInfo<sup>11+</sup>
929
930Defines the socket connection information.
931
932**System capability**: SystemCapability.Communication.NetStack
933
934| Name       | Type  | Mandatory| Description                                 |
935| ---------- | ------ | ---- | ------------------------------------- |
936| message    | ArrayBuffer | Yes  | Received **message** event.|
937| remoteInfo | [SocketRemoteInfo](#socketremoteinfo) | Yes  | Socket connection information.|
938
939## SocketStateBase
940
941Defines the status of the socket connection.
942
943**System capability**: SystemCapability.Communication.NetStack
944
945| Name     | Type   | Mandatory| Description      |
946| ----------- | ------- | ---- | ---------- |
947| isBound     | boolean | Yes  | Whether the connection is in the bound state. The value **true** indicates that the connection is in the bound state, and the value **false** indicates the opposite.|
948| isClose     | boolean | Yes  | Whether the connection is in the closed state. The value **true** indicates that the connection is in the closed state, and the value **false** indicates the opposite.|
949| isConnected | boolean | Yes  | Whether the connection is in the connected state. The value **true** indicates that the connection is in the connected state, and the value **false** indicates the opposite.|
950
951## SocketRemoteInfo
952
953Defines information about the socket connection.
954
955**System capability**: SystemCapability.Communication.NetStack
956
957| Name | Type  | Mandatory| Description                                                        |
958| ------- | ------ | ---- | ------------------------------------------------------------ |
959| address | string | Yes  | Bound IP address.                                          |
960| family  | 'IPv4' \| 'IPv6' | Yes  | Network protocol type.<br>- IPv4<br>- IPv6<br>The default value is **IPv4**.|
961| port    | number | Yes  | Port number. The value ranges from **0** to **65535**.                                       |
962| size    | number | Yes  | Length of the server response message, in bytes.                                  |
963
964## Description of UDP Error Codes
965
966The UDP error code mapping is in the format of 2301000 + Linux kernel error code.
967
968For details about error codes, see [Socket Error Codes](errorcode-net-socket.md).
969
970## socket.constructMulticastSocketInstance<sup>11+</sup>
971
972constructMulticastSocketInstance(): MulticastSocket
973
974Creates a **MulticastSocket** object.
975
976**System capability**: SystemCapability.Communication.NetStack
977
978**Return value**
979
980| Type                              | Description                   |
981| ----------------------------------- | ----------------------------- |
982| [MulticastSocket](#multicastsocket11) | **MulticastSocket** object.|
983
984**Example**
985
986```ts
987import { socket } from '@kit.NetworkKit';
988let multicast: socket.MulticastSocket = socket.constructMulticastSocketInstance();
989```
990## MulticastSocket<sup>11+</sup>
991
992Defines a **MulticastSocket** connection. Before calling MulticastSocket APIs, you need to call [socket.constructMulticastSocketInstance](#socketconstructmulticastsocketinstance11) to create a **MulticastSocket** object.
993
994### addMembership<sup>11+</sup>
995
996addMembership(multicastAddress: NetAddress, callback: AsyncCallback\<void\>): void
997
998Adds a member to a multicast group. This API uses an asynchronous callback to return the result.
999
1000> **NOTE**
1001> The IP addresses used for multicast belong to a specific range, for example, 224.0.0.0 to 239.255.255.255.
1002> A member in a multicast group can serve as a sender or a receiver. Data is transmitted in broadcast mode, regardless of the client or server.
1003
1004**Required permissions**: ohos.permission.INTERNET
1005
1006**System capability**: SystemCapability.Communication.NetStack
1007
1008**Parameters**
1009
1010| Name            | Type                          | Mandatory| Description                                      |
1011| ----------------- | ----------------------------- | ---- | ----------------------------------------- |
1012| multicastAddress  | [NetAddress](#netaddress)     |  Yes | Destination address. For details, see [NetAddress](#netaddress).|
1013| callback          | AsyncCallback\<void\>         |  Yes | Callback used to return the result. If the operation fails, an error message is returned.                                |
1014
1015**Error codes**
1016
1017| ID| Error Message                |
1018| ------- | ----------------------- |
1019| 401     | Parameter error.        |
1020| 201     | Permission denied.      |
1021| 2301022 | Invalid argument.       |
1022| 2301088 | Not a socket.           |
1023| 2301098 | Address in use.         |
1024
1025**Example**
1026
1027```ts
1028import { socket } from '@kit.NetworkKit';
1029
1030let multicast: socket.MulticastSocket = socket.constructMulticastSocketInstance();
1031let addr: socket.NetAddress = {
1032  address: '239.255.0.1',
1033  port: 8080
1034}
1035multicast.addMembership(addr, (err: Object) => {
1036  if (err) {
1037    console.log('add membership fail, err: ' + JSON.stringify(err));
1038    return;
1039  }
1040  console.log('add membership success');
1041})
1042```
1043
1044### addMembership<sup>11+</sup>
1045
1046addMembership(multicastAddress: NetAddress): Promise\<void\>
1047
1048Adds a member to a multicast group. This API uses a promise to return the result.
1049
1050> **NOTE**
1051> The IP addresses used for multicast belong to a specific range, for example, 224.0.0.0 to 239.255.255.255.
1052> A member in a multicast group can serve as a sender or a receiver. Data is transmitted in broadcast mode, regardless of the client or server.
1053
1054**Required permissions**: ohos.permission.INTERNET
1055
1056**System capability**: SystemCapability.Communication.NetStack
1057
1058**Parameters**
1059
1060| Name            | Type                          | Mandatory| Description                                          |
1061| ----------------- | ----------------------------- | ---- | --------------------------------------------  |
1062| multicastAddress  | [NetAddress](#netaddress)     |  Yes | Destination address. For details, see [NetAddress](#netaddress).|
1063
1064**Return value**
1065
1066| Type           | Description                                              |
1067|  -------------- |  -----------------------------------------------  |
1068| Promise\<void\> | Promise used to return the result.|
1069
1070**Error codes**
1071
1072| ID| Error Message                |
1073| ------- | ----------------------- |
1074| 401     | Parameter error.        |
1075| 201     | Permission denied.      |
1076| 2301088 | Not a socket.           |
1077| 2301098 | Address in use.         |
1078
1079**Example**
1080
1081```ts
1082import { socket } from '@kit.NetworkKit';
1083
1084let multicast: socket.MulticastSocket = socket.constructMulticastSocketInstance();
1085let addr: socket.NetAddress = {
1086  address: '239.255.0.1',
1087  port: 8080
1088}
1089multicast.addMembership(addr).then(() => {
1090  console.log('addMembership success');
1091}).catch((err: Object) => {
1092  console.log('addMembership fail');
1093});
1094```
1095
1096### dropMembership<sup>11+</sup>
1097
1098dropMembership(multicastAddress: NetAddress, callback: AsyncCallback\<void\>): void
1099
1100Drops a member from a multicast group. This API uses an asynchronous callback to return the result.
1101
1102> **NOTE**
1103> The IP addresses used for multicast belong to a specific range, for example, 224.0.0.0 to 239.255.255.255.
1104> You can drop only a member that has been added to a multicast group by using [addMembership](#addmembership11).
1105
1106**Required permissions**: ohos.permission.INTERNET
1107
1108**System capability**: SystemCapability.Communication.NetStack
1109
1110**Parameters**
1111
1112| Name            | Type                          | Mandatory| Description                                        |
1113| ----------------- | ----------------------------- | ---- | ------------------------------------------- |
1114| multicastAddress  | [NetAddress](#netaddress)     |  Yes | Destination address. For details, see [NetAddress](#netaddress).  |
1115| callback          | AsyncCallback\<void\>         |  Yes | Callback used to return the result. If the operation fails, an error message is returned.|
1116
1117**Error codes**
1118
1119| ID| Error Message                |
1120| ------- | ----------------------- |
1121| 401     | Parameter error.        |
1122| 201     | Permission denied.      |
1123| 2301088 | Not a socket.           |
1124| 2301098 | Address in use.         |
1125
1126**Example**
1127
1128```ts
1129import { socket } from '@kit.NetworkKit';
1130
1131let multicast: socket.MulticastSocket = socket.constructMulticastSocketInstance();
1132let addr: socket.NetAddress = {
1133  address: '239.255.0.1',
1134  port: 8080
1135}
1136multicast.dropMembership(addr, (err: Object) => {
1137  if (err) {
1138    console.log('drop membership fail, err: ' + JSON.stringify(err));
1139    return;
1140  }
1141  console.log('drop membership success');
1142})
1143```
1144
1145### dropMembership<sup>11+</sup>
1146
1147dropMembership(multicastAddress: NetAddress): Promise\<void\>
1148
1149Drops a member from a multicast group. This API uses a promise to return the result.
1150
1151> **NOTE**
1152> The IP addresses used for multicast belong to a specific range, for example, 224.0.0.0 to 239.255.255.255.
1153> You can drop only a member that has been added to a multicast group by using [addMembership](#addmembership11).
1154
1155**Required permissions**: ohos.permission.INTERNET
1156
1157**System capability**: SystemCapability.Communication.NetStack
1158
1159**Parameters**
1160
1161| Name            | Type                                  | Mandatory| Description                                          |
1162| ----------------- | ------------------------------------- | ---- | --------------------------------------------  |
1163| multicastAddress  | [NetAddress](#netaddress) |  Yes | Destination address. For details, see [NetAddress](#netaddress).    |
1164
1165**Return value**
1166
1167| Type           | Description                                             |
1168|  -------------- |  ----------------------------------------------- |
1169| Promise\<void\> | Promise used to return the result.|
1170
1171**Error codes**
1172
1173| ID| Error Message                |
1174| ------- | ----------------------- |
1175| 401     | Parameter error.        |
1176| 201     | Permission denied.      |
1177| 2301088 | Not a socket.           |
1178| 2301098 | Address in use.         |
1179
1180**Example**
1181
1182```ts
1183import { socket } from '@kit.NetworkKit';
1184
1185let multicast: socket.MulticastSocket = socket.constructMulticastSocketInstance();
1186let addr: socket.NetAddress = {
1187  address: '239.255.0.1',
1188  port: 8080
1189}
1190multicast.dropMembership(addr).then(() => {
1191  console.log('drop membership success');
1192}).catch((err: Object) => {
1193  console.log('drop membership fail');
1194});
1195```
1196
1197### setMulticastTTL<sup>11+</sup>
1198
1199setMulticastTTL(ttl: number, callback: AsyncCallback\<void\>): void
1200
1201Sets the time to live (TTL) for multicast packets. This API uses an asynchronous callback to return the result.
1202
1203> **NOTE**
1204> TTL is used to limit the maximum number of router hops for packet transmission on a network.
1205> The value ranges from 0 to 255. The default value is **1**.
1206> If the TTL value is **1**, multicast packets can be transmitted only to the host directly connected to the sender. If the TTL is set to a large value, multicast packets can be transmitted over a longer distance.
1207> This API is effective only after [addMembership](#addmembership11) is called.
1208
1209**System capability**: SystemCapability.Communication.NetStack
1210
1211**Parameters**
1212
1213| Name        | Type                  | Mandatory| Description                        |
1214| ------------- | --------------------- | ---- | ----------------------------- |
1215| ttl           | number                |  Yes | TTL value. The value is of the number type.|
1216| callback      | AsyncCallback\<void\> |  Yes | Callback used to return the result. If the operation fails, an error message is returned.   |
1217
1218**Error codes**
1219
1220| ID| Error Message                |
1221| ------- | ----------------------- |
1222| 401     | Parameter error.        |
1223| 2301022 | Invalid argument.       |
1224| 2301088 | Not a socket.           |
1225
1226**Example**
1227
1228```ts
1229import { socket } from '@kit.NetworkKit';
1230
1231let multicast: socket.MulticastSocket = socket.constructMulticastSocketInstance();
1232let ttl = 8
1233multicast.setMulticastTTL(ttl, (err: Object) => {
1234  if (err) {
1235    console.log('set ttl fail, err: ' + JSON.stringify(err));
1236    return;
1237  }
1238  console.log('set ttl success');
1239})
1240```
1241
1242### setMulticastTTL<sup>11+</sup>
1243
1244setMulticastTTL(ttl: number): Promise\<void\>
1245
1246Sets the time to live (TTL) for multicast packets. This API uses a promise to return the result.
1247
1248> **NOTE**
1249> TTL is used to limit the maximum number of router hops for packet transmission on a network.
1250> The value ranges from 0 to 255. The default value is **1**.
1251> If the TTL value is **1**, multicast packets can be transmitted only to the host directly connected to the sender. If the TTL is set to a large value, multicast packets can be transmitted over a longer distance.
1252> This API is effective only after [addMembership](#addmembership11) is called.
1253
1254**System capability**: SystemCapability.Communication.NetStack
1255
1256**Parameters**
1257
1258| Name        | Type                  | Mandatory| Description                          |
1259| ------------- | ---------------------- | ---- | ------------------------------ |
1260| ttl           | number                 |  Yes | TTL value. The value is of the number type.|
1261
1262**Return value**
1263
1264| Type           | Description                                            |
1265|  -------------- |  ---------------------------------------------- |
1266| Promise\<void\> | Promise used to return the result.|
1267
1268**Error codes**
1269
1270| ID| Error Message                |
1271| ------- | ----------------------- |
1272| 401     | Parameter error.        |
1273| 2301022 | Invalid argument.       |
1274| 2301088 | Not a socket.           |
1275
1276**Example**
1277
1278```ts
1279import { socket } from '@kit.NetworkKit';
1280
1281let multicast: socket.MulticastSocket = socket.constructMulticastSocketInstance();
1282multicast.setMulticastTTL(8).then(() => {
1283  console.log('set ttl success');
1284}).catch((err: Object) => {
1285  console.log('set ttl failed');
1286});
1287```
1288
1289### getMulticastTTL<sup>11+</sup>
1290
1291getMulticastTTL(callback: AsyncCallback\<number\>): void
1292
1293Obtains the TTL for multicast packets. This API uses an asynchronous callback to return the result.
1294
1295> **NOTE**
1296> TTL is used to limit the maximum number of router hops for packet transmission on a network.
1297> The value ranges from 0 to 255. The default value is **1**.
1298> If the TTL value is **1**, multicast packets can be transmitted only to the host directly connected to the sender. If the TTL is set to a large value, multicast packets can be transmitted over a longer distance.
1299> This API is effective only after [addMembership](#addmembership11) is called.
1300
1301**System capability**: SystemCapability.Communication.NetStack
1302
1303**Parameters**
1304
1305| Name        | Type                    | Mandatory| Description                        |
1306| ------------- | ----------------------- | ---- | --------------------------- |
1307| callback      | AsyncCallback\<number\> |  Yes | Callback used to return the result. If the operation fails, an error message is returned. |
1308
1309**Error codes**
1310
1311| ID| Error Message                |
1312| ------- | ----------------------- |
1313| 401     | Parameter error.        |
1314| 2301088 | Not a socket.           |
1315
1316**Example**
1317
1318```ts
1319import { socket } from '@kit.NetworkKit';
1320
1321let multicast: socket.MulticastSocket = socket.constructMulticastSocketInstance();
1322multicast.getMulticastTTL((err: Object, value: Number) => {
1323  if (err) {
1324    console.log('set ttl fail, err: ' + JSON.stringify(err));
1325    return;
1326  }
1327  console.log('set ttl success, value: ' + JSON.stringify(value));
1328})
1329```
1330
1331### getMulticastTTL<sup>11+</sup>
1332
1333getMulticastTTL(): Promise\<number\>
1334
1335Obtains the TTL for multicast packets. This API uses a promise to return the result.
1336
1337> **NOTE**
1338> TTL is used to limit the maximum number of router hops for packet transmission on a network.
1339> The value ranges from 0 to 255. The default value is **1**.
1340> If the TTL value is **1**, multicast packets can be transmitted only to the host directly connected to the sender. If the TTL is set to a large value, multicast packets can be transmitted over a longer distance.
1341> This API is effective only after [addMembership](#addmembership11) is called.
1342
1343**System capability**: SystemCapability.Communication.NetStack
1344
1345**Return value**
1346
1347| Type              | Description                       |
1348| ----------------   | --------------------------- |
1349| Promise\<number\> | Promise used to return the result.|
1350
1351**Error codes**
1352
1353| ID| Error Message               |
1354| ------- | ----------------------- |
1355| 401     | Parameter error.        |
1356| 2301088 | Not a socket.           |
1357
1358**Example**
1359
1360```ts
1361import { socket } from '@kit.NetworkKit';
1362
1363let multicast: socket.MulticastSocket = socket.constructMulticastSocketInstance();
1364multicast.getMulticastTTL().then((value: Number) => {
1365  console.log('ttl: ', JSON.stringify(value));
1366}).catch((err: Object) => {
1367  console.log('set ttl failed');
1368});
1369```
1370
1371### setLoopbackMode<sup>11+</sup>
1372
1373setLoopbackMode(flag: boolean, callback: AsyncCallback\<void\>): void
1374
1375Sets the loopback mode flag for multicast communication. This API uses an asynchronous callback to return the result.
1376
1377> **NOTE**
1378> Use this API to enable or disable the loopback mode. By default, the loopback mode is enabled.
1379> The value **true** indicates that the host is allowed to receive the multicast packets sent by itself, and the value **false** indicates the opposite.
1380> This API is effective only after [addMembership](#addmembership11) is called.
1381
1382**System capability**: SystemCapability.Communication.NetStack
1383
1384**Parameters**
1385
1386| Name        | Type                 | Mandatory| Description                        |
1387| ------------- | --------------------- | ---- | ---------------------------- |
1388| flag          | boolean               |  Yes | Loopback mode flag. The value is of the Boolean type. |
1389| callback      | AsyncCallback\<void\> |  Yes | Callback used to return the result. If the operation fails, an error message is returned.   |
1390
1391**Error codes**
1392
1393| ID| Error Message                |
1394| ------- | ----------------------- |
1395| 401     | Parameter error.        |
1396| 2301088 | Not a socket.           |
1397
1398**Example**
1399
1400```ts
1401import { socket } from '@kit.NetworkKit';
1402
1403let multicast: socket.MulticastSocket = socket.constructMulticastSocketInstance();
1404multicast.setLoopbackMode(false, (err: Object) => {
1405  if (err) {
1406    console.log('set loopback mode fail, err: ' + JSON.stringify(err));
1407    return;
1408  }
1409  console.log('set loopback mode success');
1410})
1411```
1412
1413### setLoopbackMode<sup>11+</sup>
1414
1415setLoopbackMode(flag: boolean): Promise\<void\>
1416
1417Sets the loopback mode flag for multicast communication. This API uses an asynchronous callback to return the result.
1418
1419> **NOTE**
1420> Use this API to enable or disable the loopback mode. By default, the loopback mode is enabled.
1421> The value **true** indicates that the host is allowed to receive the multicast packets sent by itself, and the value **false** indicates the opposite.
1422> This API is effective only after [addMembership](#addmembership11) is called.
1423
1424**System capability**: SystemCapability.Communication.NetStack
1425
1426**Parameters**
1427
1428| Name        | Type                  | Mandatory| Description                            |
1429| ------------- | ---------------------- | ---- | -------------------------------- |
1430| flag          | boolean                |  Yes | Loopback mode flag. The value is of the Boolean type.|
1431
1432**Return value**
1433
1434| Type           | Description                                            |
1435|  -------------- |  ---------------------------------------------- |
1436| Promise\<void\> | Promise used to return the result.|
1437
1438**Error codes**
1439
1440| ID| Error Message               |
1441| ------- | ----------------------- |
1442| 401     | Parameter error.        |
1443| 2301088 | Not a socket.           |
1444
1445**Example**
1446
1447```ts
1448import { socket } from '@kit.NetworkKit';
1449
1450let multicast: socket.MulticastSocket = socket.constructMulticastSocketInstance();
1451multicast.setLoopbackMode(false).then(() => {
1452  console.log('set loopback mode success');
1453}).catch((err: Object) => {
1454  console.log('set loopback mode failed');
1455});
1456```
1457
1458### getLoopbackMode<sup>11+</sup>
1459
1460getLoopbackMode(callback: AsyncCallback\<boolean\>): void
1461
1462Obtains the loopback mode flag for multicast communication. This API uses a promise to return the result.
1463
1464> **NOTE**
1465> Use this API to check whether the loopback mode is enabled.
1466> The value **true** indicates that the loopback mode is enabled, and the value **false** indicates the opposite. When the loopback mode is disabled, the host does not receive the multicast packets sent by itself.
1467> This API is effective only after [addMembership](#addmembership11) is called.
1468
1469**System capability**: SystemCapability.Communication.NetStack
1470
1471**Parameters**
1472
1473| Name        | Type                    | Mandatory| Description                        |
1474| ------------- | ----------------------- | ---- | --------------------------- |
1475| callback      | AsyncCallback\<number\> |  Yes | Callback used to return the result. If the operation fails, an error message is returned. |
1476
1477**Error codes**
1478
1479| ID| Error Message               |
1480| ------- | ----------------------- |
1481| 401     | Parameter error.        |
1482| 2301088 | Not a socket.           |
1483
1484**Example**
1485
1486```ts
1487import { socket } from '@kit.NetworkKit';
1488
1489let multicast: socket.MulticastSocket = socket.constructMulticastSocketInstance();
1490multicast.getLoopbackMode((err: Object, value: Boolean) => {
1491  if (err) {
1492    console.log('get loopback mode fail, err: ' + JSON.stringify(err));
1493    return;
1494  }
1495  console.log('get loopback mode success, value: ' + JSON.stringify(value));
1496})
1497```
1498
1499### getLoopbackMode<sup>11+</sup>
1500
1501getLoopbackMode(): Promise\<boolean\>
1502
1503Obtains the loopback mode flag for multicast communication. This API uses a promise to return the result.
1504
1505> **NOTE**
1506> Use this API to check whether the loopback mode is enabled.
1507> The value **true** indicates that the loopback mode is enabled, and the value **false** indicates the opposite. When the loopback mode is disabled, the host does not receive the multicast packets sent by itself.
1508> This API is effective only after [addMembership](#addmembership11) is called.
1509
1510**System capability**: SystemCapability.Communication.NetStack
1511
1512**Return value**
1513
1514| Type               | Description                       |
1515| ----------------  | --------------------------- |
1516| Promise\<boolean\> | Promise used to return the result.|
1517
1518**Error codes**
1519
1520| ID| Error Message               |
1521| ------- | ----------------------- |
1522| 401     | Parameter error.        |
1523| 2301088 | Not a socket.           |
1524
1525**Example**
1526
1527```ts
1528import { socket } from '@kit.NetworkKit';
1529
1530let multicast: socket.MulticastSocket = socket.constructMulticastSocketInstance();
1531multicast.getLoopbackMode().then((value: Boolean) => {
1532  console.log('loopback mode: ', JSON.stringify(value));
1533}).catch((err: Object) => {
1534  console.log('get loopback mode failed');
1535});
1536```
1537
1538## socket.constructTCPSocketInstance<sup>7+</sup>
1539
1540constructTCPSocketInstance(): TCPSocket
1541
1542Creates a **TCPSocket** object.
1543
1544**System capability**: SystemCapability.Communication.NetStack
1545
1546**Return value**
1547
1548| Type                              | Description                   |
1549| --------------------------------- | ---------------------- |
1550| [TCPSocket](#tcpsocket) | **TCPSocket** object.|
1551
1552**Example**
1553
1554```ts
1555import { socket } from '@kit.NetworkKit';
1556let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
1557```
1558
1559## TCPSocket
1560
1561Defines a TCP socket connection. Before calling TCPSocket APIs, you need to call [socket.constructTCPSocketInstance](#socketconstructtcpsocketinstance7) to create a **TCPSocket** object.
1562
1563### bind
1564
1565bind(address: NetAddress, callback: AsyncCallback\<void\>): void
1566
1567Binds an IP address and a port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result.
1568
1569> **NOTE**
1570> If the bind operation fails due to a port conflict, the system will randomly allocate a port number.
1571> The TCP client can call **tcp.bind** to explicitly bind the IP address and port number, and then call **tcp.connect** to connect to the server. Alternatively, the TCP client can directly call **tcp.connect** to automatically bind the IP address and port number to connect to the server.
1572> If the IP address is **localhost** or **127.0.0.1**, only local loopback access is allowed; that is, the TCP client and the server are deployed on the same device.
1573
1574**Required permissions**: ohos.permission.INTERNET
1575
1576**System capability**: SystemCapability.Communication.NetStack
1577
1578**Parameters**
1579
1580| Name  | Type                              | Mandatory| Description                                                  |
1581| -------- | ---------------------------------- | ---- | ------------------------------------------------------ |
1582| address  | [NetAddress](#netaddress) | Yes  | Destination address. For details, see [NetAddress](#netaddress).|
1583| callback | AsyncCallback\<void\>              | Yes  | Callback used to return the result. If the operation fails, an error message is returned.                  |
1584
1585**Error codes**
1586
1587| ID| Error Message                |
1588| ------- | ----------------------- |
1589| 401     | Parameter error.        |
1590| 201     | Permission denied.      |
1591
1592**Example**
1593
1594```ts
1595import { socket } from '@kit.NetworkKit';
1596import { BusinessError } from '@kit.BasicServicesKit';
1597
1598let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
1599let bindAddr: socket.NetAddress = {
1600  address: '192.168.xx.xxx',
1601  port: 8080
1602}
1603tcp.bind(bindAddr, (err: BusinessError) => {
1604  if (err) {
1605    console.log('bind fail');
1606    return;
1607  }
1608  console.log('bind success');
1609})
1610```
1611
1612### bind
1613
1614bind(address: NetAddress): Promise\<void\>
1615
1616Binds an IP address and a port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result.
1617
1618> **NOTE**
1619> If the bind operation fails due to a port conflict, the system will randomly allocate a port number.
1620> The TCP client can call **tcp.bind** to explicitly bind the IP address and port number, and then call **tcp.connect** to connect to the server. Alternatively, the TCP client can directly call **tcp.connect** to automatically bind the IP address and port number to connect to the server.
1621> If the IP address is **localhost** or **127.0.0.1**, only local loopback access is allowed; that is, the TCP client and the server are deployed on the same device.
1622
1623**Required permissions**: ohos.permission.INTERNET
1624
1625**System capability**: SystemCapability.Communication.NetStack
1626
1627**Parameters**
1628
1629| Name | Type                              | Mandatory| Description                                                  |
1630| ------- | ---------------------------------- | ---- | ------------------------------------------------------ |
1631| address | [NetAddress](#netaddress) | Yes  | Destination address. For details, see [NetAddress](#netaddress).|
1632
1633**Return value**
1634
1635| Type           | Description                                                    |
1636| --------------- | ------------------------------------------------------- |
1637| Promise\<void\> | Promise used to return the result.|
1638
1639**Error codes**
1640
1641| ID| Error Message                |
1642| ------- | ----------------------- |
1643| 401     | Parameter error.        |
1644| 201     | Permission denied.      |
1645
1646**Example**
1647
1648```ts
1649import { socket } from '@kit.NetworkKit';
1650import { BusinessError } from '@kit.BasicServicesKit';
1651
1652let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
1653let bindAddr: socket.NetAddress = {
1654  address: '192.168.xx.xxx',
1655  port: 8080
1656}
1657tcp.bind(bindAddr).then(() => {
1658  console.log('bind success');
1659}).catch((err: BusinessError) => {
1660  console.log('bind fail');
1661});
1662```
1663
1664### connect
1665
1666connect(options: TCPConnectOptions, callback: AsyncCallback\<void\>): void
1667
1668Sets up a connection to the specified IP address and port number. This API uses an asynchronous callback to return the result.
1669
1670> **NOTE**
1671> This API allows you to connect to the TCP server without first executing **tcp.bind**.
1672
1673**Required permissions**: ohos.permission.INTERNET
1674
1675**System capability**: SystemCapability.Communication.NetStack
1676
1677**Parameters**
1678
1679| Name  | Type                                    | Mandatory| Description                                                        |
1680| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
1681| options  | [TCPConnectOptions](#tcpconnectoptions) | Yes  | TCP socket connection parameters. For details, see [TCPConnectOptions](#tcpconnectoptions).|
1682| callback | AsyncCallback\<void\>                    | Yes  | Callback used to return the result. If the operation fails, an error message is returned.                     |
1683
1684**Error codes**
1685
1686| ID| Error Message                |
1687| ------- | ----------------------- |
1688| 401     | Parameter error.        |
1689| 201     | Permission denied.      |
1690| 2301206 | Socks5 failed to connect to the proxy server.  |
1691| 2301207 | Socks5 username or password is invalid.        |
1692| 2301208 | Socks5 failed to connect to the remote server. |
1693| 2301209 | Socks5 failed to negotiate the authentication method. |
1694| 2301210 | Socks5 failed to send the message.             |
1695| 2301211 | Socks5 failed to receive the message.          |
1696| 2301212 | Socks5 serialization error.                    |
1697| 2301213 | Socks5 deserialization error.                  |
1698
1699**Example**
1700
1701```ts
1702import { socket } from '@kit.NetworkKit';
1703import { BusinessError } from '@kit.BasicServicesKit';
1704
1705let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
1706let netAddress: socket.NetAddress = {
1707  address: '192.168.xx.xxx',
1708  port: 8080
1709}
1710let tcpconnectoptions: socket.TCPConnectOptions = {
1711  address: netAddress,
1712  timeout: 6000
1713}
1714tcp.connect(tcpconnectoptions, (err: BusinessError) => {
1715  if (err) {
1716    console.log('connect fail');
1717    return;
1718  }
1719  console.log('connect success');
1720})
1721```
1722
1723**Example (with socket proxy):**
1724
1725```ts
1726import { socket } from '@kit.NetworkKit';
1727import { BusinessError } from '@kit.BasicServicesKit';
1728
1729let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
1730let netAddress: socket.NetAddress = {
1731  address: '192.168.xx.xxx',
1732  port: 8080
1733}
1734let socks5Server: socket.NetAddress = {
1735  address: '192.168.xx.xxx',
1736  port: 8080
1737}
1738let tcpconnectoptions: socket.TCPConnectOptions = {
1739  address: netAddress,
1740  timeout: 6000,
1741  proxy: socket.ProxyOptions = {
1742    type : 1,
1743    address: socks5Server,
1744    username: "xxx",
1745    password: "xxx"
1746  }
1747}
1748tcp.connect(tcpconnectoptions, (err: BusinessError) => {
1749  if (err) {
1750    console.log('connect fail');
1751    return;
1752  }
1753  console.log('connect success');
1754})
1755```
1756
1757### connect
1758
1759connect(options: TCPConnectOptions): Promise\<void\>
1760
1761Sets up a connection to the specified IP address and port number. This API uses a promise to return the result.
1762
1763> **NOTE**
1764> This API allows you to connect to the TCP server without first executing **tcp.bind**.
1765
1766**Required permissions**: ohos.permission.INTERNET
1767
1768**System capability**: SystemCapability.Communication.NetStack
1769
1770**Parameters**
1771
1772| Name | Type                                    | Mandatory| Description                                                        |
1773| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
1774| options | [TCPConnectOptions](#tcpconnectoptions) | Yes  | TCP socket connection parameters. For details, see [TCPConnectOptions](#tcpconnectoptions).|
1775
1776**Return value**
1777
1778| Type           | Description                                                      |
1779| -------------- | --------------------------------------------------------- |
1780| Promise\<void\> | Promise used to return the result.|
1781
1782**Error codes**
1783
1784| ID| Error Message                |
1785| ------- | ----------------------- |
1786| 401     | Parameter error.        |
1787| 201     | Permission denied.      |
1788| 2301206 | Socks5 failed to connect to the proxy server.  |
1789| 2301207 | Socks5 username or password is invalid.        |
1790| 2301208 | Socks5 failed to connect to the remote server. |
1791| 2301209 | Socks5 failed to negotiate the authentication method. |
1792| 2301210 | Socks5 failed to send the message.             |
1793| 2301211 | Socks5 failed to receive the message.          |
1794| 2301212 | Socks5 serialization error.                    |
1795| 2301213 | Socks5 deserialization error.                  |
1796
1797**Example**
1798
1799```ts
1800import { socket } from '@kit.NetworkKit';
1801import { BusinessError } from '@kit.BasicServicesKit';
1802
1803let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
1804let netAddress: socket.NetAddress = {
1805  address: '192.168.xx.xxx',
1806  port: 8080
1807}
1808let tcpconnectoptions: socket.TCPConnectOptions = {
1809  address: netAddress,
1810  timeout: 6000
1811}
1812tcp.connect(tcpconnectoptions).then(() => {
1813  console.log('connect success')
1814}).catch((err: BusinessError) => {
1815  console.log('connect fail');
1816});
1817```
1818
1819**Example (with socket proxy):**
1820
1821```ts
1822import { socket } from '@kit.NetworkKit';
1823import { BusinessError } from '@kit.BasicServicesKit';
1824
1825let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
1826let netAddress: socket.NetAddress = {
1827  address: '192.168.xx.xxx',
1828  port: 8080
1829}
1830let socks5Server: socket.NetAddress = {
1831  address: '192.168.xx.xxx',
1832  port: 8080
1833}
1834let tcpconnectoptions: socket.TCPConnectOptions = {
1835  address: netAddress,
1836  timeout: 6000,
1837  proxy: socket.ProxyOptions = {
1838    type : 1,
1839    address: socks5Server,
1840    username: "xxx",
1841    password: "xxx"
1842  }
1843}
1844tcp.connect(tcpconnectoptions).then(() => {
1845  console.log('connect success')
1846}).catch((err: BusinessError) => {
1847  console.log('connect fail');
1848});
1849```
1850
1851### send
1852
1853send(options: TCPSendOptions, callback: AsyncCallback\<void\>): void
1854
1855Sends data over a TCP socket connection. This API uses an asynchronous callback to return the result.
1856
1857> **NOTE**
1858> This API can be called only after **connect** is successfully called. Call the API in the worker thread or taskpool thread as this operation is time-consuming.
1859
1860**Required permissions**: ohos.permission.INTERNET
1861
1862**System capability**: SystemCapability.Communication.NetStack
1863
1864**Parameters**
1865
1866| Name  | Type                                   | Mandatory| Description                                                        |
1867| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
1868| options  | [TCPSendOptions](#tcpsendoptions) | Yes  | Parameters for sending data over a TCP socket connection. For details, see [TCPSendOptions](#tcpsendoptions).|
1869| callback | AsyncCallback\<void\>                   | Yes  | Callback used to return the result. If the operation fails, an error message is returned.                          |
1870
1871**Error codes**
1872
1873| ID| Error Message                |
1874| ------- | ----------------------- |
1875| 401     | Parameter error.        |
1876| 201     | Permission denied.      |
1877
1878**Example**
1879
1880```ts
1881import { socket } from '@kit.NetworkKit';
1882import { BusinessError } from '@kit.BasicServicesKit';
1883
1884let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
1885let netAddress: socket.NetAddress = {
1886  address: '192.168.xx.xxx',
1887  port: 8080
1888}
1889let tcpconnectoptions: socket.TCPConnectOptions = {
1890  address: netAddress,
1891  timeout: 6000
1892}
1893tcp.connect(tcpconnectoptions, () => {
1894  console.log('connect success');
1895  let tcpSendOptions: socket.TCPSendOptions = {
1896    data: 'Hello, server!'
1897  }
1898  tcp.send(tcpSendOptions, (err: BusinessError) => {
1899    if (err) {
1900      console.log('send fail');
1901      return;
1902    }
1903    console.log('send success');
1904  })
1905})
1906```
1907
1908### send
1909
1910send(options: TCPSendOptions): Promise\<void\>
1911
1912Sends data over a TCP socket connection. This API uses a promise to return the result.
1913
1914> **NOTE**
1915> This API can be called only after **connect** is successfully called. Call the API in the worker thread or taskpool thread as this operation is time-consuming.
1916
1917**Required permissions**: ohos.permission.INTERNET
1918
1919**System capability**: SystemCapability.Communication.NetStack
1920
1921**Parameters**
1922
1923| Name | Type                                   | Mandatory| Description                                                        |
1924| ------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
1925| options | [TCPSendOptions](#tcpsendoptions) | Yes  | Parameters for sending data over a TCP socket connection. For details, see [TCPSendOptions](#tcpsendoptions).|
1926
1927**Return value**
1928
1929| Type           | Description                                              |
1930| -------------- | ------------------------------------------------- |
1931| Promise\<void\> | Promise used to return the result.|
1932
1933**Error codes**
1934
1935| ID| Error Message                |
1936| ------- | ----------------------- |
1937| 401     | Parameter error.        |
1938| 201     | Permission denied.      |
1939
1940**Example**
1941
1942```ts
1943import { socket } from '@kit.NetworkKit';
1944import { BusinessError } from '@kit.BasicServicesKit';
1945
1946let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
1947let netAddress: socket.NetAddress = {
1948  address: '192.168.xx.xxx',
1949  port: 8080
1950}
1951let tcpconnectoptions: socket.TCPConnectOptions = {
1952  address: netAddress,
1953  timeout: 6000
1954}
1955tcp.connect(tcpconnectoptions, () => {
1956  console.log('connect success');
1957  let tcpSendOptions: socket.TCPSendOptions = {
1958    data: 'Hello, server!'
1959  }
1960  tcp.send(tcpSendOptions).then(() => {
1961    console.log('send success');
1962  }).catch((err: BusinessError) => {
1963    console.log('send fail');
1964  });
1965})
1966```
1967
1968### close
1969
1970close(callback: AsyncCallback\<void\>): void
1971
1972Closes a TCP socket connection. This API uses an asynchronous callback to return the result.
1973
1974**Required permissions**: ohos.permission.INTERNET
1975
1976**System capability**: SystemCapability.Communication.NetStack
1977
1978**Parameters**
1979
1980| Name  | Type                 | Mandatory| Description      |
1981| -------- | --------------------- | ---- | ---------- |
1982| callback | AsyncCallback\<void\> | Yes  | Callback used to return the result. If the operation fails, an error message is returned.|
1983
1984**Error codes**
1985
1986| ID| Error Message                |
1987| ------- | ----------------------- |
1988| 201     | Permission denied.      |
1989
1990**Example**
1991
1992```ts
1993import { socket } from '@kit.NetworkKit';
1994import { BusinessError } from '@kit.BasicServicesKit';
1995
1996let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
1997
1998tcp.close((err: BusinessError) => {
1999  if (err) {
2000    console.log('close fail');
2001    return;
2002  }
2003  console.log('close success');
2004})
2005```
2006
2007### close
2008
2009close(): Promise\<void\>
2010
2011Closes a TCP socket connection. This API uses a promise to return the result.
2012
2013**Required permissions**: ohos.permission.INTERNET
2014
2015**System capability**: SystemCapability.Communication.NetStack
2016
2017**Return value**
2018
2019| Type           | Description                                      |
2020| -------------- | ----------------------------------------- |
2021| Promise\<void\> | Promise used to return the result.|
2022
2023**Error codes**
2024
2025| ID| Error Message                |
2026| ------- | ----------------------- |
2027| 201     | Permission denied.      |
2028
2029**Example**
2030
2031```ts
2032import { socket } from '@kit.NetworkKit';
2033
2034let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
2035
2036tcp.close().then(() => {
2037  console.log('close success');
2038}).catch((err: BusinessError) => {
2039  console.log('close fail');
2040});
2041```
2042
2043### getRemoteAddress
2044
2045getRemoteAddress(callback: AsyncCallback\<NetAddress\>): void
2046
2047Obtains the remote address of a socket connection. This API uses an asynchronous callback to return the result.
2048
2049> **NOTE**
2050> This API can be called only after **connect** is successfully called.
2051
2052**Required permissions**: ohos.permission.INTERNET
2053
2054**System capability**: SystemCapability.Communication.NetStack
2055
2056**Parameters**
2057
2058| Name  | Type                                             | Mandatory| Description      |
2059| -------- | ------------------------------------------------- | ---- | ---------- |
2060| callback | AsyncCallback\<[NetAddress](#netaddress)\> | Yes  | Callback used to return the result. If the operation is successful, the remote address is returned. If the operation fails, an error message is returned.|
2061
2062**Error codes**
2063
2064| ID| Error Message                |
2065| ------- | ----------------------- |
2066| 201     | Permission denied.      |
2067
2068**Example**
2069
2070```ts
2071import { socket } from '@kit.NetworkKit';
2072import { BusinessError } from '@kit.BasicServicesKit';
2073
2074let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
2075let netAddress: socket.NetAddress = {
2076  address: '192.168.xx.xxx',
2077  port: 8080
2078}
2079let tcpconnectoptions: socket.TCPConnectOptions = {
2080  address: netAddress,
2081  timeout: 6000
2082}
2083tcp.connect(tcpconnectoptions, () => {
2084  console.log('connect success');
2085  tcp.getRemoteAddress((err: BusinessError, data: socket.NetAddress) => {
2086    if (err) {
2087      console.log('getRemoteAddressfail');
2088      return;
2089    }
2090    console.log('getRemoteAddresssuccess:' + JSON.stringify(data));
2091  })
2092});
2093```
2094
2095### getRemoteAddress
2096
2097getRemoteAddress(): Promise\<NetAddress\>
2098
2099Obtains the remote address of a socket connection. This API uses a promise to return the result.
2100
2101> **NOTE**
2102> This API can be called only after **connect** is successfully called.
2103
2104**Required permissions**: ohos.permission.INTERNET
2105
2106**System capability**: SystemCapability.Communication.NetStack
2107
2108**Return value**
2109
2110| Type                                       | Description                                       |
2111| ------------------------------------------ | ------------------------------------------ |
2112| Promise\<[NetAddress](#netaddress)\> | Promise used to return the result.|
2113
2114**Error codes**
2115
2116| ID| Error Message                |
2117| ------- | ----------------------- |
2118| 201     | Permission denied.      |
2119
2120**Example**
2121
2122```ts
2123import { socket } from '@kit.NetworkKit';
2124import { BusinessError } from '@kit.BasicServicesKit';
2125
2126let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
2127let netAddress: socket.NetAddress = {
2128  address: '192.168.xx.xxx',
2129  port: 8080
2130}
2131let tcpconnectoptions: socket.TCPConnectOptions = {
2132  address: netAddress,
2133  timeout: 6000
2134}
2135tcp.connect(tcpconnectoptions).then(() => {
2136  console.log('connect success');
2137  tcp.getRemoteAddress().then(() => {
2138    console.log('getRemoteAddress success');
2139  }).catch((err: BusinessError) => {
2140    console.log('getRemoteAddressfail');
2141  });
2142}).catch((err: BusinessError) => {
2143  console.log('connect fail');
2144});
2145```
2146
2147### getState
2148
2149getState(callback: AsyncCallback\<SocketStateBase\>): void
2150
2151Obtains the status of the TCP socket connection. This API uses an asynchronous callback to return the result.
2152
2153> **NOTE**
2154> This API can be called only after **bind** or **connect** is successfully called.
2155
2156**Required permissions**: ohos.permission.INTERNET
2157
2158**System capability**: SystemCapability.Communication.NetStack
2159
2160**Parameters**
2161
2162| Name  | Type                                                  | Mandatory| Description      |
2163| -------- | ------------------------------------------------------ | ---- | ---------- |
2164| callback | AsyncCallback\<[SocketStateBase](#socketstatebase)\> | Yes  | Callback used to return the result. If the operation is successful, the status of the TCP socket is returned. If the operation fails, an error message is returned.|
2165
2166**Error codes**
2167
2168| ID| Error Message                |
2169| ------- | ----------------------- |
2170| 201     | Permission denied.      |
2171
2172**Example**
2173
2174```ts
2175import { socket } from '@kit.NetworkKit';
2176import { BusinessError } from '@kit.BasicServicesKit';
2177
2178let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
2179let netAddress: socket.NetAddress = {
2180  address: '192.168.xx.xxx',
2181  port: 8080
2182}
2183let tcpconnectoptions: socket.TCPConnectOptions = {
2184  address: netAddress,
2185  timeout: 6000
2186}
2187tcp.connect(tcpconnectoptions, () => {
2188  console.log('connect success');
2189  tcp.getState((err: BusinessError, data: socket.SocketStateBase) => {
2190    if (err) {
2191      console.log('getState fail');
2192      return;
2193    }
2194    console.log('getState success:' + JSON.stringify(data));
2195  });
2196});
2197```
2198
2199### getState
2200
2201getState(): Promise\<SocketStateBase\>
2202
2203Obtains the status of the TCP socket connection. This API uses a promise to return the result.
2204
2205> **NOTE**
2206> This API can be called only after **bind** or **connect** is successfully called.
2207
2208**Required permissions**: ohos.permission.INTERNET
2209
2210**System capability**: SystemCapability.Communication.NetStack
2211
2212**Return value**
2213
2214| Type                                            | Description                                      |
2215| ----------------------------------------------- | ----------------------------------------- |
2216| Promise\<[SocketStateBase](#socketstatebase)\> | Promise used to return the result.|
2217
2218**Error codes**
2219
2220| ID| Error Message                |
2221| ------- | ----------------------- |
2222| 201     | Permission denied.      |
2223
2224**Example**
2225
2226```ts
2227import { socket } from '@kit.NetworkKit';
2228import { BusinessError } from '@kit.BasicServicesKit';
2229
2230let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
2231let netAddress: socket.NetAddress = {
2232  address: '192.168.xx.xxx',
2233  port: 8080
2234}
2235let tcpconnectoptions: socket.TCPConnectOptions = {
2236  address: netAddress,
2237  timeout: 6000
2238}
2239tcp.connect(tcpconnectoptions).then(() => {
2240  console.log('connect success');
2241  tcp.getState().then(() => {
2242    console.log('getState success');
2243  }).catch((err: BusinessError) => {
2244    console.log('getState fail');
2245  });
2246}).catch((err: BusinessError) => {
2247  console.log('connect fail');
2248});
2249```
2250
2251### getSocketFd<sup>10+</sup>
2252
2253getSocketFd(callback: AsyncCallback\<number\>): void
2254
2255Obtains the file descriptor of the **TCPSocket** object. This API uses an asynchronous callback to return the result.
2256
2257> **NOTE**
2258> This API can be called only after **bind** or **connect** is successfully called.
2259
2260**System capability**: SystemCapability.Communication.NetStack
2261
2262**Parameters**
2263
2264| Name  | Type                                                  | Mandatory| Description      |
2265| -------- | ------------------------------------------------------ | ---- | ---------- |
2266| callback | AsyncCallback\<number\> | Yes  | Callback used to return the result. If the operation is successful, the file descriptor of the socket is returned. Otherwise, **undefined** is returned.|
2267
2268**Example**
2269
2270```ts
2271import { socket } from '@kit.NetworkKit';
2272import { BusinessError } from '@kit.BasicServicesKit';
2273
2274let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
2275let bindAddr: socket.NetAddress = {
2276  address: '0.0.0.0'
2277}
2278tcp.bind(bindAddr)
2279let netAddress: socket.NetAddress = {
2280  address: '192.168.xx.xxx',
2281  port: 8080
2282}
2283let tcpconnectoptions: socket.TCPConnectOptions = {
2284  address: netAddress,
2285  timeout: 6000
2286}
2287tcp.connect(tcpconnectoptions)
2288tcp.getSocketFd((err: BusinessError, data: number) => {
2289  console.info("getSocketFd failed: " + err);
2290  console.info("tunenlfd: " + data);
2291})
2292```
2293### getSocketFd<sup>10+</sup>
2294
2295getSocketFd(): Promise\<number\>
2296
2297Obtains the file descriptor of the **TCPSocket** object. This API uses a promise to return the result.
2298
2299> **NOTE**
2300> This API can be called only after **bind** or **connect** is successfully called.
2301
2302**System capability**: SystemCapability.Communication.NetStack
2303
2304**Return value**
2305
2306| Type                                            | Description                                      |
2307| ----------------------------------------------- | ----------------------------------------- |
2308| Promise\<number\> | Promise used to return the result.|
2309
2310**Example**
2311
2312```ts
2313import { socket } from '@kit.NetworkKit';
2314import { BusinessError } from '@kit.BasicServicesKit';
2315
2316let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
2317let bindAddr: socket.NetAddress = {
2318  address: '0.0.0.0'
2319}
2320tcp.bind(bindAddr)
2321let netAddress: socket.NetAddress = {
2322  address: '192.168.xx.xxx',
2323  port: 8080
2324}
2325let tcpconnectoptions: socket.TCPConnectOptions = {
2326  address: netAddress,
2327  timeout: 6000
2328}
2329tcp.connect(tcpconnectoptions)
2330tcp.getSocketFd().then((data: number) => {
2331  console.info("tunenlfd: " + data);
2332})
2333```
2334
2335### setExtraOptions
2336
2337setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\<void\>): void
2338
2339Sets other properties of the TCP socket connection. This API uses an asynchronous callback to return the result.
2340
2341> **NOTE**
2342> This API can be called only after **bind** or **connect** is successfully called.
2343
2344**Required permissions**: ohos.permission.INTERNET
2345
2346**System capability**: SystemCapability.Communication.NetStack
2347
2348**Parameters**
2349
2350| Name  | Type                                     | Mandatory| Description                                                        |
2351| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
2352| options  | [TCPExtraOptions](#tcpextraoptions) | Yes  | Other properties of the TCP socket connection. For details, see [TCPExtraOptions](#tcpextraoptions).|
2353| callback | AsyncCallback\<void\>                     | Yes  | Callback used to return the result. If the operation fails, an error message is returned.              |
2354
2355**Error codes**
2356
2357| ID| Error Message                |
2358| ------- | ----------------------- |
2359| 401     | Parameter error.        |
2360| 201     | Permission denied.      |
2361
2362**Example**
2363
2364```ts
2365import { socket } from '@kit.NetworkKit';
2366import { BusinessError } from '@kit.BasicServicesKit';
2367
2368let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
2369let netAddress: socket.NetAddress = {
2370  address: '192.168.xx.xxx',
2371  port: 8080
2372}
2373let tcpconnectoptions: socket.TCPConnectOptions = {
2374  address: netAddress,
2375  timeout: 6000
2376}
2377
2378interface SocketLinger {
2379  on: boolean;
2380  linger: number;
2381}
2382
2383tcp.connect(tcpconnectoptions, () => {
2384  console.log('connect success');
2385  let tcpExtraOptions: socket.TCPExtraOptions = {
2386    keepAlive: true,
2387    OOBInline: true,
2388    TCPNoDelay: true,
2389    socketLinger: { on: true, linger: 10 } as SocketLinger,
2390    receiveBufferSize: 1000,
2391    sendBufferSize: 1000,
2392    reuseAddress: true,
2393    socketTimeout: 3000
2394  }
2395  tcp.setExtraOptions(tcpExtraOptions, (err: BusinessError) => {
2396    if (err) {
2397      console.log('setExtraOptions fail');
2398      return;
2399    }
2400    console.log('setExtraOptions success');
2401  });
2402});
2403```
2404
2405### setExtraOptions
2406
2407setExtraOptions(options: TCPExtraOptions): Promise\<void\>
2408
2409Sets other properties of the TCP socket connection. This API uses a promise to return the result.
2410
2411> **NOTE**
2412> This API can be called only after **bind** or **connect** is successfully called.
2413
2414**Required permissions**: ohos.permission.INTERNET
2415
2416**System capability**: SystemCapability.Communication.NetStack
2417
2418**Parameters**
2419
2420| Name | Type                                     | Mandatory| Description                                                        |
2421| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
2422| options | [TCPExtraOptions](#tcpextraoptions) | Yes  | Other properties of the TCP socket connection. For details, see [TCPExtraOptions](#tcpextraoptions).|
2423
2424**Return value**
2425
2426| Type           | Description                                                |
2427| -------------- | --------------------------------------------------- |
2428| Promise\<void\> | Promise used to return the result.|
2429
2430**Error codes**
2431
2432| ID| Error Message                |
2433| ------- | ----------------------- |
2434| 401     | Parameter error.        |
2435| 201     | Permission denied.      |
2436
2437**Example**
2438
2439```ts
2440import { socket } from '@kit.NetworkKit';
2441import { BusinessError } from '@kit.BasicServicesKit';
2442
2443let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
2444let netAddress: socket.NetAddress = {
2445  address: '192.168.xx.xxx',
2446  port: 8080
2447}
2448let tcpconnectoptions: socket.TCPConnectOptions = {
2449  address: netAddress,
2450  timeout: 6000
2451}
2452
2453interface SocketLinger {
2454  on: boolean;
2455  linger: number;
2456}
2457
2458tcp.connect(tcpconnectoptions, () => {
2459  console.log('connect success');
2460  let tcpExtraOptions: socket.TCPExtraOptions = {
2461    keepAlive: true,
2462    OOBInline: true,
2463    TCPNoDelay: true,
2464    socketLinger: { on: true, linger: 10 } as SocketLinger,
2465    receiveBufferSize: 1000,
2466    sendBufferSize: 1000,
2467    reuseAddress: true,
2468    socketTimeout: 3000
2469  }
2470  tcp.setExtraOptions(tcpExtraOptions).then(() => {
2471    console.log('setExtraOptions success');
2472  }).catch((err: BusinessError) => {
2473    console.log('setExtraOptions fail');
2474  });
2475});
2476```
2477
2478### getLocalAddress<sup>12+</sup>
2479
2480getLocalAddress(): Promise\<NetAddress\>
2481
2482Obtains the local socket address of a **TCPSocket** connection. This API uses a promise to return the result.
2483
2484> **NOTE**
2485> This API can be called only after **bind** is successfully called.
2486
2487**System capability**: SystemCapability.Communication.NetStack
2488
2489**Return value**
2490
2491| Type           | Description                                                |
2492|  -------------- |  --------------------------------------------------- |
2493| Promise\<[NetAddress](#netaddress)\> | Promise used to return the result.|
2494
2495**Error codes**
2496
2497| ID| Error Message                                   |
2498| -------- | ------------------------------------------- |
2499| 2300002  | System internal error.                      |
2500| 2301009  | Bad file descriptor.                            |
2501| 2303188  | Socket operation on non-socket. |
2502
2503**Example**
2504
2505```ts
2506import { socket } from '@kit.NetworkKit';
2507import { BusinessError } from '@kit.BasicServicesKit';
2508
2509let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
2510let bindAddr: socket.NetAddress = {
2511  address: '192.168.xx.xxx',
2512  family: 1,
2513  port: 8080
2514}
2515tcp.bind(bindAddr).then(() => {
2516  tcp.getLocalAddress().then((localAddress: socket.NetAddress) => {
2517    console.info("SUCCESS! Address:" + JSON.stringify(localAddress));
2518  }).catch((err: BusinessError) => {
2519    console.error("FAILED! Error:" + JSON.stringify(err));
2520  })
2521}).catch((err: BusinessError) => {
2522  console.error('bind fail');
2523});
2524```
2525
2526### on('message')
2527
2528on(type: 'message', callback: Callback<SocketMessageInfo\>): void
2529
2530Subscribes to **message** events of the TCP socket connection. This API uses an asynchronous callback to return the result.
2531
2532**System capability**: SystemCapability.Communication.NetStack
2533
2534**Parameters**
2535
2536| Name  | Type                                                        | Mandatory| Description                                     |
2537| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
2538| type     | string                                                       | Yes  | Event type.<br/> **message**: message receiving event.|
2539| callback | Callback\<[SocketMessageInfo](#socketmessageinfo11)\> | Yes  | Callback used to return the result.                           |
2540
2541**Example**
2542
2543```ts
2544import { socket } from '@kit.NetworkKit';
2545import { BusinessError } from '@kit.BasicServicesKit';
2546
2547let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
2548let messageView = '';
2549tcp.on('message', (value: socket.SocketMessageInfo) => {
2550  for (let i: number = 0; i < value.message.byteLength; i++) {
2551    let uint8Array = new Uint8Array(value.message)
2552    let messages = uint8Array[i]
2553    let message = String.fromCharCode(messages);
2554    messageView += message;
2555  }
2556  console.log('on message message: ' + JSON.stringify(messageView));
2557  console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo));
2558});
2559```
2560
2561### off('message')
2562
2563off(type: 'message', callback?: Callback<SocketMessageInfo\>): void
2564
2565Unsubscribes from **message** events of the TCP socket connection. This API uses an asynchronous callback to return the result.
2566
2567**System capability**: SystemCapability.Communication.NetStack
2568
2569**Parameters**
2570
2571| Name  | Type                                                        | Mandatory| Description                                     |
2572| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
2573| type     | string                                                       | Yes  | Event type.<br/> **message**: message receiving event.|
2574| callback | Callback\<[SocketMessageInfo](#socketmessageinfo11)\> | No  | Callback used to return the result.                              |
2575
2576**Example**
2577
2578```ts
2579import { socket } from '@kit.NetworkKit';
2580import { BusinessError } from '@kit.BasicServicesKit';
2581
2582let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
2583let messageView = '';
2584let callback = (value: socket.SocketMessageInfo) => {
2585  for (let i: number = 0; i < value.message.byteLength; i++) {
2586    let uint8Array = new Uint8Array(value.message)
2587    let messages = uint8Array[i]
2588    let message = String.fromCharCode(messages);
2589    messageView += message;
2590  }
2591  console.log('on message message: ' + JSON.stringify(messageView));
2592  console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo));
2593}
2594tcp.on('message', callback);
2595// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
2596tcp.off('message', callback);
2597tcp.off('message');
2598```
2599
2600### on('connect' | 'close')
2601
2602on(type: 'connect' | 'close', callback: Callback\<void\>): void
2603
2604Subscribes to connection or close events of the TCP socket connection. This API uses an asynchronous callback to return the result.
2605
2606**System capability**: SystemCapability.Communication.NetStack
2607
2608**Parameters**
2609
2610| Name  | Type            | Mandatory| Description                                                        |
2611| -------- | ---------------- | ---- | ------------------------------------------------------------ |
2612| type     | string           | Yes  | Event type.<br>- **connect**: connection event.<br>- **close**: close event.|
2613| callback | Callback\<void\> | Yes  | Callback used to return the result.             |
2614
2615**Example**
2616
2617```ts
2618import { socket } from '@kit.NetworkKit';
2619import { BusinessError } from '@kit.BasicServicesKit';
2620
2621let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
2622tcp.on('connect', () => {
2623  console.log("on connect success")
2624});
2625tcp.on('close', () => {
2626  console.log("on close success")
2627});
2628```
2629
2630### off('connect' | 'close')
2631
2632off(type: 'connect' | 'close', callback?: Callback\<void\>): void
2633
2634Unsubscribes from connection or close events of the TCP socket connection. This API uses an asynchronous callback to return the result.
2635
2636**System capability**: SystemCapability.Communication.NetStack
2637
2638**Parameters**
2639
2640| Name  | Type            | Mandatory| Description                                                        |
2641| -------- | ---------------- | ---- | ------------------------------------------------------------ |
2642| type     | string           | Yes  | Event type.<br>- **connect**: connection event.<br>- **close**: close event.|
2643| callback | Callback\<void\> | No  | Callback used to return the result.                         |
2644
2645**Example**
2646
2647```ts
2648import { socket } from '@kit.NetworkKit';
2649import { BusinessError } from '@kit.BasicServicesKit';
2650
2651let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
2652let callback1 = () => {
2653  console.log("on connect success");
2654}
2655tcp.on('connect', callback1);
2656// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
2657tcp.off('connect', callback1);
2658tcp.off('connect');
2659let callback2 = () => {
2660  console.log("on close success");
2661}
2662tcp.on('close', callback2);
2663// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
2664tcp.off('close', callback2);
2665tcp.off('close');
2666```
2667
2668### on('error')
2669
2670on(type: 'error', callback: ErrorCallback): void
2671
2672Subscribes to **error** events of the TCP socket connection. This API uses an asynchronous callback to return the result.
2673
2674**System capability**: SystemCapability.Communication.NetStack
2675
2676**Parameters**
2677
2678| Name  | Type         | Mandatory| Description                                |
2679| -------- | ------------- | ---- | ------------------------------------ |
2680| type     | string        | Yes  | Event type.<br/> **error**: error event.|
2681| callback | ErrorCallback | Yes  | Callback used to return the result.                            |
2682
2683**Example**
2684
2685```ts
2686import { socket } from '@kit.NetworkKit';
2687import { BusinessError } from '@kit.BasicServicesKit';
2688
2689let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
2690tcp.on('error', (err: BusinessError) => {
2691  console.log("on error, err:" + JSON.stringify(err))
2692});
2693```
2694
2695### off('error')
2696
2697off(type: 'error', callback?: ErrorCallback): void
2698
2699Unsubscribes from **error** events of the TCP socket connection. This API uses an asynchronous callback to return the result.
2700
2701**System capability**: SystemCapability.Communication.NetStack
2702
2703**Parameters**
2704
2705| Name  | Type         | Mandatory| Description                                |
2706| -------- | ------------- | ---- | ------------------------------------ |
2707| type     | string        | Yes  | Event type.<br/> **error**: error event.|
2708| callback | ErrorCallback | No  | Callback used to return the result.                            |
2709
2710**Example**
2711
2712```ts
2713import { socket } from '@kit.NetworkKit';
2714import { BusinessError } from '@kit.BasicServicesKit';
2715
2716let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
2717let callback = (err: BusinessError) => {
2718  console.log("on error, err:" + JSON.stringify(err));
2719}
2720tcp.on('error', callback);
2721// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
2722tcp.off('error', callback);
2723tcp.off('error');
2724```
2725
2726## TCPConnectOptions
2727
2728Defines TCP socket connection parameters.
2729
2730**System capability**: SystemCapability.Communication.NetStack
2731
2732| Name | Type                              | Mandatory| Description                      |
2733| ------- | ---------------------------------- | ---- | -------------------------- |
2734| address | [NetAddress](#netaddress) | Yes  | Bound IP address and port number.      |
2735| timeout | number                             | No  | Timeout duration of the TCP socket connection, in ms.|
2736| proxy<sup>18+</sup>   | [ProxyOptions](#proxyoptions18) | No  | Proxy option. By default, no proxy is used.|
2737
2738## TCPSendOptions
2739
2740Defines the parameters for sending data over a TCP socket connection.
2741
2742**System capability**: SystemCapability.Communication.NetStack
2743
2744| Name  | Type  | Mandatory| Description                                                        |
2745| -------- | ------ | ---- | ------------------------------------------------------------ |
2746| data     | string\| ArrayBuffer  | Yes  | Data to send.                                                |
2747| encoding | string | No  | Character encoding format. The options are as follows: **UTF-8**, **UTF-16BE**, **UTF-16LE**, **UTF-16**, **US-AECII**, and **ISO-8859-1**. The default value is **UTF-8**.|
2748
2749## TCPExtraOptions
2750
2751Defines other properties of the TCP socket connection. This API inherits from [ExtraOptionsBase](#extraoptionsbase7).
2752
2753**System capability**: SystemCapability.Communication.NetStack
2754
2755| Name           | Type   | Mandatory| Description                                                        |
2756| ----------------- | ------- | ---- | ------------------------------------------------------------ |
2757| keepAlive         | boolean | No  | Whether to keep the connection alive. The default value is **false**. The value **true** means to keep the connection alive, and the value **false** indicates the opposite.                                 |
2758| OOBInline         | boolean | No  | Whether to enable OOBInline. The default value is **false**. The value **true** means to enable OOBInline, and the value **false** indicates the opposite.                                |
2759| TCPNoDelay        | boolean | No  | Whether to enable no-delay on the TCP socket connection. The default value is **false**. The value **true** means to enable no-delay on the TCP socket connection, and the value **false** indicates the opposite.                      |
2760| socketLinger      | \{on:boolean, linger:number\}  | No  | Socket linger.<br>- **on**: whether to enable socket linger. The value true means to enable socket linger and false means the opposite.<br>- **linger**: linger time, in ms. The value ranges from **0** to **65535**.<br>Specify this parameter only when **on** is set to **true**.|
2761
2762## socket.constructTCPSocketServerInstance<sup>10+</sup>
2763
2764constructTCPSocketServerInstance(): TCPSocketServer
2765
2766Creates a **TCPSocketServer** object.
2767
2768**System capability**: SystemCapability.Communication.NetStack
2769
2770**Return value**
2771
2772| Type                               | Description                         |
2773|  ---------------------------------- |  ---------------------------- |
2774| [TCPSocketServer](#tcpsocketserver10) | **TCPSocketServer** object.|
2775
2776**Example**
2777
2778```ts
2779import { socket } from '@kit.NetworkKit';
2780let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance();
2781```
2782
2783## TCPSocketServer<sup>10+</sup>
2784
2785Defines a TCP socket server connection. Before calling TCPSocketServer APIs, you need to call [socket.constructTCPSocketServerInstance](#socketconstructtcpsocketserverinstance10) to create a **TCPSocketServer** object.
2786
2787### listen<sup>10+</sup>
2788
2789listen(address: NetAddress, callback: AsyncCallback\<void\>): void
2790
2791Binds the IP address and port number. The port number can be specified or randomly allocated by the system. The server listens to and accepts TCP socket connections established over the socket. Multiple threads are used to process client data concurrently. This API uses an asynchronous callback to return the result.
2792
2793> **NOTE**<br>
2794> The server uses this API to perform the **bind**, **listen**, and **accept** operations. If the **bind** operation fails, the system randomly allocates a port number.
2795
2796**Required permissions**: ohos.permission.INTERNET
2797
2798**System capability**: SystemCapability.Communication.NetStack
2799
2800**Parameters**
2801
2802| Name  | Type                     | Mandatory| Description                                         |
2803| -------- | ------------------------- | ---- | --------------------------------------------- |
2804| address  | [NetAddress](#netaddress) | Yes  | Destination address.|
2805| callback | AsyncCallback\<void\>     | Yes  | Callback used to return the result. If the operation fails, an error message is returned.   |
2806
2807**Error codes**
2808
2809| ID| Error Message                                   |
2810| -------- | ------------------------------------------- |
2811| 401      | Parameter error.                            |
2812| 201      | Permission denied.                          |
2813| 2300002  | System internal error.                      |
2814| 2303109  | Bad file number.                            |
2815| 2303111  | Resource temporarily unavailable. Try again.|
2816| 2303198  | Address already in use.                     |
2817| 2303199  | Cannot assign requested address.            |
2818
2819**Example**
2820
2821```ts
2822import { socket } from '@kit.NetworkKit';
2823import { BusinessError } from '@kit.BasicServicesKit';
2824
2825let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance();
2826let listenAddr: socket.NetAddress = {
2827  address:  '192.168.xx.xxx',
2828  port: 8080,
2829  family: 1
2830}
2831tcpServer.listen(listenAddr, (err: BusinessError) => {
2832  if (err) {
2833    console.log("listen fail");
2834    return;
2835  }
2836  console.log("listen success");
2837})
2838```
2839
2840### listen<sup>10+</sup>
2841
2842listen(address: NetAddress): Promise\<void\>
2843
2844Binds the IP address and port number. The port number can be specified or randomly allocated by the system. The server listens to and accepts TCP socket connections established over the socket. Multiple threads are used to process client data concurrently. This API uses a promise to return the result.
2845
2846> **NOTE**<br>
2847> The server uses this API to perform the **bind**, **listen**, and **accept** operations. If the **bind** operation fails, the system randomly allocates a port number.
2848
2849**Required permissions**: ohos.permission.INTERNET
2850
2851**System capability**: SystemCapability.Communication.NetStack
2852
2853**Parameters**
2854
2855| Name | Type                     | Mandatory| Description                                         |
2856| ------- | ------------------------- | ---- | --------------------------------------------- |
2857| address | [NetAddress](#netaddress) | Yes  | Destination address.|
2858
2859**Return value**
2860
2861| Type           | Description                                                        |
2862|  -------------- |  ----------------------------------------------------------- |
2863| Promise\<void\> | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
2864
2865**Error codes**
2866
2867| ID| Error Message                                   |
2868| -------- | ------------------------------------------- |
2869| 401      | Parameter error.                            |
2870| 201      | Permission denied.                          |
2871| 2300002  | System internal error.                      |
2872| 2303109  | Bad file number.                            |
2873| 2303111  | Resource temporarily unavailable. Try again.|
2874| 2303198  | Address already in use.                     |
2875| 2303199  | Cannot assign requested address.            |
2876
2877**Example**
2878
2879```ts
2880import { socket } from '@kit.NetworkKit';
2881import { BusinessError } from '@kit.BasicServicesKit';
2882
2883let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance();
2884let listenAddr: socket.NetAddress = {
2885  address:  '192.168.xx.xxx',
2886  port: 8080,
2887  family: 1
2888}
2889tcpServer.listen(listenAddr).then(() => {
2890  console.log('listen success');
2891}).catch((err: BusinessError) => {
2892  console.log('listen fail');
2893});
2894```
2895
2896### getState<sup>10+</sup>
2897
2898getState(callback: AsyncCallback\<SocketStateBase\>): void
2899
2900Obtains the status of a TCP socket server connection. This API uses an asynchronous callback to return the result.
2901
2902> **NOTE**
2903> This API can be called only after **listen** is successfully called.
2904
2905**Required permissions**: ohos.permission.INTERNET
2906
2907**System capability**: SystemCapability.Communication.NetStack
2908
2909**Parameters**
2910
2911| Name  | Type                                              | Mandatory| Description      |
2912| -------- | -------------------------------------------------- | ---- | ---------- |
2913| callback | AsyncCallback\<[SocketStateBase](#socketstatebase)\> | Yes  | Callback used to return the result. If the operation fails, an error message is returned.|
2914
2915**Error codes**
2916
2917| ID| Error Message                       |
2918| -------- | ------------------------------- |
2919| 401      | Parameter error.                |
2920| 201      | Permission denied.              |
2921| 2300002  | System internal error.          |
2922| 2303188  | Socket operation on non-socket. |
2923
2924**Example**
2925
2926```ts
2927import { socket } from '@kit.NetworkKit';
2928import { BusinessError } from '@kit.BasicServicesKit';
2929
2930let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance();
2931let listenAddr: socket.NetAddress = {
2932  address:  '192.168.xx.xxx',
2933  port: 8080,
2934  family: 1
2935}
2936tcpServer.listen(listenAddr, (err: BusinessError) => {
2937  if (err) {
2938    console.log("listen fail");
2939    return;
2940  }
2941  console.log("listen success");
2942})
2943tcpServer.getState((err: BusinessError, data: socket.SocketStateBase) => {
2944  if (err) {
2945    console.log('getState fail');
2946    return;
2947  }
2948  console.log('getState success:' + JSON.stringify(data));
2949})
2950```
2951
2952### getState<sup>10+</sup>
2953
2954getState(): Promise\<SocketStateBase\>
2955
2956Obtains the status of a TCP socket server connection. This API uses a promise to return the result.
2957
2958> **NOTE**
2959> This API can be called only after **listen** is successfully called.
2960
2961**Required permissions**: ohos.permission.INTERNET
2962
2963**System capability**: SystemCapability.Communication.NetStack
2964
2965**Return value**
2966
2967| Type                                        | Description                                      |
2968|  ------------------------------------------- |  ----------------------------------------- |
2969| Promise\<[SocketStateBase](#socketstatebase)\> | Promise used to return the result.|
2970
2971**Error codes**
2972
2973| ID| Error Message                       |
2974| -------- | ------------------------------- |
2975| 201      | Permission denied.              |
2976| 2300002  | System internal error.          |
2977| 2303188  | Socket operation on non-socket. |
2978
2979**Example**
2980
2981```ts
2982import { socket } from '@kit.NetworkKit';
2983import { BusinessError } from '@kit.BasicServicesKit';
2984
2985let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance();
2986let listenAddr: socket.NetAddress = {
2987  address:  '192.168.xx.xxx',
2988  port: 8080,
2989  family: 1
2990}
2991tcpServer.listen(listenAddr, (err: BusinessError) => {
2992  if (err) {
2993    console.log("listen fail");
2994    return;
2995  }
2996  console.log("listen success");
2997})
2998tcpServer.getState().then((data: socket.SocketStateBase) => {
2999  console.log('getState success' + JSON.stringify(data));
3000}).catch((err: BusinessError) => {
3001  console.log('getState fail');
3002});
3003```
3004
3005### setExtraOptions<sup>10+</sup>
3006
3007setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\<void\>): void
3008
3009Sets other properties of a TCP socket server connection. This API uses an asynchronous callback to return the result.
3010
3011> **NOTE**
3012> This API can be called only after **listen** is successfully called.
3013
3014**Required permissions**: ohos.permission.INTERNET
3015
3016**System capability**: SystemCapability.Communication.NetStack
3017
3018**Parameters**
3019
3020| Name  | Type                               | Mandatory| Description                                                        |
3021| -------- | ----------------------------------- | ---- | ------------------------------------------------------------ |
3022| options  | [TCPExtraOptions](#tcpextraoptions) | Yes  | Other properties of a TCP socket server connection.|
3023| callback | AsyncCallback\<void\>               | Yes  | Callback used to return the result. If the operation fails, an error message is returned.               |
3024
3025**Error codes**
3026
3027| ID| Error Message                       |
3028| -------- | ------------------------------- |
3029| 401      | Parameter error.                |
3030| 201      | Permission denied.              |
3031| 2300002  | System internal error.          |
3032| 2303188  | Socket operation on non-socket. |
3033
3034**Example**
3035
3036```ts
3037import { socket } from '@kit.NetworkKit';
3038import { BusinessError } from '@kit.BasicServicesKit';
3039
3040let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance();
3041let listenAddr: socket.NetAddress = {
3042  address:  '192.168.xx.xxx',
3043  port: 8080,
3044  family: 1
3045}
3046tcpServer.listen(listenAddr, (err: BusinessError) => {
3047  if (err) {
3048    console.log("listen fail");
3049    return;
3050  }
3051  console.log("listen success");
3052})
3053
3054interface SocketLinger {
3055  on: boolean;
3056  linger: number;
3057}
3058
3059let tcpExtraOptions: socket.TCPExtraOptions = {
3060  keepAlive: true,
3061  OOBInline: true,
3062  TCPNoDelay: true,
3063  socketLinger: { on: true, linger: 10 } as SocketLinger,
3064  receiveBufferSize: 1000,
3065  sendBufferSize: 1000,
3066  reuseAddress: true,
3067  socketTimeout: 3000
3068}
3069tcpServer.setExtraOptions(tcpExtraOptions, (err: BusinessError) => {
3070  if (err) {
3071    console.log('setExtraOptions fail');
3072    return;
3073  }
3074  console.log('setExtraOptions success');
3075});
3076```
3077
3078### setExtraOptions<sup>10+</sup>
3079
3080setExtraOptions(options: TCPExtraOptions): Promise\<void\>
3081
3082Sets other properties of a TCP socket server connection. This API uses a promise to return the result.
3083
3084> **NOTE**
3085> This API can be called only after **listen** is successfully called.
3086
3087**Required permissions**: ohos.permission.INTERNET
3088
3089**System capability**: SystemCapability.Communication.NetStack
3090
3091**Parameters**
3092
3093| Name | Type                               | Mandatory| Description                                                        |
3094| ------- | ----------------------------------- | ---- | ------------------------------------------------------------ |
3095| options | [TCPExtraOptions](#tcpextraoptions) | Yes  | Other properties of a TCP socket server connection.|
3096
3097**Return value**
3098
3099| Type           | Description                                                      |
3100|  -------------- |  --------------------------------------------------------- |
3101| Promise\<void\> | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
3102
3103**Error codes**
3104
3105| ID| Error Message                       |
3106| -------- | ------------------------------- |
3107| 401      | Parameter error.                |
3108| 201      | Permission denied.              |
3109| 2300002  | System internal error.          |
3110| 2303188  | Socket operation on non-socket. |
3111
3112**Example**
3113
3114```ts
3115import { socket } from '@kit.NetworkKit';
3116import { BusinessError } from '@kit.BasicServicesKit';
3117
3118let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance();
3119let listenAddr: socket.NetAddress = {
3120  address:  '192.168.xx.xxx',
3121  port: 8080,
3122  family: 1
3123}
3124
3125interface SocketLinger {
3126  on: boolean;
3127  linger: number;
3128}
3129
3130tcpServer.listen(listenAddr, (err: BusinessError) => {
3131  if (err) {
3132    console.log("listen fail");
3133    return;
3134  }
3135  console.log("listen success");
3136})
3137
3138let tcpExtraOptions: socket.TCPExtraOptions = {
3139  keepAlive: true,
3140  OOBInline: true,
3141  TCPNoDelay: true,
3142  socketLinger: { on: true, linger: 10 } as SocketLinger,
3143  receiveBufferSize: 1000,
3144  sendBufferSize: 1000,
3145  reuseAddress: true,
3146  socketTimeout: 3000
3147}
3148tcpServer.setExtraOptions(tcpExtraOptions).then(() => {
3149  console.log('setExtraOptions success');
3150}).catch((err: BusinessError) => {
3151  console.log('setExtraOptions fail');
3152});
3153```
3154
3155### getLocalAddress<sup>12+</sup>
3156
3157getLocalAddress(): Promise\<NetAddress\>
3158
3159Obtains the local socket address of a **TCPSocketServer** connection. This API uses a promise to return the result.
3160
3161> **NOTE**
3162> This API can be called only after **listen** is successfully called.
3163
3164**System capability**: SystemCapability.Communication.NetStack
3165
3166**Return value**
3167
3168| Type           | Description                                                |
3169|  -------------- |  --------------------------------------------------- |
3170| Promise\<[NetAddress](#netaddress)\> | Promise used to return the result.|
3171
3172**Error codes**
3173
3174| ID| Error Message                                   |
3175| -------- | ------------------------------------------- |
3176| 2300002  | System internal error.                      |
3177| 2301009  | Bad file descriptor.                            |
3178| 2303188  | Socket operation on non-socket. |
3179
3180**Example**
3181
3182```ts
3183import { socket } from '@kit.NetworkKit';
3184import { BusinessError } from '@kit.BasicServicesKit';
3185
3186let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance();
3187let listenAddr: socket.NetAddress = {
3188  address: '192.168.xx.xxx',
3189  port: 8080,
3190  family: 1
3191}
3192tcpServer.listen(listenAddr).then(() => {
3193  tcpServer.getLocalAddress().then((localAddress: socket.NetAddress) => {
3194    console.info("SUCCESS! Address:" + JSON.stringify(localAddress));
3195  }).catch((err: BusinessError) => {
3196    console.error("FerrorAILED! Error:" + JSON.stringify(err));
3197  })
3198}).catch((err: BusinessError) => {
3199  console.error('listen fail');
3200});
3201```
3202
3203### on('connect')<sup>10+</sup>
3204
3205on(type: 'connect', callback: Callback\<TCPSocketConnection\>): void
3206
3207Subscribes to **connect** events of a **TCPSocketServer** object. This API uses an asynchronous callback to return the result.
3208
3209> **NOTE**
3210> This API can be called only after **listen** is successfully called.
3211
3212**System capability**: SystemCapability.Communication.NetStack
3213
3214**Parameters**
3215
3216| Name  | Type                           | Mandatory| Description                                 |
3217| -------- | ------------------------------- | ---- | ------------------------------------- |
3218| type     | string                          | Yes  | Event type.<br/> **connect**: connection event.|
3219| callback | Callback\<[TCPSocketConnection](#tcpsocketconnection10)\> | Yes  | Callback used to return the result. If the operation fails, an error message is returned.      |
3220
3221**Error codes**
3222
3223| ID| Error Message        |
3224| -------- | ---------------- |
3225| 401      | Parameter error. |
3226
3227**Example**
3228
3229```ts
3230import { socket } from '@kit.NetworkKit';
3231
3232let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance();
3233
3234let listenAddr: socket.NetAddress = {
3235  address:  '192.168.xx.xxx',
3236  port: 8080,
3237  family: 1
3238}
3239tcpServer.listen(listenAddr, (err: BusinessError) => {
3240  if (err) {
3241    console.log("listen fail");
3242    return;
3243  }
3244  console.log("listen success");
3245  tcpServer.on('connect', (data: socket.TCPSocketConnection) => {
3246    console.log(JSON.stringify(data))
3247  });
3248})
3249```
3250
3251### off('connect')<sup>10+</sup>
3252
3253off(type: 'connect', callback?: Callback\<TCPSocketConnection\>): void
3254
3255Unsubscribes from **connect** events of a **TCPSocketServer** object. This API uses an asynchronous callback to return the result.
3256
3257**System capability**: SystemCapability.Communication.NetStack
3258
3259**Parameters**
3260
3261| Name  | Type                           | Mandatory| Description                                 |
3262| -------- | ------------------------------- | ---- | ------------------------------------- |
3263| type     | string                          | Yes  | Event type.<br/> **connect**: connection event.|
3264| callback | Callback\<[TCPSocketConnection](#tcpsocketconnection10)\> | No  | Callback used to return the result. If the operation fails, an error message is returned.|
3265
3266**Error codes**
3267
3268| ID| Error Message        |
3269| -------- | ---------------- |
3270| 401      | Parameter error. |
3271
3272**Example**
3273
3274```ts
3275import { socket } from '@kit.NetworkKit';
3276
3277let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance();
3278
3279let listenAddr: socket.NetAddress = {
3280  address:  '192.168.xx.xxx',
3281  port: 8080,
3282  family: 1
3283}
3284tcpServer.listen(listenAddr, (err: BusinessError) => {
3285  if (err) {
3286    console.log("listen fail");
3287    return;
3288  }
3289  console.log("listen success");
3290  let callback = (data: socket.TCPSocketConnection) => {
3291    console.log('on connect message: ' + JSON.stringify(data));
3292  }
3293  tcpServer.on('connect', callback);
3294  // You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
3295  tcpServer.off('connect', callback);
3296  tcpServer.off('connect');
3297})
3298```
3299
3300### on('error')<sup>10+</sup>
3301
3302on(type: 'error', callback: ErrorCallback): void
3303
3304Subscribes to **error** events of a **TCPSocketServer** object. This API uses an asynchronous callback to return the result.
3305
3306> **NOTE**
3307> This API can be called only after **listen** is successfully called.
3308
3309**System capability**: SystemCapability.Communication.NetStack
3310
3311**Parameters**
3312
3313| Name  | Type         | Mandatory| Description                                |
3314| -------- | ------------- | ---- | ------------------------------------ |
3315| type     | string        | Yes  | Event type.<br/> **error**: error event.|
3316| callback | ErrorCallback | Yes  | Callback used to return the result. If the operation fails, an error message is returned.|
3317
3318**Error codes**
3319
3320| ID| Error Message        |
3321| -------- | ---------------- |
3322| 401      | Parameter error. |
3323
3324**Example**
3325
3326```ts
3327import { socket } from '@kit.NetworkKit';
3328import { BusinessError } from '@kit.BasicServicesKit';
3329
3330let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance();
3331
3332let listenAddr: socket.NetAddress = {
3333  address:  '192.168.xx.xxx',
3334  port: 8080,
3335  family: 1
3336}
3337tcpServer.listen(listenAddr, (err: BusinessError) => {
3338  if (err) {
3339    console.log("listen fail");
3340    return;
3341  }
3342  console.log("listen success");
3343  tcpServer.on('error', (err: BusinessError) => {
3344    console.log("on error, err:" + JSON.stringify(err))
3345  });
3346})
3347```
3348
3349### off('error')<sup>10+</sup>
3350
3351off(type: 'error', callback?: ErrorCallback): void
3352
3353Unsubscribes from **error** events of a **TCPSocketServer** object. This API uses an asynchronous callback to return the result.
3354
3355**System capability**: SystemCapability.Communication.NetStack
3356
3357**Parameters**
3358
3359| Name  | Type         | Mandatory| Description                                |
3360| -------- | ------------- | ---- | ------------------------------------ |
3361| type     | string        | Yes  | Event type.<br/> **error**: error event.|
3362| callback | ErrorCallback | No  | Callback used to return the result. If the operation fails, an error message is returned.                          |
3363
3364**Error codes**
3365
3366| ID| Error Message        |
3367| -------- | ---------------- |
3368| 401      | Parameter error. |
3369
3370**Example**
3371
3372```ts
3373import { socket } from '@kit.NetworkKit';
3374import { BusinessError } from '@kit.BasicServicesKit';
3375
3376let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance();
3377
3378let listenAddr: socket.NetAddress = {
3379  address:  '192.168.xx.xxx',
3380  port: 8080,
3381  family: 1
3382}
3383tcpServer.listen(listenAddr, (err: BusinessError) => {
3384  if (err) {
3385    console.log("listen fail");
3386    return;
3387  }
3388  console.log("listen success");
3389  let callback = (err: BusinessError) => {
3390    console.log("on error, err:" + JSON.stringify(err));
3391  }
3392  tcpServer.on('error', callback);
3393  // You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
3394  tcpServer.off('error', callback);
3395  tcpServer.off('error');
3396})
3397```
3398
3399## TCPSocketConnection<sup>10+</sup>
3400
3401Defines a **TCPSocketConnection** object, that is, the connection between the TCPSocket client and the server. Before calling TCPSocketConnection APIs, you need to obtain a **TCPSocketConnection** object.
3402
3403> **NOTE**
3404> The TCPSocket client can call related APIs through the **TCPSocketConnection** object only after a connection is successfully established between the TCPSocket client and the server.
3405
3406**System capability**: SystemCapability.Communication.NetStack
3407
3408### Attributes
3409
3410| Name    | Type  | Mandatory| Description                                     |
3411| -------- | ------ | ---- | ----------------------------------------- |
3412| clientId | number | Yes  | ID of the connection between the client and TCPSocketServer.|
3413
3414### send<sup>10+</sup>
3415
3416send(options: TCPSendOptions, callback: AsyncCallback\<void\>): void
3417
3418Sends data over a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result.
3419
3420> **NOTE**
3421> This API can be called only after a connection with the client is set up.
3422
3423**Required permissions**: ohos.permission.INTERNET
3424
3425**System capability**: SystemCapability.Communication.NetStack
3426
3427**Parameters**
3428
3429| Name  | Type                             | Mandatory| Description                                                        |
3430| -------- | --------------------------------- | ---- | ------------------------------------------------------------ |
3431| options  | [TCPSendOptions](#tcpsendoptions) | Yes  | Defines the parameters for sending data over a TCP socket connection.|
3432| callback | AsyncCallback\<void\>             | Yes  | Callback used to return the result. If the operation fails, an error message is returned.            |
3433
3434**Error codes**
3435
3436| ID| Error Message              |
3437| -------- | ---------------------- |
3438| 401      | Parameter error.       |
3439| 201      | Permission denied.     |
3440| 2300002  | System internal error. |
3441
3442**Example**
3443
3444```ts
3445import { socket } from '@kit.NetworkKit';
3446
3447let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance();
3448
3449tcpServer.on('connect', (client: socket.TCPSocketConnection) => {
3450  let tcpSendOption: socket.TCPSendOptions = {
3451    data: 'Hello, client!'
3452  }
3453  client.send(tcpSendOption, () => {
3454    console.log('send success');
3455  });
3456});
3457```
3458
3459### send<sup>10+</sup>
3460
3461send(options: TCPSendOptions): Promise\<void\>
3462
3463Sends data over a **TCPSocketConnection** object. This API uses a promise to return the result.
3464
3465> **NOTE**
3466> This API can be called only after a connection with the client is set up.
3467
3468**Required permissions**: ohos.permission.INTERNET
3469
3470**System capability**: SystemCapability.Communication.NetStack
3471
3472**Parameters**
3473
3474| Name | Type                             | Mandatory| Description                                                        |
3475| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
3476| options | [TCPSendOptions](#tcpsendoptions) | Yes  | Defines the parameters for sending data over a TCP socket connection.|
3477
3478**Return value**
3479
3480| Type           | Description                                                        |
3481|  -------------- |  ----------------------------------------------------------- |
3482| Promise\<void\> | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
3483
3484**Error codes**
3485
3486| ID| Error Message              |
3487| -------- | ---------------------- |
3488| 401      | Parameter error.       |
3489| 201      | Permission denied.     |
3490| 2300002  | System internal error. |
3491
3492**Example**
3493
3494```ts
3495import { socket } from '@kit.NetworkKit';
3496import { BusinessError } from '@kit.BasicServicesKit';
3497
3498let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance();
3499
3500tcpServer.on('connect', (client: socket.TCPSocketConnection) => {
3501  let tcpSendOption: socket.TCPSendOptions = {
3502    data: 'Hello, client!'
3503  }
3504  client.send(tcpSendOption).then(() => {
3505    console.log('send success');
3506  }).catch((err: BusinessError) => {
3507    console.log('send fail');
3508  });
3509});
3510```
3511
3512### close<sup>10+</sup>
3513
3514close(callback: AsyncCallback\<void\>): void
3515
3516Closes a TCP socket connection. This API uses an asynchronous callback to return the result.
3517
3518**Required permissions**: ohos.permission.INTERNET
3519
3520**System capability**: SystemCapability.Communication.NetStack
3521
3522**Parameters**
3523
3524| Name  | Type                 | Mandatory| Description      |
3525| -------- | --------------------- | ---- | ---------- |
3526| callback | AsyncCallback\<void\> | Yes  | Callback used to return the result. If the operation fails, an error message is returned.|
3527
3528**Error codes**
3529
3530| ID| Error Message              |
3531| -------- | ---------------------- |
3532| 401      | Parameter error.       |
3533| 201      | Permission denied.     |
3534| 2300002  | System internal error. |
3535
3536**Example**
3537
3538```ts
3539import { socket } from '@kit.NetworkKit';
3540import { BusinessError } from '@kit.BasicServicesKit';
3541
3542let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance();
3543
3544tcpServer.on('connect', (client: socket.TCPSocketConnection) => {
3545  client.close((err: BusinessError) => {
3546    if (err) {
3547      console.log('close fail');
3548      return;
3549    }
3550    console.log('close success');
3551  });
3552});
3553```
3554
3555### close<sup>10+</sup>
3556
3557close(): Promise\<void\>
3558
3559Closes a TCP socket connection. This API uses a promise to return the result.
3560
3561**Required permissions**: ohos.permission.INTERNET
3562
3563**System capability**: SystemCapability.Communication.NetStack
3564
3565**Return value**
3566
3567| Type           | Description                                        |
3568|  -------------- |  ------------------------------------------- |
3569| Promise\<void\> | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
3570
3571**Error codes**
3572
3573| ID| Error Message              |
3574| -------- | ---------------------- |
3575| 201      | Permission denied.     |
3576| 2300002  | System internal error. |
3577
3578**Example**
3579
3580```ts
3581import { socket } from '@kit.NetworkKit';
3582
3583let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance();
3584tcpServer.on('connect', (client: socket.TCPSocketConnection) => {
3585  client.close().then(() => {
3586  	console.log('close success');
3587  }).catch((err: BusinessError) => {
3588  	console.log('close fail');
3589  });
3590});
3591```
3592
3593### getRemoteAddress<sup>10+</sup>
3594
3595getRemoteAddress(callback: AsyncCallback\<NetAddress\>): void
3596
3597Obtains the remote address of a socket connection. This API uses an asynchronous callback to return the result.
3598
3599> **NOTE**
3600> This API can be called only after a connection with the client is set up.
3601
3602**Required permissions**: ohos.permission.INTERNET
3603
3604**System capability**: SystemCapability.Communication.NetStack
3605
3606**Parameters**
3607
3608| Name  | Type                                    | Mandatory| Description      |
3609| -------- | ---------------------------------------- | ---- | ---------- |
3610| callback | AsyncCallback\<[NetAddress](#netaddress)\> | Yes  | Callback used to return the result. If the operation fails, an error message is returned.|
3611
3612**Error codes**
3613
3614| ID| Error Message                       |
3615| -------- | ------------------------------- |
3616| 401      | Parameter error.                |
3617| 201      | Permission denied.              |
3618| 2300002  | System internal error.          |
3619| 2303188  | Socket operation on non-socket. |
3620
3621**Example**
3622
3623```ts
3624import { socket } from '@kit.NetworkKit';
3625import { BusinessError } from '@kit.BasicServicesKit';
3626
3627let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance();
3628tcpServer.on('connect', (client: socket.TCPSocketConnection) => {
3629  client.getRemoteAddress((err: BusinessError, data: socket.NetAddress) => {
3630    if (err) {
3631      console.log('getRemoteAddress fail');
3632      return;
3633    }
3634    console.log('getRemoteAddress success:' + JSON.stringify(data));
3635  });
3636});
3637```
3638
3639### getRemoteAddress<sup>10+</sup>
3640
3641getRemoteAddress(): Promise\<NetAddress\>
3642
3643Obtains the remote address of a socket connection. This API uses a promise to return the result.
3644
3645> **NOTE**
3646> This API can be called only after a connection with the client is set up.
3647
3648**Required permissions**: ohos.permission.INTERNET
3649
3650**System capability**: SystemCapability.Communication.NetStack
3651
3652**Return value**
3653
3654| Type                              | Description                                       |
3655|  --------------------------------- |  ------------------------------------------ |
3656| Promise\<[NetAddress](#netaddress)\> | Promise used to return the result.|
3657
3658**Error codes**
3659
3660| ID| Error Message                       |
3661| -------- | ------------------------------- |
3662| 201      | Permission denied.              |
3663| 2300002  | System internal error.          |
3664| 2303188  | Socket operation on non-socket. |
3665
3666**Example**
3667
3668```ts
3669import { socket } from '@kit.NetworkKit';
3670import { BusinessError } from '@kit.BasicServicesKit';
3671
3672let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance();
3673tcpServer.on('connect', (client: socket.TCPSocketConnection) => {
3674  client.getRemoteAddress().then(() => {
3675    console.log('getRemoteAddress success');
3676  }).catch((err: BusinessError) => {
3677    console.log('getRemoteAddress fail');
3678  });
3679});
3680```
3681
3682### getLocalAddress<sup>12+</sup>
3683
3684getLocalAddress(): Promise\<NetAddress\>
3685
3686Obtains the local socket address of a **TCPSocketConnection** connection. This API uses a promise to return the result.
3687
3688**System capability**: SystemCapability.Communication.NetStack
3689
3690**Return value**
3691
3692| Type           | Description                                                |
3693|  -------------- |  --------------------------------------------------- |
3694| Promise\<[NetAddress](#netaddress)\> | Promise used to return the result.|
3695
3696**Error codes**
3697
3698| ID| Error Message                                   |
3699| -------- | ------------------------------------------- |
3700| 2300002  | System internal error.                      |
3701| 2301009  | Bad file descriptor.                            |
3702| 2303188  | Socket operation on non-socket. |
3703
3704**Example**
3705
3706```ts
3707import { socket } from '@kit.NetworkKit';
3708import { BusinessError } from '@kit.BasicServicesKit';
3709
3710let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance();
3711let listenAddr: socket.NetAddress = {
3712  address: "192.168.xx.xx",
3713  port: 8080,
3714  family: 1
3715}
3716tcpServer.listen(listenAddr, (err: BusinessError) => {
3717  let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
3718  let netAddress: socket.NetAddress = {
3719    address: "192.168.xx.xx",
3720    port: 8080
3721  }
3722  let options: socket.TCPConnectOptions = {
3723    address: netAddress,
3724    timeout: 6000
3725  }
3726  tcp.connect(options, (err: BusinessError) => {
3727    if (err) {
3728      console.error('connect fail');
3729      return;
3730    }
3731    console.info('connect success!');
3732  })
3733  tcpServer.on('connect', (client: socket.TCPSocketConnection) => {
3734    client.getLocalAddress().then((localAddress: socket.NetAddress) => {
3735      console.info("Family IP Port: " + JSON.stringify(localAddress));
3736    }).catch((err: BusinessError) => {
3737      console.error('Error:' + JSON.stringify(err));
3738    });
3739  })
3740})
3741```
3742
3743### on('message')<sup>10+</sup>
3744
3745on(type: 'message', callback: Callback<SocketMessageInfo\>): void
3746
3747Subscribes to **message** events of a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result.
3748
3749**System capability**: SystemCapability.Communication.NetStack
3750
3751**Parameters**
3752
3753| Name  | Type                                                        | Mandatory| Description                                     |
3754| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
3755| type     | string                                                       | Yes  | Event type.<br/> **message**: message receiving event.|
3756| callback | Callback\<[SocketMessageInfo](#socketmessageinfo11)\> | Yes  | Callback used to return the result. If the operation fails, an error message is returned.        |
3757
3758**Error codes**
3759
3760| ID| Error Message        |
3761| -------- | ---------------- |
3762| 401      | Parameter error. |
3763
3764**Example**
3765
3766```ts
3767import { socket } from '@kit.NetworkKit';
3768import { BusinessError } from '@kit.BasicServicesKit';
3769
3770let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance();
3771
3772tcpServer.on('connect', (client: socket.TCPSocketConnection) => {
3773  client.on('message', (value: socket.SocketMessageInfo) => {
3774    let messageView = '';
3775    for (let i: number = 0; i < value.message.byteLength; i++) {
3776      let uint8Array = new Uint8Array(value.message)
3777      let messages = uint8Array[i]
3778      let message = String.fromCharCode(messages);
3779      messageView += message;
3780    }
3781    console.log('on message message: ' + JSON.stringify(messageView));
3782    console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo));
3783  });
3784});
3785```
3786
3787### off('message')<sup>10+</sup>
3788
3789off(type: 'message', callback?: Callback<SocketMessageInfo\>): void
3790
3791Unsubscribes from **message** events of a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result.
3792
3793**System capability**: SystemCapability.Communication.NetStack
3794
3795**Parameters**
3796
3797| Name  | Type                                                        | Mandatory| Description                                     |
3798| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
3799| type     | string                                                       | Yes  | Event type.<br/> **message**: message receiving event.|
3800| callback | Callback\<[SocketMessageInfo](#socketmessageinfo11)\> | No  | Callback used to return the result. If the operation fails, an error message is returned.       |
3801
3802**Error codes**
3803
3804| ID| Error Message        |
3805| -------- | ---------------- |
3806| 401      | Parameter error. |
3807
3808**Example**
3809
3810```ts
3811import { socket } from '@kit.NetworkKit';
3812import { BusinessError } from '@kit.BasicServicesKit';
3813
3814let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance();
3815let callback = (value: socket.SocketMessageInfo) => {
3816  let messageView = '';
3817  for (let i: number = 0; i < value.message.byteLength; i++) {
3818    let uint8Array = new Uint8Array(value.message)
3819    let messages = uint8Array[i]
3820    let message = String.fromCharCode(messages);
3821    messageView += message;
3822  }
3823  console.log('on message message: ' + JSON.stringify(messageView));
3824  console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo));
3825}
3826tcpServer.on('connect', (client: socket.TCPSocketConnection) => {
3827  client.on('message', callback);
3828  // You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
3829  client.off('message', callback);
3830  client.off('message');
3831});
3832```
3833
3834### on('close')<sup>10+</sup>
3835
3836on(type: 'close', callback: Callback\<void\>): void
3837
3838Subscribes to **close** events of a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result.
3839
3840**System capability**: SystemCapability.Communication.NetStack
3841
3842**Parameters**
3843
3844| Name  | Type            | Mandatory| Description                               |
3845| -------- | ---------------- | ---- | ----------------------------------- |
3846| type     | string           | Yes  | Event type.<br/> **close**: close event.|
3847| callback | Callback\<void\> | Yes  | Callback used to return the result. If the operation fails, an error message is returned.       |
3848
3849**Error codes**
3850
3851| ID| Error Message        |
3852| -------- | ---------------- |
3853| 401      | Parameter error. |
3854
3855**Example**
3856
3857```ts
3858import { socket } from '@kit.NetworkKit';
3859import { BusinessError } from '@kit.BasicServicesKit';
3860
3861let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance();
3862tcpServer.on('connect', (client: socket.TCPSocketConnection) => {
3863  client.on('close', () => {
3864    console.log("on close success")
3865  });
3866});
3867```
3868
3869### off('close')<sup>10+</sup>
3870
3871off(type: 'close', callback?: Callback\<void\>): void
3872
3873Unsubscribes from **close** events of a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result.
3874
3875**System capability**: SystemCapability.Communication.NetStack
3876
3877**Parameters**
3878
3879| Name  | Type            | Mandatory| Description                               |
3880| -------- | ---------------- | ---- | ----------------------------------- |
3881| type     | string           | Yes  | Event type.<br/> **close**: close event.|
3882| callback | Callback\<void\> | No  | Callback used to return the result. If the operation fails, an error message is returned.   |
3883
3884**Error codes**
3885
3886| ID| Error Message        |
3887| -------- | ---------------- |
3888| 401      | Parameter error. |
3889
3890**Example**
3891
3892```ts
3893import { socket } from '@kit.NetworkKit';
3894
3895let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance();
3896let callback = () => {
3897  console.log("on close success");
3898}
3899tcpServer.on('connect', (client: socket.TCPSocketConnection) => {
3900  client.on('close', callback);
3901  // You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
3902  client.off('close', callback);
3903  client.off('close');
3904});
3905```
3906
3907### on('error')<sup>10+</sup>
3908
3909on(type: 'error', callback: ErrorCallback): void
3910
3911Subscribes to **error** events of a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result.
3912
3913**System capability**: SystemCapability.Communication.NetStack
3914
3915**Parameters**
3916
3917| Name  | Type         | Mandatory| Description                                |
3918| -------- | ------------- | ---- | ------------------------------------ |
3919| type     | string        | Yes  | Event type.<br/> **error**: error event.|
3920| callback | ErrorCallback | Yes  | Callback used to return the result. If the operation fails, an error message is returned.   |
3921
3922**Error codes**
3923
3924| ID| Error Message        |
3925| -------- | ---------------- |
3926| 401      | Parameter error. |
3927
3928**Example**
3929
3930```ts
3931import { socket } from '@kit.NetworkKit';
3932import { BusinessError } from '@kit.BasicServicesKit';
3933
3934let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance();
3935tcpServer.on('connect', (client: socket.TCPSocketConnection) => {
3936  client.on('error', (err: BusinessError) => {
3937    console.log("on error, err:" + JSON.stringify(err))
3938  });
3939});
3940```
3941
3942### off('error')<sup>10+</sup>
3943
3944off(type: 'error', callback?: ErrorCallback): void
3945
3946Unsubscribes from **error** events of a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result.
3947
3948**System capability**: SystemCapability.Communication.NetStack
3949
3950**Parameters**
3951
3952| Name  | Type         | Mandatory| Description                                |
3953| -------- | ------------- | ---- | ------------------------------------ |
3954| type     | string        | Yes  | Event type.<br/> **error**: error event.|
3955| callback | ErrorCallback | No  | Callback used to return the result. If the operation fails, an error message is returned. |
3956
3957**Error codes**
3958
3959| ID| Error Message        |
3960| -------- | ---------------- |
3961| 401      | Parameter error. |
3962
3963**Example**
3964
3965```ts
3966import { socket } from '@kit.NetworkKit';
3967import { BusinessError } from '@kit.BasicServicesKit';
3968
3969let callback = (err: BusinessError) => {
3970  console.log("on error, err:" + JSON.stringify(err));
3971}
3972let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance();
3973tcpServer.on('connect', (client: socket.TCPSocketConnection) => {
3974  client.on('error', callback);
3975  // You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
3976  client.off('error', callback);
3977  client.off('error');
3978});
3979```
3980
3981## Description of TCP Error Codes
3982
3983The TCP error code mapping is in the format of 2301000 + Linux kernel error code.
3984
3985For details about error codes, see [Socket Error Codes](errorcode-net-socket.md).
3986
3987## socket.constructLocalSocketInstance<sup>11+</sup>
3988
3989constructLocalSocketInstance(): LocalSocket
3990
3991Creates a **LocalSocket** object.
3992
3993**System capability**: SystemCapability.Communication.NetStack
3994
3995**Return value**
3996
3997| Type                              | Description                   |
3998| :--------------------------------- | :---------------------- |
3999| [LocalSocket](#localsocket11) | **LocalSocket** object.|
4000
4001**Example**
4002
4003```ts
4004import { socket } from '@kit.NetworkKit';
4005let client: socket.LocalSocket = socket.constructLocalSocketInstance();
4006```
4007
4008## LocalSocket<sup>11+</sup>
4009
4010Defines a **LocalSocket** object. Before calling LocalSocket APIs, you need to call [socket.constructLocalSocketInstance](#socketconstructlocalsocketinstance11) to create a **LocalSocket** object.
4011
4012### bind<sup>11+</sup>
4013
4014bind(address: LocalAddress): Promise\<void\>;
4015
4016Binds the address of a local socket file. This API uses a promise to return the result.
4017
4018> **NOTE**
4019> This API explicitly binds the client to a local socket file based on the specified address.
4020> It is not mandatory in local socket communication.
4021
4022**System capability**: SystemCapability.Communication.NetStack
4023
4024**Parameters**
4025
4026| Name  | Type                              | Mandatory| Description                                                  |
4027| -------- | ---------------------------------- | ---- | ------------------------------------------------------ |
4028| address  | [LocalAddress](#localaddress11) | Yes  | Destination address. For details, see [LocalAddress](#localaddress11).|
4029
4030**Error codes**
4031
4032| ID| Error Message                   |
4033| ------- | -------------------------- |
4034| 401     | Parameter error.           |
4035| 2301013 | Insufficient permissions.  |
4036| 2301022 | Invalid argument.          |
4037| 2301098 | Address already in use.    |
4038
4039**Example**
4040
4041```ts
4042import { socket } from '@kit.NetworkKit';
4043
4044let client: socket.LocalSocket = socket.constructLocalSocketInstance()
4045let sandboxPath: string = getContext().filesDir + '/testSocket'
4046let address : socket.LocalAddress = {
4047  address: sandboxPath
4048}
4049client.bind(address).then(() => {
4050  console.log('bind success')
4051}).catch((err: Object) => {
4052  console.error('failed to bind: ' + JSON.stringify(err))
4053})
4054```
4055
4056### connect<sup>11+</sup>
4057
4058connect(options: LocalConnectOptions): Promise\<void\>
4059
4060Connects to the specified socket file. This API uses a promise to return the result.
4061
4062> **NOTE**
4063> This API allows you to connect to the TCP server without first executing **localsocket.bind**.
4064
4065**System capability**: SystemCapability.Communication.NetStack
4066
4067**Parameters**
4068
4069| Name | Type                                    | Mandatory| Description                                                        |
4070| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
4071| options | [LocalConnectOptions](#localconnectoptions11) | Yes  | Local socket connection parameters. For details, see [LocalConnectOptions](#localconnectoptions11).|
4072
4073**Return value**
4074
4075| Type           | Description                                      |
4076| :-------------- | :---------------------------------------- |
4077| Promise\<void\> | Promise used to return the result.|
4078
4079**Error codes**
4080
4081| ID| Error Message                |
4082| ------- | ----------------------- |
4083| 401     | Parameter error.                 |
4084| 2301013     | Insufficient permissions.        |
4085| 2301022     | Invalid argument.                |
4086| 2301111     | Connection refused.              |
4087| 2301099     | Cannot assign requested address. |
4088
4089**Example**
4090
4091```ts
4092import { socket } from '@kit.NetworkKit';
4093
4094let client: socket.LocalSocket = socket.constructLocalSocketInstance();
4095let sandboxPath: string = getContext().filesDir + '/testSocket'
4096let localAddress : socket.LocalAddress = {
4097  address: sandboxPath
4098}
4099let connectOpt: socket.LocalConnectOptions = {
4100  address: localAddress,
4101  timeout: 6000
4102}
4103client.connect(connectOpt).then(() => {
4104  console.log('connect success')
4105}).catch((err: Object) => {
4106  console.error('connect fail: ' + JSON.stringify(err));
4107});
4108```
4109
4110### send<sup>11+</sup>
4111
4112send(options: LocalSendOptions): Promise\<void\>
4113
4114Sends data over a local socket connection. This API uses a promise to return the result.
4115
4116> **NOTE**
4117> This API can be called only after **connect** is successfully called.
4118
4119**System capability**: SystemCapability.Communication.NetStack
4120
4121**Parameters**
4122
4123| Name | Type                                   | Mandatory| Description                                                        |
4124| ------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
4125| options | [LocalSendOptions](#localsendoptions11) | Yes  | Parameters for sending data over a local socket connection. For details, see [LocalSendOptions](#localsendoptions11).|
4126
4127**Return value**
4128
4129| Type           | Description                                        |
4130| :-------------- | :------------------------------------------ |
4131| Promise\<void\> | Promise used to return the result.|
4132
4133**Error codes**
4134
4135| ID| Error Message                |
4136| ------- | ----------------------- |
4137| 401     | Parameter error.        |
4138| 2301011 | Operation would block.  |
4139
4140**Example**
4141
4142```ts
4143import { socket } from '@kit.NetworkKit';
4144
4145let client: socket.LocalSocket = socket.constructLocalSocketInstance()
4146let sandboxPath: string = getContext().filesDir + '/testSocket'
4147let localAddress : socket.LocalAddress = {
4148  address: sandboxPath
4149}
4150let connectOpt: socket.LocalConnectOptions = {
4151  address: localAddress,
4152  timeout: 6000
4153}
4154client.connect(connectOpt).then(() => {
4155  console.log('connect success')
4156}).catch((err: Object) => {
4157  console.error('connect failed: ' + JSON.stringify(err))
4158})
4159let sendOpt: socket.LocalSendOptions = {
4160  data: 'Hello world!'
4161}
4162client.send(sendOpt).then(() => {
4163  console.log('send success')
4164}).catch((err: Object) => {
4165  console.error('send fail: ' + JSON.stringify(err))
4166})
4167```
4168
4169### close<sup>11+</sup>
4170
4171close(): Promise\<void\>
4172
4173Closes a local socket connection. This API uses a promise to return the result.
4174
4175**System capability**: SystemCapability.Communication.NetStack
4176
4177**Return value**
4178
4179| Type           | Description                                      |
4180| :-------------- | :----------------------------------------- |
4181| Promise\<void\> | Promise used to return the result.|
4182
4183**Error codes**
4184
4185| ID| Error Message                |
4186| ------- | ----------------------- |
4187| 2301009 | Bad file descriptor.    |
4188
4189**Example**
4190
4191```ts
4192import { socket } from '@kit.NetworkKit';
4193
4194let client: socket.LocalSocket = socket.constructLocalSocketInstance();
4195
4196client.close().then(() => {
4197  console.log('close success');
4198}).catch((err: Object) => {
4199  console.error('close fail: ' + JSON.stringify(err));
4200});
4201```
4202
4203### getState<sup>11+</sup>
4204
4205getState(): Promise\<SocketStateBase\>
4206
4207Obtains the local socket connection status. This API uses a promise to return the result.
4208
4209> **NOTE**
4210> This API can be called only after **bind** or **connect** is successfully called.
4211
4212**System capability**: SystemCapability.Communication.NetStack
4213
4214**Return value**
4215
4216| Type                                         | Description                                    |
4217| :------------------------------------------- | :--------------------------------------- |
4218| Promise\<[SocketStateBase](#socketstatebase)\> | Promise used to return the result.|
4219
4220**Example**
4221
4222```ts
4223import { socket } from '@kit.NetworkKit';
4224
4225let client: socket.LocalSocket = socket.constructLocalSocketInstance();
4226let sandboxPath: string = getContext().filesDir + '/testSocket'
4227let localAddress : socket.LocalAddress = {
4228  address: sandboxPath
4229}
4230let connectOpt: socket.LocalConnectOptions = {
4231  address: localAddress,
4232  timeout: 6000
4233}
4234client.connect(connectOpt).then(() => {
4235  console.log('connect success');
4236  client.getState().then(() => {
4237    console.log('getState success');
4238  }).catch((err: Object) => {
4239    console.error('getState fail: ' + JSON.stringify(err))
4240  });
4241}).catch((err: Object) => {
4242  console.error('connect fail: ' + JSON.stringify(err));
4243});
4244```
4245
4246### getSocketFd<sup>11+</sup>
4247
4248getSocketFd(): Promise\<number\>
4249
4250Obtains the file descriptor of the **LocalSocket** object. This API uses a promise to return the result.
4251
4252> **NOTE**
4253> This API can be called only after **bind** or **connect** is successfully called.
4254> The file descriptor is allocated by the system kernel to uniquely identify the local socket in use.
4255
4256**System capability**: SystemCapability.Communication.NetStack
4257
4258**Return value**
4259
4260| Type              | Description                             |
4261| :---------------- | :-------------------------------- |
4262| Promise\<number\> | Promise used to return the result.|
4263
4264**Example**
4265
4266```ts
4267import { socket } from '@kit.NetworkKit';
4268
4269let client: socket.LocalSocket = socket.constructLocalSocketInstance();
4270let sandboxPath: string = getContext().filesDir + '/testSocket'
4271let localAddress : socket.LocalAddress = {
4272  address: sandboxPath
4273}
4274let connectOpt: socket.LocalConnectOptions = {
4275  address: localAddress,
4276  timeout: 6000
4277}
4278client.connect(connectOpt).then(() => {
4279  console.log('connect ok')
4280}).catch((err: Object) => {
4281  console.error('connect fail: ' + JSON.stringify(err))
4282})
4283client.getSocketFd().then((data: number) => {
4284  console.info("fd: " + data);
4285}).catch((err: Object) => {
4286  console.error("getSocketFd faile: " + JSON.stringify(err));
4287})
4288```
4289
4290### setExtraOptions<sup>11+</sup>
4291
4292setExtraOptions(options: ExtraOptionsBase): Promise\<void\>
4293
4294Sets other properties of the local socket connection. This API uses a promise to return the result.
4295
4296> **NOTE**
4297> This API can be called only after **bind** or **connect** is successfully called.
4298
4299**System capability**: SystemCapability.Communication.NetStack
4300
4301**Parameters**
4302
4303| Name | Type                                     | Mandatory| Description                                                        |
4304| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
4305| options | [ExtraOptionsBase](#extraoptionsbase7) | Yes  | Other properties of the local socket connection. For details, see [ExtraOptionsBase](#extraoptionsbase7).|
4306
4307**Return value**
4308
4309| Type           | Description                                          |
4310| :-------------- | :-------------------------------------------- |
4311| Promise\<void\> | Promise used to return the result.|
4312
4313**Error codes**
4314
4315| ID| Error Message                |
4316| ------- | ----------------------- |
4317| 401     | Parameter error.        |
4318| 2301009 | Bad file descriptor.    |
4319
4320**Example**
4321
4322```ts
4323import { socket } from '@kit.NetworkKit';
4324
4325let client: socket.LocalSocket = socket.constructLocalSocketInstance();
4326let sandboxPath: string = getContext().filesDir + '/testSocket'
4327let localAddress : socket.LocalAddress = {
4328  address: sandboxPath
4329}
4330let connectOpt: socket.LocalConnectOptions = {
4331  address: localAddress,
4332  timeout: 6000
4333}
4334client.connect(connectOpt).then(() => {
4335  console.log('connect success');
4336  let options: socket.ExtraOptionsBase = {
4337    receiveBufferSize: 8000,
4338    sendBufferSize: 8000,
4339    socketTimeout: 3000
4340  }
4341  client.setExtraOptions(options).then(() => {
4342    console.log('setExtraOptions success');
4343  }).catch((err: Object) => {
4344    console.error('setExtraOptions fail: ' + JSON.stringify(err));
4345  });
4346}).catch((err: Object) => {
4347  console.error('connect fail: ' + JSON.stringify(err));
4348});
4349```
4350
4351### getExtraOptions<sup>11+</sup>
4352
4353getExtraOptions(): Promise\<ExtraOptionsBase\>;
4354
4355Obtains other properties of the local socket connection. This API uses a promise to return the result.
4356
4357> **NOTE**
4358> This API can be called only after **bind** or **connect** is successfully called.
4359
4360**System capability**: SystemCapability.Communication.NetStack
4361
4362**Return value**
4363
4364| Type                        | Description                                     |
4365| :-------------------------- | :---------------------------------------- |
4366| Promise\<[ExtraOptionsBase](#extraoptionsbase7)\> | Promise used to return the result.|
4367
4368**Error codes**
4369
4370| ID| Error Message                |
4371| ------- | ----------------------- |
4372| 2301009 | Bad file descriptor.    |
4373
4374**Example**
4375
4376```ts
4377import { socket } from '@kit.NetworkKit';
4378
4379let client: socket.LocalSocket = socket.constructLocalSocketInstance();
4380let sandboxPath: string = getContext().filesDir + '/testSocket'
4381let localAddress : socket.LocalAddress = {
4382  address: sandboxPath
4383}
4384let connectOpt: socket.LocalConnectOptions = {
4385  address: localAddress,
4386  timeout: 6000
4387}
4388client.connect(connectOpt).then(() => {
4389  console.log('connect success');
4390  client.getExtraOptions().then((options : socket.ExtraOptionsBase) => {
4391    console.log('options: ' + JSON.stringify(options));
4392  }).catch((err: Object) => {
4393    console.error('setExtraOptions fail: ' + JSON.stringify(err));
4394  });
4395}).catch((err: Object) => {
4396  console.error('connect fail: ' + JSON.stringify(err));
4397});
4398```
4399
4400### getLocalAddress<sup>12+</sup>
4401
4402getLocalAddress(): Promise\<string\>
4403
4404Obtains the local socket address of a **LocalSocket** connection. This API uses a promise to return the result.
4405
4406> **NOTE**
4407> This API can be called only after **bind** is successfully called.
4408
4409**System capability**: SystemCapability.Communication.NetStack
4410
4411**Return value**
4412
4413| Type           | Description                                                |
4414|  -------------- |  --------------------------------------------------- |
4415| Promise\<string\> | Promise used to return the result.|
4416
4417**Error codes**
4418
4419| ID| Error Message                                   |
4420| -------- | ------------------------------------------- |
4421| 2300002  | System internal error.                      |
4422| 2301009  | Bad file descriptor.                            |
4423| 2303188  | Socket operation on non-socket. |
4424
4425**Example**
4426
4427```ts
4428let client: socket.LocalSocket = socket.constructLocalSocketInstance();
4429let sandboxPath: string = getContext().filesDir + '/testSocket';
4430let address : socket.LocalAddress = {
4431  address: sandboxPath
4432}
4433client.bind(address).then(() => {
4434  console.error('bind success');
4435  client.getLocalAddress().then((localPath: string) => {
4436    console.info("SUCCESS " + JSON.stringify(localPath));
4437  }).catch((err: BusinessError) => {
4438    console.error("FAIL " + JSON.stringify(err));
4439  })
4440}).catch((err: Object) => {
4441  console.info('failed to bind: ' + JSON.stringify(err));
4442})
4443```
4444
4445### on('message')<sup>11+</sup>
4446
4447on(type: 'message', callback: Callback\<LocalSocketMessageInfo\>): void
4448
4449Subscribes to **message** events of a **LocalSocket** object. This API uses an asynchronous callback to return the result.
4450
4451**System capability**: SystemCapability.Communication.NetStack
4452
4453**Parameters**
4454
4455| Name  | Type                                             | Mandatory| Description                                     |
4456| -------- | ----------------------------------------------- | ---- | ----------------------------------- |
4457| type     | string                                          | Yes  | Event type.<br/> **message**: message receiving event.|
4458| callback | Callback\<[LocalSocketMessageInfo](#localsocketmessageinfo11)\> | Yes  | Callback used to return the result.|
4459
4460**Error codes**
4461
4462| ID| Error Message                |
4463| ------- | ----------------------- |
4464| 401     | Parameter error.        |
4465
4466**Example**
4467
4468```ts
4469import { socket } from '@kit.NetworkKit';
4470
4471let client: socket.LocalSocket = socket.constructLocalSocketInstance();
4472client.on('message', (value: socket.LocalSocketMessageInfo) => {
4473  const uintArray = new Uint8Array(value.message)
4474  let messageView = '';
4475  for (let i = 0; i < uintArray.length; i++) {
4476    messageView += String.fromCharCode(uintArray[i]);
4477  }
4478  console.log('total: ' + JSON.stringify(value));
4479  console.log('message infomation: ' + messageView);
4480});
4481```
4482
4483### off('message')<sup>11+</sup>
4484
4485off(type: 'message', callback?: Callback\<LocalSocketMessageInfo\>): void
4486
4487Unsubscribes from **message** events of a **LocalSocket** object. This API uses an asynchronous callback to return the result.
4488
4489**System capability**: SystemCapability.Communication.NetStack
4490
4491**Parameters**
4492
4493| Name  | Type                                              | Mandatory| Description                                |
4494| -------- | ------------------------------------------------ | ---- | ----------------------------------- |
4495| type     | string                                           | Yes  | Event type.<br/> **message**: message receiving event.|
4496| callback | Callback\<[LocalSocketMessageInfo](#localsocketmessageinfo11)\> | No  | Callback passed to the **on** function.|
4497
4498**Error codes**
4499
4500| ID| Error Message                |
4501| ------- | ----------------------- |
4502| 401     | Parameter error.        |
4503
4504**Example**
4505
4506```ts
4507import { socket } from '@kit.NetworkKit';
4508
4509let client: socket.LocalSocket = socket.constructLocalSocketInstance();
4510let messageView = '';
4511let callback = (value: socket.LocalSocketMessageInfo) => {
4512  const uintArray = new Uint8Array(value.message)
4513  let messageView = '';
4514  for (let i = 0; i < uintArray.length; i++) {
4515    messageView += String.fromCharCode(uintArray[i]);
4516  }
4517  console.log('total: ' + JSON.stringify(value));
4518  console.log('message infomation: ' + messageView);
4519}
4520client.on('message', callback);
4521client.off('message');
4522```
4523
4524### on('connect')<sup>11+</sup>
4525
4526on(type: 'connect', callback: Callback\<void\>): void;
4527
4528Subscribes to **connect** events of a **LocalSocket** object. This API uses an asynchronous callback to return the result.
4529
4530**System capability**: SystemCapability.Communication.NetStack
4531
4532**Parameters**
4533
4534| Name  | Type            | Mandatory| Description                                                        |
4535| -------- | ---------------- | ---- | --------------------------------------------------------- |
4536| type     | string           | Yes  | Event type.<br/>                                            |
4537| callback | Callback\<void\> | Yes  | Callback used to return the result.                    |
4538
4539**Error codes**
4540
4541| ID| Error Message                |
4542| ------- | ----------------------- |
4543| 401     | Parameter error.        |
4544
4545**Example**
4546
4547```ts
4548import { socket } from '@kit.NetworkKit';
4549
4550let client: socket.LocalSocket = socket.constructLocalSocketInstance();
4551client.on('connect', () => {
4552  console.log("on connect success")
4553});
4554```
4555
4556### off('connect')<sup>11+</sup>
4557
4558off(type: 'connect', callback?: Callback\<void\>): void;
4559
4560Unsubscribes from **connect** events of a **LocalSocket** object. This API uses an asynchronous callback to return the result.
4561
4562**System capability**: SystemCapability.Communication.NetStack
4563
4564**Parameters**
4565
4566| Name  | Type            | Mandatory| Description                                                        |
4567| -------- | ---------------- | ---- | --------------------------------------------------------- |
4568| type     | string           | Yes  | Event type.<br/>                                            |
4569| callback | Callback\<void\> | No  | Callback passed to the **on** function.                          |
4570
4571**Error codes**
4572
4573| ID| Error Message                |
4574| ------- | ----------------------- |
4575| 401     | Parameter error.        |
4576
4577**Example**
4578
4579```ts
4580import { socket } from '@kit.NetworkKit';
4581
4582let client: socket.LocalSocket = socket.constructLocalSocketInstance();
4583let callback = () => {
4584  console.log("on connect success");
4585}
4586client.on('connect', callback);
4587// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
4588client.off('connect', callback);
4589client.off('connect');
4590```
4591
4592### on('close')<sup>11+</sup>
4593
4594on(type: 'close', callback: Callback\<void\>): void;
4595
4596Subscribes to **close** events of a **LocalSocket** object. This API uses an asynchronous callback to return the result.
4597
4598**System capability**: SystemCapability.Communication.NetStack
4599
4600**Parameters**
4601
4602| Name  | Type            | Mandatory| Description                       |
4603| -------- | ---------------- | ---- | ------------------------ |
4604| type     | string           | Yes  | Event type.|
4605| callback | Callback\<void\> | Yes  | Callback used to return the result.|
4606
4607**Error codes**
4608
4609| ID| Error Message                |
4610| ------- | ----------------------- |
4611| 401     | Parameter error.        |
4612
4613**Example**
4614
4615```ts
4616import { socket } from '@kit.NetworkKit';
4617
4618let client: socket.LocalSocket = socket.constructLocalSocketInstance();
4619let callback = () => {
4620  console.log("on close success");
4621}
4622client.on('close', callback);
4623```
4624
4625### off('close')<sup>11+</sup>
4626
4627off(type: 'close', callback?: Callback\<void\>): void;
4628
4629Unsubscribes from **close** events of a **LocalSocket** object. This API uses an asynchronous callback to return the result.
4630
4631**System capability**: SystemCapability.Communication.NetStack
4632
4633**Parameters**
4634
4635| Name  | Type            | Mandatory| Description                       |
4636| -------- | ---------------- | ---- | ------------------------ |
4637| type     | string           | Yes  | Event type.|
4638| callback | Callback\<void\> | No  | Callback passed to the **on** function.|
4639
4640**Error codes**
4641
4642| ID| Error Message                |
4643| ------- | ----------------------- |
4644| 401     | Parameter error.        |
4645
4646**Example**
4647
4648```ts
4649import { socket } from '@kit.NetworkKit';
4650
4651let client: socket.LocalSocket = socket.constructLocalSocketInstance();
4652let callback = () => {
4653  console.log("on close success");
4654}
4655client.on('close', callback);
4656// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
4657client.off('close', callback);
4658client.off('close');
4659```
4660
4661### on('error')<sup>11+</sup>
4662
4663on(type: 'error', callback: ErrorCallback): void
4664
4665Subscribes to **error** events of a **LocalSocket** object. This API uses an asynchronous callback to return the result.
4666
4667**System capability**: SystemCapability.Communication.NetStack
4668
4669**Parameters**
4670
4671| Name  | Type         | Mandatory| Description                           |
4672| -------- | ------------- | ---- | ---------------------------- |
4673| type     | string        | Yes  | Event type.  |
4674| callback | ErrorCallback | Yes  | Callback used to return the result.|
4675
4676**Error codes**
4677
4678| ID| Error Message                |
4679| ------- | ----------------------- |
4680| 401     | Parameter error.        |
4681
4682**Example**
4683
4684```ts
4685import { socket } from '@kit.NetworkKit';
4686
4687let client: socket.LocalSocket = socket.constructLocalSocketInstance();
4688client.on('error', (err: Object) => {
4689  console.log("on error, err:" + JSON.stringify(err))
4690});
4691```
4692
4693### off('error')<sup>11+</sup>
4694
4695off(type: 'error', callback?: ErrorCallback): void;
4696
4697Unsubscribes from **error** events of a **LocalSocket** object. This API uses an asynchronous callback to return the result.
4698
4699**System capability**: SystemCapability.Communication.NetStack
4700
4701**Parameters**
4702
4703| Name  | Type         | Mandatory| Description                            |
4704| -------- | ------------- | ---- | ----------------------------- |
4705| type     | string        | Yes  | Event type.|
4706| callback | ErrorCallback | No  | Callback passed to the **on** function.|
4707
4708**Error codes**
4709
4710| ID| Error Message                |
4711| ------- | ----------------------- |
4712| 401     | Parameter error.        |
4713
4714**Example**
4715
4716```ts
4717import { socket } from '@kit.NetworkKit';
4718
4719let client: socket.LocalSocket = socket.constructLocalSocketInstance();
4720let callback = (err: Object) => {
4721  console.log("on error, err:" + JSON.stringify(err));
4722}
4723client.on('error', callback);
4724// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
4725client.off('error', callback);
4726client.off('error');
4727```
4728
4729## LocalSocketMessageInfo<sup>11+</sup>
4730
4731Defines the data received by the client over a local socket connection.
4732
4733**System capability**: SystemCapability.Communication.NetStack
4734
4735| Name    | Type           | Mandatory| Description              |
4736| ------- | --------------- | --- | ------------------ |
4737| message | ArrayBuffer     | Yes  | Data received.    |
4738| address | string          | Yes  | Local socket connection address.|
4739| size    | number          | Yes  | Data length.         |
4740
4741## LocalAddress<sup>11+</sup>
4742
4743Defines the address of a local socket file. When the address is passed for binding, a socket file is created at this address.
4744
4745**System capability**: SystemCapability.Communication.NetStack
4746
4747| Name    | Type      | Mandatory| Description              |
4748| ------- | ---------- | --- | ------------------ |
4749| address | string     | Yes  | Address of the local socket file.    |
4750
4751## LocalConnectOptions<sup>11+</sup>
4752
4753Defines local socket connection parameters.
4754
4755**System capability**: SystemCapability.Communication.NetStack
4756
4757| Name    | Type      | Mandatory| Description                           |
4758| ------- | ---------- | --- | ------------------------------ |
4759| address | [LocalAddress](#localaddress11)    | Yes  | Address of the local socket file.           |
4760| timeout | number     | No  | Timeout duration of the local socket connection, in ms. |
4761
4762## LocalSendOptions<sup>11+</sup>
4763
4764Defines the parameters for sending data over a local socket connection.
4765
4766**System capability**: SystemCapability.Communication.NetStack
4767
4768| Name    | Type      | Mandatory| Description                |
4769| ------- | ---------- | --- | ------------------- |
4770| data    | string \| ArrayBuffer | Yes  | Data to be transmitted.|
4771| encoding | string   | No  | Encoding format of the string. |
4772
4773## ExtraOptionsBase<sup>7+</sup>
4774
4775Defines other properties of the local socket connection.
4776
4777**System capability**: SystemCapability.Communication.NetStack
4778
4779| Name           | Type   | Mandatory| Description                             |
4780| ----------------- | ------- | ---- | ----------------------------- |
4781| receiveBufferSize | number  | No  | Size of the receive buffer, in bytes.    |
4782| sendBufferSize    | number  | No  | Size of the send buffer, in bytes.    |
4783| reuseAddress      | boolean | No  | Whether to reuse addresses. The value **true** means to reuse addresses, and the value **false** means the opposite.                  |
4784| socketTimeout     | number  | No  | Timeout duration of the local socket connection, in ms.   |
4785
4786## socket.constructLocalSocketServerInstance<sup>11+</sup>
4787
4788constructLocalSocketServerInstance(): LocalSocketServer
4789
4790Creates a **LocalSocketServer** object.
4791
4792**System capability**: SystemCapability.Communication.NetStack
4793
4794**Return value**
4795
4796| Type                               | Description                         |
4797| :---------------------------------- | :---------------------------- |
4798| [LocalSocketServer](#localsocketserver11) | **LocalSocketServer** object.|
4799
4800**Example**
4801
4802```ts
4803import { socket } from '@kit.NetworkKit';
4804let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance();
4805```
4806
4807## LocalSocketServer<sup>11+</sup>
4808
4809Defines a local socket server connection. Before calling LocalSocketServer APIs, you need to call [socket.constructLocalSocketServerInstance](#socketconstructlocalsocketserverinstance11) to create a **LocalSocketServer** object.
4810
4811### listen<sup>11+</sup>
4812
4813listen(address: LocalAddress): Promise\<void\>
4814
4815Binds the address of the local socket file. The server listens to and accepts local socket connections established over the socket. Multiple threads are used to process client data concurrently. This API uses a promise to return the result.
4816
4817> **NOTE**
4818> The server uses this API to complete the **bind**, **listen**, and **accept** operations. If the address of the local socket file is passed for binding, a socket file is automatically created when this API is called.
4819
4820**System capability**: SystemCapability.Communication.NetStack
4821
4822**Parameters**
4823
4824| Name | Type                     | Mandatory| Description                                         |
4825| ------- | ------------------------- | ---- | --------------------------------------------- |
4826| address | [LocalAddress](#localaddress11) | Yes  | Destination address.|
4827
4828**Return value**
4829
4830| Type           | Description                                                  |
4831| :-------------- | :---------------------------------------------------- |
4832| Promise\<void\> | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
4833
4834**Error codes**
4835
4836| ID| Error Message                     |
4837| -------- | --------------------------- |
4838| 401      | Parameter error.            |
4839| 2303109  | Bad file number.            |
4840| 2301013  | Insufficient permissions.   |
4841| 2301022  | Invalid argument.           |
4842| 2301098  | Address already in use.     |
4843
4844**Example**
4845
4846```ts
4847import { socket } from '@kit.NetworkKit';
4848
4849let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance();
4850let sandboxPath: string = getContext().filesDir + '/testSocket'
4851let addr: socket.LocalAddress = {
4852  address: sandboxPath
4853}
4854server.listen(addr).then(() => {
4855  console.log('listen success');
4856}).catch((err: Object) => {
4857  console.error('listen fail: ' + JSON.stringify(err));
4858});
4859```
4860
4861### getState<sup>11+</sup>
4862
4863getState(): Promise\<SocketStateBase\>
4864
4865Obtains the status of a local socket server connection. This API uses a promise to return the result.
4866
4867> **NOTE**
4868> This API can be called only after **listen** is successfully called.
4869
4870**System capability**: SystemCapability.Communication.NetStack
4871
4872**Return value**
4873
4874| Type                                        | Description                                           |
4875| :------------------------------------------- | :--------------------------------------------- |
4876| Promise\<[SocketStateBase](#socketstatebase)\> | Promise used to return the result.|
4877
4878**Example**
4879
4880```ts
4881import { socket } from '@kit.NetworkKit';
4882
4883let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance();
4884let sandboxPath: string = getContext().filesDir + '/testSocket'
4885let listenAddr: socket.LocalAddress = {
4886  address: sandboxPath
4887}
4888server.listen(listenAddr).then(() => {
4889  console.log("listen success");
4890}).catch((err: Object) => {
4891  console.error("listen fail: " + JSON.stringify(err));
4892})
4893server.getState().then((data: socket.SocketStateBase) => {
4894  console.log('getState success: ' + JSON.stringify(data));
4895}).catch((err: Object) => {
4896  console.error('getState fail: ' + JSON.stringify(err));
4897});
4898```
4899
4900### setExtraOptions<sup>11+</sup>
4901
4902setExtraOptions(options: ExtraOptionsBase): Promise\<void\>
4903
4904Sets other properties of the local socket server connection. This API uses a promise to return the result.
4905
4906> **NOTE**
4907> This API can be called only after **listen** is successfully called.
4908
4909**System capability**: SystemCapability.Communication.NetStack
4910
4911**Parameters**
4912
4913| Name | Type                                     | Mandatory| Description                           |
4914| ------- | --------------------------------------- | ---- | ------------------------------ |
4915| options | [ExtraOptionsBase](#extraoptionsbase7) | Yes  | Other properties of a local socket server connection.|
4916
4917**Return value**
4918
4919| Type           | Description                                            |
4920| :-------------- | :---------------------------------------------- |
4921| Promise\<void\> | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
4922
4923**Error codes**
4924
4925| ID| Error Message                       |
4926| -------- | ------------------------------- |
4927| 401      | Parameter error.                |
4928| 2301009  | Bad file descriptor.            |
4929
4930**Example**
4931
4932```ts
4933import { socket } from '@kit.NetworkKit';
4934
4935let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance();
4936let sandboxPath: string = getContext().filesDir + '/testSocket'
4937let listenAddr: socket.NetAddress = {
4938  address: sandboxPath
4939}
4940server.listen(listenAddr).then(() => {
4941  console.log("listen success");
4942}).catch((err: Object) => {
4943  console.error("listen fail: " + JSON.stringify(err));
4944})
4945
4946let options: socket.ExtraOptionsBase = {
4947  receiveBufferSize: 6000,
4948  sendBufferSize: 6000,
4949  socketTimeout: 3000
4950}
4951server.setExtraOptions(options).then(() => {
4952  console.log('setExtraOptions success');
4953}).catch((err: Object) => {
4954  console.error('setExtraOptions fail: ' + JSON.stringify(err));
4955});
4956```
4957
4958### getExtraOptions<sup>11+</sup>
4959
4960getExtraOptions(): Promise\<ExtraOptionsBase\>;
4961
4962Obtains other properties of a local socket server connection. This API uses a promise to return the result.
4963
4964> **NOTE**
4965> This API can be called only after **listen** is successfully called.
4966
4967**System capability**: SystemCapability.Communication.NetStack
4968
4969**Return value**
4970
4971| Type                        | Description                       |
4972| :-------------------------- | :-------------------------- |
4973| Promise\<[ExtraOptionsBase](#extraoptionsbase7)\> | Promise used to return the result.|
4974
4975**Error codes**
4976
4977| ID| Error Message              |
4978| -------- | -------------------- |
4979| 401     | Parameter error. |
4980
4981**Example**
4982
4983```ts
4984import { socket } from '@kit.NetworkKit';
4985
4986let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance();
4987let sandboxPath: string = getContext().filesDir + '/testSocket'
4988let listenAddr: socket.LocalAddress = {
4989  address: sandboxPath
4990}
4991server.listen(listenAddr).then(() => {
4992  console.log("listen success");
4993}).catch((err: Object) => {
4994  console.error("listen fail: " + JSON.stringify(err));
4995})
4996server.getExtraOptions().then((options: socket.ExtraOptionsBase) => {
4997  console.log('options: ' + JSON.stringify(options));
4998}).catch((err: Object) => {
4999  console.error('getExtraOptions fail: ' + JSON.stringify(err));
5000});
5001```
5002
5003### getLocalAddress<sup>12+</sup>
5004
5005getLocalAddress(): Promise\<string\>
5006
5007Obtains the local socket address of a **LocalSocketServer** connection. This API uses a promise to return the result.
5008
5009> **NOTE**
5010> This API can be called only after **listen** is successfully called.
5011
5012**System capability**: SystemCapability.Communication.NetStack
5013
5014**Return value**
5015
5016| Type           | Description                                                |
5017|  -------------- |  --------------------------------------------------- |
5018| Promise\<string\> | Promise used to return the result.|
5019
5020**Error codes**
5021
5022| ID| Error Message                                   |
5023| -------- | ------------------------------------------- |
5024| 2300002  | System internal error.                      |
5025| 2301009  | Bad file descriptor.                            |
5026| 2303188  | Socket operation on non-socket. |
5027
5028**Example**
5029
5030```ts
5031let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance();
5032let sandboxPath: string = getContext().filesDir + '/testSocket';
5033let listenAddr: socket.LocalAddress = {
5034  address: sandboxPath
5035}
5036server.listen(listenAddr).then(() => {
5037  console.info("listen success");
5038  server.getLocalAddress().then((localPath: string) => {
5039    console.info("SUCCESS " + JSON.stringify(localPath));
5040  }).catch((err: BusinessError) => {
5041    console.error("FAIL " + JSON.stringify(err));
5042  })
5043}).catch((err: Object) => {
5044  console.error("listen fail: " + JSON.stringify(err));
5045})
5046
5047```
5048
5049### on('connect')<sup>11+</sup>
5050
5051on(type: 'connect', callback: Callback\<LocalSocketConnection\>): void
5052
5053Subscribes to **connect** events of a **LocalSocketServer** object. This API uses an asynchronous callback to return the result.
5054
5055> **NOTE**
5056> This API can be called only after **listen** is successfully called.
5057
5058**System capability**: SystemCapability.Communication.NetStack
5059
5060**Parameters**
5061
5062| Name  | Type                           | Mandatory| Description                                 |
5063| -------- | ------------------------------- | ---- | ------------------------------------- |
5064| type     | string                          | Yes  | Event type.<br/> **connect**: connection event.|
5065| callback | Callback\<[LocalSocketConnection](#localsocketconnection11)\> | Yes  | Callback used to return the result.|
5066
5067**Error codes**
5068
5069| ID| Error Message        |
5070| -------- | ---------------- |
5071| 401      | Parameter error. |
5072
5073**Example**
5074
5075```ts
5076import { socket } from '@kit.NetworkKit';
5077
5078let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance();
5079server.on('connect', (connection: socket.LocalSocketConnection) => {
5080  if (connection) {
5081    console.log('accept a client')
5082  }
5083});
5084```
5085
5086### off('connect')<sup>11+</sup>
5087
5088off(type: 'connect', callback?: Callback\<LocalSocketConnection\>): void
5089
5090Unsubscribes from **connect** events of a **LocalSocketServer** object. This API uses an asynchronous callback to return the result.
5091
5092**System capability**: SystemCapability.Communication.NetStack
5093
5094**Parameters**
5095
5096| Name  | Type                           | Mandatory| Description                                 |
5097| -------- | ------------------------------- | ---- | ------------------------------------- |
5098| type     | string                          | Yes  | Event type.<br/> **connect**: connection event.|
5099| callback | Callback\<[LocalSocketConnection](#localsocketconnection11)\> | No  | Callback passed to the **on** function.|
5100
5101**Error codes**
5102
5103| ID| Error Message        |
5104| -------- | ---------------- |
5105| 401      | Parameter error. |
5106
5107**Example**
5108
5109```ts
5110import { socket } from '@kit.NetworkKit';
5111
5112let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance();
5113let callback = (connection: socket.LocalSocketConnection) => {
5114  if (connection) {
5115    console.log('accept a client')
5116  }
5117}
5118server.on('connect', callback);
5119// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
5120server.off('connect', callback);
5121server.off('connect');
5122```
5123
5124### on('error')<sup>11+</sup>
5125
5126on(type: 'error', callback: ErrorCallback): void
5127
5128Subscribes to **error** events of a **LocalSocketServer** object. This API uses an asynchronous callback to return the result.
5129
5130> **NOTE**
5131> This API can be called only after **listen** is successfully called.
5132
5133**System capability**: SystemCapability.Communication.NetStack
5134
5135**Parameters**
5136
5137| Name  | Type         | Mandatory| Description                                |
5138| -------- | ------------- | ---- | ------------------------------------ |
5139| type     | string        | Yes  | Event type.<br/> **error**: error event.|
5140| callback | ErrorCallback | Yes  | Callback used to return the result.|
5141
5142**Error codes**
5143
5144| ID| Error Message        |
5145| -------- | ---------------- |
5146| 401      | Parameter error. |
5147
5148**Example**
5149
5150```ts
5151import { socket } from '@kit.NetworkKit';
5152
5153let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance();
5154server.on('error', (err: Object) => {
5155  console.error("on error, err:" + JSON.stringify(err))
5156});
5157```
5158
5159### off('error')<sup>11+</sup>
5160
5161off(type: 'error', callback?: ErrorCallback): void
5162
5163Unsubscribes from **error** events of a **LocalSocketServer** object. This API uses an asynchronous callback to return the result.
5164
5165**System capability**: SystemCapability.Communication.NetStack
5166
5167**Parameters**
5168
5169| Name  | Type         | Mandatory| Description                                |
5170| -------- | ------------- | ---- | ------------------------------------ |
5171| type     | string        | Yes  | Event type.<br/> **error**: error event.|
5172| callback | ErrorCallback | No  | Callback passed to the **on** function.  |
5173
5174**Error codes**
5175
5176| ID| Error Message        |
5177| -------- | ---------------- |
5178| 401      | Parameter error. |
5179
5180**Example**
5181
5182```ts
5183import { socket } from '@kit.NetworkKit';
5184
5185let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance();
5186let callback = (err: Object) => {
5187  console.error("on error, err:" + JSON.stringify(err));
5188}
5189server.on('error', callback);
5190// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
5191server.off('error', callback);
5192server.off('error');
5193```
5194
5195
5196## LocalSocketConnection<sup>11+</sup>
5197
5198Defines a local socket connection, that is, the session between the local socket client and the server. Before calling LocalSocketConnection APIs, you need to obtain a **LocalSocketConnection** object.
5199
5200> **NOTE**
5201> The LocalSocketConnection client can call related APIs through the **LocalSocketConnection** object only after a connection is successfully established between the local socket client and the server.
5202
5203**System capability**: SystemCapability.Communication.NetStack
5204
5205### Attributes
5206
5207| Name    | Type  | Mandatory| Description                           |
5208| -------- | ------ | ---- | ---------------------------- |
5209| clientId | number | Yes  | ID of the session between the client and the server.|
5210
5211### send<sup>11+</sup>
5212
5213send(options: LocalSendOptions): Promise\<void\>
5214
5215Sends data through a local socket connection. This API uses a promise to return the result.
5216
5217> **NOTE**
5218> This API can be used only after the server obtains a **LocalSocketConnection** object through the **callback** of the **connect** event.
5219
5220**System capability**: SystemCapability.Communication.NetStack
5221
5222**Parameters**
5223
5224| Name | Type                             | Mandatory| Description                                                        |
5225| ------- | --------------------------------- | ---- | -------------------------------------- |
5226| options | [LocalSendOptions](#localsendoptions11) | Yes  | Defines the parameters for sending data over a local socket connection.|
5227
5228**Return value**
5229
5230| Type           | Description                                            |
5231| :-------------- | :---------------------------------------------- |
5232| Promise\<void\> | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
5233
5234**Error codes**
5235
5236| ID| Error Message              |
5237| -------- | ---------------------- |
5238| 401      | Parameter error.       |
5239| 2301011  | Operation would block. |
5240
5241**Example**
5242
5243```ts
5244import { socket } from '@kit.NetworkKit';
5245
5246let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance();
5247
5248server.on('connect', (connection: socket.LocalSocketConnection) => {
5249  let sendOptions: socket.LocalSendOptions = {
5250    data: 'Hello, client!'
5251  }
5252  connection.send(sendOptions).then(() => {
5253    console.log('send success');
5254  }).catch((err: Object) => {
5255    console.error('send fail: ' + JSON.stringify(err));
5256  });
5257});
5258```
5259
5260### close<sup>11+</sup>
5261
5262close(): Promise\<void\>
5263
5264Closes a local socket connection. This API uses a promise to return the result.
5265
5266**System capability**: SystemCapability.Communication.NetStack
5267
5268**Return value**
5269
5270| Type           | Description                                        |
5271| :-------------- | :------------------------------------------- |
5272| Promise\<void\> | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
5273
5274**Error codes**
5275
5276| ID| Error Message              |
5277| -------- | -------------------- |
5278| 2301009  | Bad file descriptor. |
5279
5280**Example**
5281
5282```ts
5283import { socket } from '@kit.NetworkKit';
5284
5285let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance();
5286server.on('connect', (connection: socket.LocalSocketConnection) => {
5287  connection.close().then(() => {
5288    console.log('close success');
5289  }).catch((err: Object) => {
5290    console.error('close fail: ' + JSON.stringify(err));
5291  });
5292});
5293```
5294
5295### getLocalAddress<sup>12+</sup>
5296
5297getLocalAddress(): Promise\<string\>
5298
5299Obtains the local socket address of a **LocalSocketConnection** connection. This API uses a promise to return the result.
5300
5301**System capability**: SystemCapability.Communication.NetStack
5302
5303**Return value**
5304
5305| Type           | Description                                                |
5306|  -------------- |  --------------------------------------------------- |
5307| Promise\<string\> | Promise used to return the result.|
5308
5309**Error codes**
5310
5311| ID| Error Message                                   |
5312| -------- | ------------------------------------------- |
5313| 2300002  | System internal error.                      |
5314| 2301009  | Bad file descriptor.                            |
5315| 2303188  | Socket operation on non-socket. |
5316
5317**Example**
5318
5319```ts
5320let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance();
5321let sandboxPath: string = getContext().filesDir + '/testSocket';
5322let localAddr: socket.LocalAddress = {
5323  address: sandboxPath
5324}
5325server.listen(localAddr).then(() => {
5326  console.info('listen success');
5327  let client: socket.LocalSocket = socket.constructLocalSocketInstance();
5328  let connectOpt: socket.LocalConnectOptions = {
5329    address: localAddr,
5330    timeout: 6000
5331  }
5332  client.connect(connectOpt).then(() => {
5333    server.getLocalAddress().then((localPath: string) => {
5334      console.info("success, localPath is" + JSON.stringify(localPath));
5335    }).catch((err: BusinessError) => {
5336      console.error("FAIL " + JSON.stringify(err));
5337    })
5338  }).catch((err: Object) => {
5339    console.error('connect fail: ' + JSON.stringify(err));
5340  });
5341});
5342```
5343
5344### on('message')<sup>11+</sup>
5345
5346on(type: 'message', callback: Callback\<LocalSocketMessageInfo\>): void;
5347
5348Subscribes to **message** events of a **LocalSocketConnection** object. This API uses an asynchronous callback to return the result.
5349
5350**System capability**: SystemCapability.Communication.NetStack
5351
5352**Parameters**
5353
5354| Name  | Type                                             | Mandatory| Description                                    |
5355| -------- | ----------------------------------------------- | ---- | --------------------------------------- |
5356| type     | string                                          | Yes  | Event type.<br/> **message**: message receiving event.    |
5357| callback | Callback\<[LocalSocketMessageInfo](#localsocketmessageinfo11)\> | Yes  | Callback used to return the result.|
5358
5359**Error codes**
5360
5361| ID| Error Message        |
5362| -------- | ---------------- |
5363| 401      | Parameter error. |
5364
5365**Example**
5366
5367```ts
5368import { socket } from '@kit.NetworkKit';
5369
5370let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance();
5371let sandboxPath: string = getContext().filesDir + '/testSocket'
5372let listenAddr: socket.LocalAddress = {
5373  address: sandboxPath
5374}
5375server.listen(listenAddr).then(() => {
5376  console.log("listen success");
5377}).catch((err: Object) => {
5378  console.error("listen fail: " + JSON.stringify(err));
5379});
5380server.on('connect', (connection: socket.LocalSocketConnection) => {
5381  connection.on('message', (value: socket.LocalSocketMessageInfo) => {
5382    const uintArray = new Uint8Array(value.message);
5383    let messageView = '';
5384    for (let i = 0; i < uintArray.length; i++) {
5385      messageView += String.fromCharCode(uintArray[i]);
5386    }
5387    console.log('total: ' + JSON.stringify(value));
5388    console.log('message infomation: ' + messageView);
5389  });
5390});
5391```
5392
5393### off('message')<sup>11+</sup>
5394
5395off(type: 'message', callback?: Callback\<LocalSocketMessageInfo\>): void
5396
5397Unsubscribes from **message** events of a **LocalSocketConnection** object. This API uses an asynchronous callback to return the result.
5398
5399**System capability**: SystemCapability.Communication.NetStack
5400
5401**Parameters**
5402
5403| Name  | Type                                             | Mandatory| Description                                |
5404| -------- | ----------------------------------------------- | ---- | ----------------------------------- |
5405| type     | string                                          | Yes  | Event type.<br/> **message**: message receiving event.|
5406| callback | Callback\<[LocalSocketMessageInfo](#localsocketmessageinfo11)\> | No  | Callback passed to the **on** function.|
5407
5408**Error codes**
5409
5410| ID| Error Message        |
5411| -------- | ---------------- |
5412| 401      | Parameter error. |
5413
5414**Example**
5415
5416```ts
5417import { socket } from '@kit.NetworkKit';
5418
5419let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance();
5420let callback = (value: socket.LocalSocketMessageInfo) => {
5421  const uintArray = new Uint8Array(value.message)
5422  let messageView = '';
5423  for (let i = 0; i < uintArray.length; i++) {
5424    messageView += String.fromCharCode(uintArray[i]);
5425  }
5426  console.log('total: ' + JSON.stringify(value));
5427  console.log('message infomation: ' + messageView);
5428}
5429server.on('connect', (connection: socket.LocalSocketConnection) => {
5430  connection.on('message', callback);
5431  // You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
5432  connection.off('message', callback);
5433  connection.off('message');
5434});
5435```
5436
5437### on('close')<sup>11+</sup>
5438
5439on(type: 'close', callback: Callback\<void\>): void
5440
5441Unsubscribes from **close** events of a **LocalSocketConnection** object. This API uses an asynchronous callback to return the result.
5442
5443**System capability**: SystemCapability.Communication.NetStack
5444
5445**Parameters**
5446
5447| Name  | Type            | Mandatory| Description                               |
5448| -------- | ---------------- | ---- | ----------------------------------- |
5449| type     | string           | Yes  | Event type.<br/> **close**: close event.|
5450| callback | Callback\<void\> | Yes  | Callback used to return the result.|
5451
5452**Error codes**
5453
5454| ID| Error Message        |
5455| -------- | ---------------- |
5456| 401      | Parameter error. |
5457
5458**Example**
5459
5460```ts
5461import { socket } from '@kit.NetworkKit';
5462
5463let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance();
5464server.on('connect', (connection: socket.LocalSocketConnection) => {
5465  connection.on('close', () => {
5466    console.log("on close success")
5467  });
5468});
5469```
5470
5471### off('close')<sup>11+</sup>
5472
5473off(type: 'close', callback?: Callback\<void\>): void
5474
5475Unsubscribes from **close** events of a **LocalSocketConnection** object. This API uses an asynchronous callback to return the result.
5476
5477**System capability**: SystemCapability.Communication.NetStack
5478
5479**Parameters**
5480
5481| Name  | Type            | Mandatory| Description                               |
5482| -------- | ---------------- | ---- | ----------------------------------- |
5483| type     | string           | Yes  | Event type.<br/> **close**: close event.|
5484| callback | Callback\<void\> | No  | Callback passed to the **on** function.|
5485
5486**Error codes**
5487
5488| ID| Error Message        |
5489| -------- | ---------------- |
5490| 401      | Parameter error. |
5491
5492**Example**
5493
5494```ts
5495import { socket } from '@kit.NetworkKit';
5496
5497let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance();
5498let callback = () => {
5499  console.log("on close success");
5500}
5501server.on('connect', (connection: socket.LocalSocketConnection) => {
5502  connection.on('close', callback);
5503  // You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
5504  connection.off('close', callback);
5505  connection.off('close');
5506});
5507```
5508
5509### on('error')<sup>11+</sup>
5510
5511on(type: 'error', callback: ErrorCallback): void
5512
5513Subscribes to **error** events of a **LocalSocketConnection** object. This API uses an asynchronous callback to return the result.
5514
5515**System capability**: SystemCapability.Communication.NetStack
5516
5517**Parameters**
5518
5519| Name  | Type         | Mandatory| Description                                |
5520| -------- | ------------- | ---- | ------------------------------------ |
5521| type     | string        | Yes  | Event type.<br/> **error**: error event.|
5522| callback | ErrorCallback | Yes  | Callback used to return the result.|
5523
5524**Error codes**
5525
5526| ID| Error Message        |
5527| -------- | ---------------- |
5528| 401      | Parameter error. |
5529
5530**Example**
5531
5532```ts
5533import { socket } from '@kit.NetworkKit';
5534
5535let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance();
5536server.on('connect', (connection: socket.LocalSocketConnection) => {
5537  connection.on('error', (err: Object) => {
5538    console.error("on error, err:" + JSON.stringify(err))
5539  });
5540});
5541```
5542
5543### off('error')<sup>11+</sup>
5544
5545off(type: 'error', callback?: ErrorCallback): void
5546
5547Unsubscribes from **error** events of a **LocalSocketConnection** object. This API uses an asynchronous callback to return the result.
5548
5549**System capability**: SystemCapability.Communication.NetStack
5550
5551**Parameters**
5552
5553| Name  | Type         | Mandatory| Description                                |
5554| -------- | ------------- | ---- | ------------------------------------ |
5555| type     | string        | Yes  | Event type.<br/> **error**: error event.|
5556| callback | ErrorCallback | No  | Callback passed to the **on** function.  |
5557
5558**Error codes**
5559
5560| ID| Error Message        |
5561| -------- | ---------------- |
5562| 401      | Parameter error. |
5563
5564**Example**
5565
5566```ts
5567import { socket } from '@kit.NetworkKit';
5568
5569let callback = (err: Object) => {
5570  console.error("on error, err: " + JSON.stringify(err));
5571}
5572let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance();
5573server.on('connect', (connection: socket.LocalSocketConnection) => {
5574  connection.on('error', callback);
5575  // You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
5576  connection.off('error', callback);
5577  connection.off('error');
5578});
5579```
5580
5581## Description of LocalSocket Error Codes
5582
5583The LocalSocket error code mapping is in the format of 2301000 + Linux kernel error code.
5584
5585For details about error codes, see [Socket Error Codes](errorcode-net-socket.md).
5586
5587## socket.constructTLSSocketInstance<sup>9+</sup>
5588
5589constructTLSSocketInstance(): TLSSocket
5590
5591Creates a **TLSSocket** object.
5592
5593**System capability**: SystemCapability.Communication.NetStack
5594
5595**Return value**
5596
5597| Type                              | Description                   |
5598|  --------------------------------- |  ---------------------- |
5599| [TLSSocket](#tlssocket9) | **TLSSocket** object.|
5600
5601**Example**
5602
5603```ts
5604import { socket } from '@kit.NetworkKit';
5605
5606let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
5607```
5608
5609## socket.constructTLSSocketInstance<sup>12+</sup>
5610
5611constructTLSSocketInstance(tcpSocket: TCPSocket): TLSSocket
5612
5613Upgrades a **TCPSocket** connection to a **TLSSocket** connection.
5614
5615> **NOTE**
5616> Before calling **constructTLSSocketInstance**, ensure that a **TCPSocket** connection has been established and no data is transmitted. After a successful upgrade, you do not need to call the **close** API for the **TCPSocket** object.
5617
5618**System capability**: SystemCapability.Communication.NetStack
5619
5620**Parameters**
5621
5622| Name      | Type| Mandatory| Description                    |
5623|-----------|----| ---- |------------------------|
5624| tcpSocket | [TCPSocket](#tcpsocket)   | Yes  | **TCPSocket** connection to be upgraded.|
5625
5626**Return value**
5627
5628| Type                              | Description                   |
5629|  --------------------------------- |  ---------------------- |
5630| [TLSSocket](#tlssocket9) | **TLSSocket** object.|
5631
5632**Error codes**
5633
5634| ID  | Error Message                            |
5635|---------|----------------------------------|
5636| 401     | Parameter error.  |
5637| 2300002 | System internal error.  |
5638| 2303601 | Invalid socket FD.     |
5639| 2303602 | Socket is not connected.  |
5640
5641**Example**
5642
5643```ts
5644import { socket } from '@kit.NetworkKit';
5645import { BusinessError } from '@kit.BasicServicesKit';
5646
5647let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
5648let connAddress: socket.TCPConnectOptions = {
5649  address: '192.168.xx.xxx',
5650  port: 8080
5651};
5652let tcpconnectoptions: socket.TCPConnectOptions = {
5653  address: connAddress,
5654  timeout: 6000
5655}
5656
5657tcp.connect(tcpconnectoptions, (err: BusinessError) => {
5658  if (err) {
5659    console.log('connect fail');
5660    return;
5661  }
5662  console.log('connect success');
5663
5664  // Ensure that a TCPSocket connection has been established before upgrading it to a TLSSocket connection.
5665  let tls: socket.TLSSocket = socket.constructTLSSocketInstance(tcp);
5666})
5667```
5668
5669## TLSSocket<sup>9+</sup>
5670
5671Defines a TLS socket connection. Before calling TLSSocket APIs, you need to call [socket.constructTLSSocketInstance](#socketconstructtlssocketinstance9) to create a **TLSSocket** object.
5672
5673### bind<sup>9+</sup>
5674
5675bind(address: NetAddress, callback: AsyncCallback\<void\>): void
5676
5677Binds the IP address and port number. This API uses an asynchronous callback to return the result.
5678
5679> **NOTE**
5680> If the **TLSSocket** object is upgraded from a **TCPSocket** object, you do not need to execute the **bind** API.
5681
5682**Required permissions**: ohos.permission.INTERNET
5683
5684**System capability**: SystemCapability.Communication.NetStack
5685
5686**Parameters**
5687
5688| Name  | Type                              | Mandatory| Description                                                  |
5689| -------- | ---------------------------------- | ---- | ------------------------------------------------------ |
5690| address  | [NetAddress](#netaddress) | Yes  | Destination address. For details, see [NetAddress](#netaddress).|
5691| callback | AsyncCallback\<void\>              | Yes  | Callback used to return the result. If the operation is successful, the result of binding the local IP address and port number is returned. If the operation fails, an error message is returned.|
5692
5693**Error codes**
5694
5695| ID| Error Message                |
5696| ------- | ----------------------- |
5697| 401     | Parameter error.        |
5698| 201     | Permission denied.      |
5699| 2303198 | Address already in use. |
5700| 2300002 | System internal error.  |
5701
5702**Example**
5703
5704```ts
5705import { socket } from '@kit.NetworkKit';
5706import { BusinessError } from '@kit.BasicServicesKit';
5707
5708let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
5709let bindAddr: socket.NetAddress = {
5710  address: '192.168.xx.xxx',
5711  port: 8080
5712}
5713tls.bind(bindAddr, (err: BusinessError) => {
5714  if (err) {
5715    console.log('bind fail');
5716    return;
5717  }
5718  console.log('bind success');
5719});
5720```
5721
5722### bind<sup>9+</sup>
5723
5724bind(address: NetAddress): Promise\<void\>
5725
5726Binds the IP address and port number. This API uses a promise to return the result.
5727
5728> **NOTE**
5729> If the **TLSSocket** object is upgraded from a **TCPSocket** object, you do not need to execute the **bind** API.
5730
5731**Required permissions**: ohos.permission.INTERNET
5732
5733**System capability**: SystemCapability.Communication.NetStack
5734
5735**Parameters**
5736
5737| Name | Type                              | Mandatory| Description                                                  |
5738| ------- | ---------------------------------- | ---- | ------------------------------------------------------ |
5739| address | [NetAddress](#netaddress)          | Yes  | Destination address. For details, see [NetAddress](#netaddress).|
5740
5741**Return value**
5742
5743| Type           | Description                                                    |
5744|  -------------- |  ------------------------------------------------------- |
5745| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.|
5746
5747**Error codes**
5748
5749| ID| Error Message                |
5750| ------- | ----------------------- |
5751| 401     | Parameter error.        |
5752| 201     | Permission denied.      |
5753| 2303198 | Address already in use. |
5754| 2300002 | System internal error.  |
5755
5756**Example**
5757
5758```ts
5759import { socket } from '@kit.NetworkKit';
5760import { BusinessError } from '@kit.BasicServicesKit';
5761
5762let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
5763let bindAddr: socket.NetAddress = {
5764  address: '192.168.xx.xxx',
5765  port: 8080
5766}
5767tls.bind(bindAddr).then(() => {
5768  console.log('bind success');
5769}).catch((err: BusinessError) => {
5770  console.log('bind fail');
5771});
5772```
5773
5774### getState<sup>9+</sup>
5775
5776getState(callback: AsyncCallback\<SocketStateBase\>): void
5777
5778Obtains the status of the TLS socket connection. This API uses an asynchronous callback to return the result.
5779
5780**System capability**: SystemCapability.Communication.NetStack
5781
5782**Parameters**
5783
5784| Name  | Type                                                  | Mandatory| Description      |
5785| -------- | ------------------------------------------------------ | ---- | ---------- |
5786| callback | AsyncCallback\<[SocketStateBase](#socketstatebase)\> | Yes  | Callback used to return the result. If the operation is successful, the status of the TLS socket connection is returned. If the operation fails, an error message is returned.|
5787
5788**Error codes**
5789
5790| ID| Error Message                       |
5791| ------- | ------------------------------ |
5792| 2303188 | Socket operation on non-socket.|
5793| 2300002 | System internal error.         |
5794
5795**Example**
5796
5797```ts
5798import { socket } from '@kit.NetworkKit';
5799import { BusinessError } from '@kit.BasicServicesKit';
5800
5801let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
5802let bindAddr: socket.NetAddress = {
5803  address: '192.168.xx.xxx',
5804  port: 8080
5805}
5806tls.bind(bindAddr, (err: BusinessError) => {
5807  if (err) {
5808    console.log('bind fail');
5809    return;
5810  }
5811  console.log('bind success');
5812});
5813tls.getState((err: BusinessError, data: socket.SocketStateBase) => {
5814  if (err) {
5815    console.log('getState fail');
5816    return;
5817  }
5818  console.log('getState success:' + JSON.stringify(data));
5819});
5820```
5821
5822### getState<sup>9+</sup>
5823
5824getState(): Promise\<SocketStateBase\>
5825
5826Obtains the status of the TLS socket connection. This API uses a promise to return the result.
5827
5828**System capability**: SystemCapability.Communication.NetStack
5829
5830**Return value**
5831
5832| Type                                            | Description                                      |
5833|  ----------------------------------------------- |  ----------------------------------------- |
5834| Promise\<[SocketStateBase](#socketstatebase)\> | Promise used to return the result. If the operation fails, an error message is returned.|
5835
5836**Error codes**
5837
5838| ID| Error Message                       |
5839| ------- | ------------------------------ |
5840| 2303188 | Socket operation on non-socket.|
5841| 2300002 | System internal error.         |
5842
5843**Example**
5844
5845```ts
5846import { socket } from '@kit.NetworkKit';
5847import { BusinessError } from '@kit.BasicServicesKit';
5848
5849let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
5850let bindAddr: socket.NetAddress = {
5851  address: '192.168.xx.xxx',
5852  port: 8080
5853}
5854tls.bind(bindAddr, (err: BusinessError) => {
5855  if (err) {
5856    console.log('bind fail');
5857    return;
5858  }
5859  console.log('bind success');
5860});
5861tls.getState().then(() => {
5862  console.log('getState success');
5863}).catch((err: BusinessError) => {
5864  console.log('getState fail');
5865});
5866```
5867
5868### setExtraOptions<sup>9+</sup>
5869
5870setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\<void\>): void
5871
5872Sets other properties of the TCP socket connection after **bind** is successfully called. This API uses an asynchronous callback to return the result.
5873
5874**System capability**: SystemCapability.Communication.NetStack
5875
5876**Parameters**
5877
5878| Name  | Type                                     | Mandatory| Description                                                        |
5879| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
5880| options  | [TCPExtraOptions](#tcpextraoptions) | Yes  | Other properties of the TCP socket connection. For details, see [TCPExtraOptions](#tcpextraoptions).|
5881| callback | AsyncCallback\<void\>                     | Yes  | Callback used to return the result. If the operation is successful, the result of setting other properties of the TCP socket connection is returned. If the operation fails, an error message is returned.|
5882
5883**Error codes**
5884
5885| ID| Error Message                       |
5886| ------- | -----------------------------  |
5887| 401     | Parameter error.               |
5888| 2303188 | Socket operation on non-socket.|
5889| 2300002 | System internal error.         |
5890
5891**Example**
5892
5893```ts
5894import { socket } from '@kit.NetworkKit';
5895import { BusinessError } from '@kit.BasicServicesKit';
5896
5897let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
5898let bindAddr: socket.NetAddress = {
5899  address: '192.168.xx.xxx',
5900  port: 8080
5901}
5902tls.bind(bindAddr, (err: BusinessError) => {
5903  if (err) {
5904    console.log('bind fail');
5905    return;
5906  }
5907  console.log('bind success');
5908});
5909
5910interface SocketLinger {
5911  on: boolean;
5912  linger: number;
5913}
5914
5915let tcpExtraOptions: socket.TCPExtraOptions = {
5916  keepAlive: true,
5917  OOBInline: true,
5918  TCPNoDelay: true,
5919  socketLinger: { on: true, linger: 10 } as SocketLinger,
5920  receiveBufferSize: 1000,
5921  sendBufferSize: 1000,
5922  reuseAddress: true,
5923  socketTimeout: 3000
5924}
5925tls.setExtraOptions(tcpExtraOptions, (err: BusinessError) => {
5926  if (err) {
5927    console.log('setExtraOptions fail');
5928    return;
5929  }
5930  console.log('setExtraOptions success');
5931});
5932```
5933
5934### setExtraOptions<sup>9+</sup>
5935
5936setExtraOptions(options: TCPExtraOptions): Promise\<void\>
5937
5938Sets other properties of the TCP socket connection after **bind** is successfully called. This API uses a promise to return the result.
5939
5940**System capability**: SystemCapability.Communication.NetStack
5941
5942**Parameters**
5943
5944| Name | Type                                     | Mandatory| Description                                                        |
5945| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
5946| options | [TCPExtraOptions](#tcpextraoptions) | Yes  | Other properties of the TCP socket connection. For details, see [TCPExtraOptions](#tcpextraoptions).|
5947
5948**Return value**
5949
5950| Type           | Description                                                |
5951|  -------------- |  --------------------------------------------------- |
5952| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.|
5953
5954**Error codes**
5955
5956| ID| Error Message                       |
5957| ------- | ------------------------------ |
5958| 401     | Parameter error.               |
5959| 2303188 | Socket operation on non-socket.|
5960| 2300002 | System internal error.         |
5961
5962**Example**
5963
5964```ts
5965import { socket } from '@kit.NetworkKit';
5966import { BusinessError } from '@kit.BasicServicesKit';
5967
5968let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
5969let bindAddr: socket.NetAddress = {
5970  address: '192.168.xx.xxx',
5971  port: 8080
5972}
5973tls.bind(bindAddr, (err: BusinessError) => {
5974  if (err) {
5975    console.log('bind fail');
5976    return;
5977  }
5978  console.log('bind success');
5979});
5980
5981interface SocketLinger {
5982  on: boolean;
5983  linger: number;
5984}
5985
5986let tcpExtraOptions: socket.TCPExtraOptions = {
5987  keepAlive: true,
5988  OOBInline: true,
5989  TCPNoDelay: true,
5990  socketLinger: { on: true, linger: 10 } as SocketLinger,
5991  receiveBufferSize: 1000,
5992  sendBufferSize: 1000,
5993  reuseAddress: true,
5994  socketTimeout: 3000
5995}
5996tls.setExtraOptions(tcpExtraOptions).then(() => {
5997  console.log('setExtraOptions success');
5998}).catch((err: BusinessError) => {
5999  console.log('setExtraOptions fail');
6000});
6001```
6002
6003### on('message')<sup>9+</sup>
6004
6005on(type: 'message', callback: Callback\<SocketMessageInfo\>): void;
6006
6007Subscribes to **message** events of the TLS socket connection. This API uses an asynchronous callback to return the result.
6008
6009**System capability**: SystemCapability.Communication.NetStack
6010
6011**Parameters**
6012
6013| Name  | Type                                                        | Mandatory| Description                                     |
6014| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
6015| type     | string                                                       | Yes  | Event type.<br/> **message**: message receiving event.|
6016| callback | Callback\<[SocketMessageInfo](#socketmessageinfo11)\> | Yes  | Callback used to return the result.  |
6017
6018**Error codes**
6019
6020| ID| Error Message                       |
6021| ------- | ------------------------------ |
6022| 401     | Parameter error.               |
6023
6024**Example**
6025
6026```ts
6027import { socket } from '@kit.NetworkKit';
6028import { BusinessError } from '@kit.BasicServicesKit';
6029
6030let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
6031let messageView = '';
6032tls.on('message', (value: socket.SocketMessageInfo) => {
6033  for (let i: number = 0; i < value.message.byteLength; i++) {
6034    let uint8Array = new Uint8Array(value.message)
6035    let messages = uint8Array[i]
6036    let message = String.fromCharCode(messages);
6037    messageView += message;
6038  }
6039  console.log('on message message: ' + JSON.stringify(messageView));
6040  console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo));
6041});
6042```
6043
6044### off('message')<sup>9+</sup>
6045
6046off(type: 'message', callback?: Callback\<SocketMessageInfo\>): void
6047
6048Unsubscribes from **message** events of a **TLSSocket** object. This API uses an asynchronous callback to return the result.
6049
6050**System capability**: SystemCapability.Communication.NetStack
6051
6052**Parameters**
6053
6054| Name  | Type                                                        | Mandatory| Description                                     |
6055| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
6056| type     | string                                                       | Yes  | Event type.<br/> **message**: message receiving event.|
6057| callback | Callback\<[SocketMessageInfo](#socketmessageinfo11)\> | No  | Callback used to return the result.  |
6058
6059**Error codes**
6060
6061| ID| Error Message                       |
6062| ------- | ------------------------------ |
6063| 401     | Parameter error.               |
6064
6065**Example**
6066
6067```ts
6068import { socket } from '@kit.NetworkKit';
6069import { BusinessError } from '@kit.BasicServicesKit';
6070
6071let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
6072let messageView = '';
6073let callback = (value: socket.SocketMessageInfo) => {
6074  for (let i: number = 0; i < value.message.byteLength; i++) {
6075    let uint8Array = new Uint8Array(value.message)
6076    let messages = uint8Array[i]
6077    let message = String.fromCharCode(messages);
6078    messageView += message;
6079  }
6080  console.log('on message message: ' + JSON.stringify(messageView));
6081  console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo));
6082}
6083tls.on('message', callback);
6084// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
6085tls.off('message', callback);
6086```
6087### on('connect' | 'close')<sup>9+</sup>
6088
6089on(type: 'connect' | 'close', callback: Callback\<void\>): void
6090
6091Subscribes to **connect** or **close** events of the TLS socket connection. This API uses an asynchronous callback to return the result.
6092
6093**System capability**: SystemCapability.Communication.NetStack
6094
6095**Parameters**
6096
6097| Name  | Type            | Mandatory| Description                                                        |
6098| -------- | ---------------- | ---- | ------------------------------------------------------------ |
6099| type     | string           | Yes  | Event type.<br>- **connect**: connection event.<br>- **close**: close event.|
6100| callback | Callback\<void\> | Yes  | Callback used to return the result.                                                    |
6101
6102**Error codes**
6103
6104| ID| Error Message                       |
6105| ------- | ------------------------------ |
6106| 401     | Parameter error.               |
6107
6108**Example**
6109
6110```ts
6111import { socket } from '@kit.NetworkKit';
6112import { BusinessError } from '@kit.BasicServicesKit';
6113
6114let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
6115tls.on('connect', () => {
6116  console.log("on connect success")
6117});
6118tls.on('close', () => {
6119  console.log("on close success")
6120});
6121```
6122
6123### off('connect' | 'close')<sup>9+</sup>
6124
6125off(type: 'connect' | 'close', callback?: Callback\<void\>): void
6126
6127Unsubscribes from **connect** or **close** events of a **TLSSocket** object. This API uses an asynchronous callback to return the result.
6128
6129**System capability**: SystemCapability.Communication.NetStack
6130
6131**Parameters**
6132
6133| Name  | Type            | Mandatory| Description                                                        |
6134| -------- | ---------------- | ---- | ------------------------------------------------------------ |
6135| type     | string           | Yes  | Event type.<br>- **connect**: connection event.<br>- **close**: close event.|
6136| callback | Callback\<void\> | No  | Callback used to return the result.           |
6137
6138**Error codes**
6139
6140| ID| Error Message                       |
6141| ------- | ------------------------------ |
6142| 401     | Parameter error.               |
6143
6144**Example**
6145
6146```ts
6147import { socket } from '@kit.NetworkKit';
6148import { BusinessError } from '@kit.BasicServicesKit';
6149
6150let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
6151let callback1 = () => {
6152  console.log("on connect success");
6153}
6154tls.on('connect', callback1);
6155// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
6156tls.off('connect', callback1);
6157tls.off('connect');
6158let callback2 = () => {
6159  console.log("on close success");
6160}
6161tls.on('close', callback2);
6162// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
6163tls.off('close', callback2);
6164```
6165
6166### on('error')<sup>9+</sup>
6167
6168on(type: 'error', callback: ErrorCallback): void
6169
6170Subscribes to **error** events of the TLS socket connection. This API uses an asynchronous callback to return the result.
6171
6172**System capability**: SystemCapability.Communication.NetStack
6173
6174**Parameters**
6175
6176| Name  | Type         | Mandatory| Description                                |
6177| -------- | ------------- | ---- | ------------------------------------ |
6178| type     | string        | Yes  | Event type.<br/> **error**: error event.|
6179| callback | ErrorCallback | Yes  | Callback used to return the result.         |
6180
6181**Error codes**
6182
6183| ID| Error Message                       |
6184| ------- | ------------------------------ |
6185| 401     | Parameter error.               |
6186
6187**Example**
6188
6189```ts
6190import { socket } from '@kit.NetworkKit';
6191import { BusinessError } from '@kit.BasicServicesKit';
6192
6193let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
6194tls.on('error', (err: BusinessError) => {
6195  console.log("on error, err:" + JSON.stringify(err))
6196});
6197```
6198
6199### off('error')<sup>9+</sup>
6200
6201off(type: 'error', callback?: ErrorCallback): void
6202
6203Unsubscribes from **error** events of a **TLSSocket** object. This API uses an asynchronous callback to return the result.
6204
6205**System capability**: SystemCapability.Communication.NetStack
6206
6207**Parameters**
6208
6209| Name  | Type         | Mandatory| Description                                |
6210| -------- | ------------- | ---- | ------------------------------------ |
6211| type     | string        | Yes  | Event type.<br/> **error**: error event.|
6212| callback | ErrorCallback | No  | Callback used to return the result.                            |
6213
6214**Error codes**
6215
6216| ID| Error Message                       |
6217| ------- | ------------------------------ |
6218| 401     | Parameter error.               |
6219
6220**Example**
6221
6222```ts
6223import { socket } from '@kit.NetworkKit';
6224import { BusinessError } from '@kit.BasicServicesKit';
6225
6226let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
6227let callback = (err: BusinessError) => {
6228  console.log("on error, err:" + JSON.stringify(err));
6229}
6230tls.on('error', callback);
6231// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
6232tls.off('error', callback);
6233```
6234
6235### connect<sup>9+</sup>
6236
6237connect(options: TLSConnectOptions, callback: AsyncCallback\<void\>): void
6238
6239Sets up a TLS socket connection, and creates and initializes a TLS session after **bind** is successfully called. During this process, a TLS/SSL handshake is performed between the application and the server to implement data transmission. This API uses an asynchronous callback to return the result. Note that **ca** in **secureOptions** of the **options** parameter is mandatory in API version 11 or earlier. You need to enter the CA certificate of the server for certificate authentication. The certificate content starts with "-----BEGIN CERTIFICATE-----" and ends with "-----END CERTIFICATE-----". This field is optional since API version 12.
6240
6241**System capability**: SystemCapability.Communication.NetStack
6242
6243**Parameters**
6244
6245| Name  | Type                                  | Mandatory| Description|
6246| -------- | ---------------------------------------| ----| --------------- |
6247| options  | [TLSConnectOptions](#tlsconnectoptions9) | Yes  | Parameters required for the TLS socket connection.|
6248| callback | AsyncCallback\<void\>                  | Yes  | Callback used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
6249
6250**Error codes**
6251
6252| ID| Error Message                                     |
6253| ------- | -------------------------------------------- |
6254| 401     | Parameter error.                             |
6255| 2303104 | Interrupted system call.                     |
6256| 2303109 | Bad file number.                             |
6257| 2303111 | Resource temporarily unavailable. Try again. |
6258| 2303188 | Socket operation on non-socket.              |
6259| 2303191 | Incorrect socket protocol type.              |
6260| 2303198 | Address already in use.                      |
6261| 2303199 | Cannot assign requested address.             |
6262| 2303210 | Connection timed out.                        |
6263| 2303501 | SSL is null.                                 |
6264| 2303502 | An error occurred when reading data on the TLS socket.|
6265| 2303503 | An error occurred when writing data on the TLS socket.|
6266| 2303505 | An error occurred in the TLS system call.    |
6267| 2303506 | Failed to close the TLS connection.          |
6268| 2300002 | System internal error.                       |
6269| 2301206 | Socks5 failed to connect to the proxy server.  |
6270| 2301207 | Socks5 username or password is invalid.        |
6271| 2301208 | Socks5 failed to connect to the remote server. |
6272| 2301209 | Socks5 failed to negotiate the authentication method. |
6273| 2301210 | Socks5 failed to send the message.             |
6274| 2301211 | Socks5 failed to receive the message.          |
6275| 2301212 | Socks5 serialization error.                    |
6276| 2301213 | Socks5 deserialization error.                  |
6277
6278**Example**
6279
6280```ts
6281import { socket } from '@kit.NetworkKit';
6282import { BusinessError } from '@kit.BasicServicesKit';
6283
6284let tlsTwoWay: socket.TLSSocket = socket.constructTLSSocketInstance();  // Two way authentication
6285let bindAddr: socket.NetAddress = {
6286  address: '0.0.0.0',
6287}
6288tlsTwoWay.bind(bindAddr, (err: BusinessError) => {
6289  if (err) {
6290    console.log('bind fail');
6291    return;
6292  }
6293  console.log('bind success');
6294});
6295let twoWayNetAddr: socket.NetAddress = {
6296  address: '192.168.xx.xxx',
6297  port: 8080
6298}
6299let twoWaySecureOptions: socket.TLSSecureOptions = {
6300  key: "xxxx",
6301  cert: "xxxx",
6302  ca: ["xxxx"],
6303  password: "xxxx",
6304  protocols: socket.Protocol.TLSv12,
6305  useRemoteCipherPrefer: true,
6306  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
6307  cipherSuite: "AES256-SHA256"
6308}
6309let tlsConnectOptions: socket.TLSConnectOptions = {
6310  address: twoWayNetAddr,
6311  secureOptions: twoWaySecureOptions,
6312  ALPNProtocols: ["spdy/1", "http/1.1"]
6313}
6314
6315tlsTwoWay.connect(tlsConnectOptions, (err: BusinessError) => {
6316  console.error("connect callback error" + err);
6317});
6318
6319let tlsOneWay: socket.TLSSocket = socket.constructTLSSocketInstance(); // One way authentication
6320tlsOneWay.bind(bindAddr, (err: BusinessError) => {
6321  if (err) {
6322    console.log('bind fail');
6323    return;
6324  }
6325  console.log('bind success');
6326});
6327let oneWayNetAddr: socket.NetAddress = {
6328  address: '192.168.xx.xxx',
6329  port: 8080
6330}
6331let oneWaySecureOptions: socket.TLSSecureOptions = {
6332  ca: ["xxxx", "xxxx"],
6333  cipherSuite: "AES256-SHA256"
6334}
6335let tlsOneWayConnectOptions: socket.TLSConnectOptions = {
6336  address: oneWayNetAddr,
6337  secureOptions: oneWaySecureOptions
6338}
6339tlsOneWay.connect(tlsOneWayConnectOptions, (err: BusinessError) => {
6340  console.error("connect callback error" + err);
6341});
6342```
6343
6344**Example (with socket proxy):**
6345
6346```ts
6347import { socket } from '@kit.NetworkKit';
6348import { BusinessError } from '@kit.BasicServicesKit';
6349
6350let tlsTwoWay: socket.TLSSocket = socket.constructTLSSocketInstance(); // Two-way authentication
6351let bindAddr: socket.NetAddress = {
6352  address: '0.0.0.0',
6353}
6354tlsTwoWay.bind(bindAddr, (err: BusinessError) => {
6355  if (err) {
6356    console.log('bind fail');
6357    return;
6358  }
6359  console.log('bind success');
6360});
6361let twoWayNetAddr: socket.NetAddress = {
6362  address: '192.168.xx.xxx',
6363  port: 8080
6364}
6365let socks5Server: socket.NetAddress = {
6366  address: '192.168.xx.xxx',
6367  port: 8080
6368}
6369let twoWaySecureOptions: socket.TLSSecureOptions = {
6370  key: "xxxx",
6371  cert: "xxxx",
6372  ca: ["xxxx"],
6373  password: "xxxx",
6374  protocols: socket.Protocol.TLSv12,
6375  useRemoteCipherPrefer: true,
6376  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
6377  cipherSuite: "AES256-SHA256"
6378}
6379let tlsConnectOptions: socket.TLSConnectOptions = {
6380  address: twoWayNetAddr,
6381  secureOptions: twoWaySecureOptions,
6382  ALPNProtocols: ["spdy/1", "http/1.1"],
6383  proxy: socket.ProxyOptions = {
6384    type : 1,
6385    address: socks5Server,
6386    username: "xxx",
6387    password: "xxx"
6388  }
6389}
6390
6391tlsTwoWay.connect(tlsConnectOptions, (err: BusinessError) => {
6392  console.error("connect callback error" + err);
6393});
6394
6395let tlsOneWay: socket.TLSSocket = socket.constructTLSSocketInstance(); // One-way authentication
6396tlsOneWay.bind(bindAddr, (err: BusinessError) => {
6397  if (err) {
6398    console.log('bind fail');
6399    return;
6400  }
6401  console.log('bind success');
6402});
6403let oneWayNetAddr: socket.NetAddress = {
6404  address: '192.168.xx.xxx',
6405  port: 8080
6406}
6407let oneWaySecureOptions: socket.TLSSecureOptions = {
6408  ca: ["xxxx", "xxxx"],
6409  cipherSuite: "AES256-SHA256"
6410}
6411let tlsOneWayConnectOptions: socket.TLSConnectOptions = {
6412  address: oneWayNetAddr,
6413  secureOptions: oneWaySecureOptions,
6414  proxy: socket.ProxyOptions = {
6415    type : 1,
6416    address: socks5Server,
6417    username: "xxx",
6418    password: "xxx"
6419  }
6420}
6421tlsOneWay.connect(tlsOneWayConnectOptions, (err: BusinessError) => {
6422  console.error("connect callback error" + err);
6423});
6424```
6425
6426### connect<sup>9+</sup>
6427
6428connect(options: TLSConnectOptions): Promise\<void\>
6429
6430Sets up a TLS socket connection, and creates and initializes a TLS session after **bind** is successfully called. During this process, a TLS/SSL handshake is performed between the application and the server to implement data transmission. Both two-way and one-way authentication modes are supported. This API uses a promise to return the result. Note that **ca** in **secureOptions** of the **options** parameter is mandatory in API version 11 or earlier. You need to enter the CA certificate of the server for certificate authentication. The certificate content starts with "-----BEGIN CERTIFICATE-----" and ends with "-----END CERTIFICATE-----". This field is optional since API version 12.
6431
6432**System capability**: SystemCapability.Communication.NetStack
6433
6434**Parameters**
6435
6436| Name  | Type                                  | Mandatory| Description|
6437| -------- | --------------------------------------| ----| --------------- |
6438| options  | [TLSConnectOptions](#tlsconnectoptions9) | Yes  | Parameters required for the connection.|
6439
6440**Return value**
6441
6442| Type                                       | Description                         |
6443| ------------------------------------------- | ----------------------------- |
6444| Promise\<void\>                              | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
6445
6446**Error codes**
6447
6448| ID| Error Message                                     |
6449| ------- | -------------------------------------------- |
6450| 401     | Parameter error.                             |
6451| 2303104 | Interrupted system call.                     |
6452| 2303109 | Bad file number.                             |
6453| 2303111 | Resource temporarily unavailable. Try again. |
6454| 2303188 | Socket operation on non-socket.              |
6455| 2303191 | Incorrect socket protocol type.              |
6456| 2303198 | Address already in use.                      |
6457| 2303199 | Cannot assign requested address.             |
6458| 2303210 | Connection timed out.                        |
6459| 2303501 | SSL is null.                                 |
6460| 2303502 | An error occurred when reading data on the TLS socket.|
6461| 2303503 | An error occurred when writing data on the TLS socket.|
6462| 2303505 | An error occurred in the TLS system call.    |
6463| 2303506 | Failed to close the TLS connection.          |
6464| 2300002 | System internal error.                       |
6465| 2301206 | Socks5 failed to connect to the proxy server.  |
6466| 2301207 | Socks5 username or password is invalid.        |
6467| 2301208 | Socks5 failed to connect to the remote server. |
6468| 2301209 | Socks5 failed to negotiate the authentication method. |
6469| 2301210 | Socks5 failed to send the message.             |
6470| 2301211 | Socks5 failed to receive the message.          |
6471| 2301212 | Socks5 serialization error.                    |
6472| 2301213 | Socks5 deserialization error.                  |
6473
6474**Example**
6475
6476```ts
6477import { socket } from '@kit.NetworkKit';
6478import { BusinessError } from '@kit.BasicServicesKit';
6479
6480let tlsTwoWay: socket.TLSSocket = socket.constructTLSSocketInstance();  // Two way authentication
6481let bindAddr: socket.NetAddress = {
6482  address: '0.0.0.0',
6483}
6484tlsTwoWay.bind(bindAddr, (err: BusinessError) => {
6485  if (err) {
6486    console.log('bind fail');
6487    return;
6488  }
6489  console.log('bind success');
6490});
6491let twoWayNetAddr: socket.NetAddress = {
6492  address: '192.168.xx.xxx',
6493  port: 8080
6494}
6495let twoWaySecureOptions: socket.TLSSecureOptions = {
6496  key: "xxxx",
6497  cert: "xxxx",
6498  ca: ["xxxx"],
6499  password: "xxxx",
6500  protocols: socket.Protocol.TLSv12,
6501  useRemoteCipherPrefer: true,
6502  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
6503  cipherSuite: "AES256-SHA256"
6504}
6505let tlsConnectOptions: socket.TLSConnectOptions = {
6506  address: twoWayNetAddr,
6507  secureOptions: twoWaySecureOptions,
6508  ALPNProtocols: ["spdy/1", "http/1.1"]
6509}
6510
6511tlsTwoWay.connect(tlsConnectOptions).then(() => {
6512  console.log("connect successfully");
6513}).catch((err: BusinessError) => {
6514  console.log("connect failed " + JSON.stringify(err));
6515});
6516
6517let tlsOneWay: socket.TLSSocket = socket.constructTLSSocketInstance(); // One way authentication
6518tlsOneWay.bind(bindAddr, (err: BusinessError) => {
6519  if (err) {
6520    console.log('bind fail');
6521    return;
6522  }
6523  console.log('bind success');
6524});
6525let oneWayNetAddr: socket.NetAddress = {
6526  address: '192.168.xx.xxx',
6527  port: 8080
6528}
6529let oneWaySecureOptions: socket.TLSSecureOptions = {
6530  ca: ["xxxx", "xxxx"],
6531  cipherSuite: "AES256-SHA256"
6532}
6533let tlsOneWayConnectOptions: socket.TLSConnectOptions = {
6534  address: oneWayNetAddr,
6535  secureOptions: oneWaySecureOptions
6536}
6537tlsOneWay.connect(tlsOneWayConnectOptions).then(() => {
6538  console.log("connect successfully");
6539}).catch((err: BusinessError) => {
6540  console.log("connect failed " + JSON.stringify(err));
6541});
6542```
6543
6544**Example (with socket proxy):**
6545
6546```ts
6547import { socket } from '@kit.NetworkKit';
6548import { BusinessError } from '@kit.BasicServicesKit';
6549
6550let tlsTwoWay: socket.TLSSocket = socket.constructTLSSocketInstance(); // Two-way authentication
6551let bindAddr: socket.NetAddress = {
6552  address: '0.0.0.0',
6553}
6554tlsTwoWay.bind(bindAddr, (err: BusinessError) => {
6555  if (err) {
6556    console.log('bind fail');
6557    return;
6558  }
6559  console.log('bind success');
6560});
6561let twoWayNetAddr: socket.NetAddress = {
6562  address: '192.168.xx.xxx',
6563  port: 8080
6564}
6565let socks5Server: socket.NetAddress = {
6566  address: '192.168.xx.xxx',
6567  port: 8080
6568}
6569let twoWaySecureOptions: socket.TLSSecureOptions = {
6570  key: "xxxx",
6571  cert: "xxxx",
6572  ca: ["xxxx"],
6573  password: "xxxx",
6574  protocols: socket.Protocol.TLSv12,
6575  useRemoteCipherPrefer: true,
6576  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
6577  cipherSuite: "AES256-SHA256"
6578}
6579let tlsConnectOptions: socket.TLSConnectOptions = {
6580  address: twoWayNetAddr,
6581  secureOptions: twoWaySecureOptions,
6582  ALPNProtocols: ["spdy/1", "http/1.1"],
6583  proxy: socket.ProxyOptions = {
6584    type : 1,
6585    address: socks5Server,
6586    username: "xxx",
6587    password: "xxx"
6588  }
6589}
6590
6591tlsTwoWay.connect(tlsConnectOptions).then(() => {
6592  console.log("connect successfully");
6593}).catch((err: BusinessError) => {
6594  console.log("connect failed " + JSON.stringify(err));
6595});
6596
6597let tlsOneWay: socket.TLSSocket = socket.constructTLSSocketInstance(); // One-way authentication
6598tlsOneWay.bind(bindAddr, (err: BusinessError) => {
6599  if (err) {
6600    console.log('bind fail');
6601    return;
6602  }
6603  console.log('bind success');
6604});
6605let oneWayNetAddr: socket.NetAddress = {
6606  address: '192.168.xx.xxx',
6607  port: 8080
6608}
6609let oneWaySecureOptions: socket.TLSSecureOptions = {
6610  ca: ["xxxx", "xxxx"],
6611  cipherSuite: "AES256-SHA256"
6612}
6613let tlsOneWayConnectOptions: socket.TLSConnectOptions = {
6614  address: oneWayNetAddr,
6615  secureOptions: oneWaySecureOptions,
6616  proxy: socket.ProxyOptions = {
6617    type : 1,
6618    address: socks5Server,
6619    username: "xxx",
6620    password: "xxx"
6621  }
6622}
6623tlsOneWay.connect(tlsOneWayConnectOptions).then(() => {
6624  console.log("connect successfully");
6625}).catch((err: BusinessError) => {
6626  console.log("connect failed " + JSON.stringify(err));
6627});
6628```
6629
6630### getRemoteAddress<sup>9+</sup>
6631
6632getRemoteAddress(callback: AsyncCallback\<NetAddress\>): void
6633
6634Obtains the remote address of a TLS socket connection. This API uses an asynchronous callback to return the result.
6635
6636**System capability**: SystemCapability.Communication.NetStack
6637
6638**Parameters**
6639
6640| Name  | Type                                             | Mandatory| Description      |
6641| -------- | ------------------------------------------------- | ---- | ---------- |
6642| callback | AsyncCallback\<[NetAddress](#netaddress)\> | Yes  | Callback used to return the result. If the operation is successful, the remote address is returned. If the operation fails, an error message is returned.|
6643
6644**Error codes**
6645
6646| ID| Error Message                       |
6647| ------- | -----------------------------  |
6648| 2303188 | Socket operation on non-socket.|
6649| 2300002 | System internal error.         |
6650
6651**Example**
6652
6653```ts
6654import { socket } from '@kit.NetworkKit';
6655import { BusinessError } from '@kit.BasicServicesKit';
6656
6657let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
6658tls.getRemoteAddress((err: BusinessError, data: socket.NetAddress) => {
6659  if (err) {
6660    console.log('getRemoteAddress fail');
6661    return;
6662  }
6663  console.log('getRemoteAddress success:' + JSON.stringify(data));
6664});
6665```
6666
6667### getRemoteAddress<sup>9+</sup>
6668
6669getRemoteAddress(): Promise\<NetAddress\>
6670
6671Obtains the remote address of a TLS socket connection. This API uses a promise to return the result.
6672
6673**System capability**: SystemCapability.Communication.NetStack
6674
6675**Return value**
6676
6677| Type                                       | Description                                       |
6678|  ------------------------------------------ |  ------------------------------------------ |
6679| Promise\<[NetAddress](#netaddress)\> | Promise used to return the result. If the operation fails, an error message is returned.|
6680
6681**Error codes**
6682
6683| ID| Error Message                       |
6684| ------- | ------------------------------ |
6685| 2303188 | Socket operation on non-socket.|
6686| 2300002 | System internal error.         |
6687
6688**Example**
6689
6690```ts
6691import { socket } from '@kit.NetworkKit';
6692import { BusinessError } from '@kit.BasicServicesKit';
6693
6694let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
6695tls.getRemoteAddress().then(() => {
6696  console.log('getRemoteAddress success');
6697}).catch((err: BusinessError) => {
6698  console.log('getRemoteAddress fail');
6699});
6700```
6701
6702### getCertificate<sup>9+</sup>
6703
6704getCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)\>): void
6705
6706Obtains the local digital certificate after a TLS socket connection is established. This API is applicable to two-way authentication. It uses an asynchronous callback to return the result.
6707
6708**System capability**: SystemCapability.Communication.NetStack
6709
6710**Parameters**
6711
6712| Name  | Type                                  | Mandatory| Description|
6713| -------- | ----------------------------------------| ---- | ---------------|
6714| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)\>    | Yes  | Callback used to return the result. If the operation is successful, the local certificate is returned. If the operation fails, an error message is returned.|
6715
6716**Error codes**
6717
6718| ID| Error Message                       |
6719| ------- | ------------------------------ |
6720| 2303501 | SSL is null.                   |
6721| 2303504 | An error occurred when verifying the X.509 certificate.|
6722| 2300002 | System internal error.         |
6723
6724**Example**
6725
6726```ts
6727import { socket } from '@kit.NetworkKit';
6728import { BusinessError } from '@kit.BasicServicesKit';
6729
6730let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
6731tls.getCertificate((err: BusinessError, data: socket.X509CertRawData) => {
6732  if (err) {
6733    console.log("getCertificate callback error = " + err);
6734  } else {
6735    console.log("getCertificate callback = " + data);
6736  }
6737});
6738```
6739
6740### getCertificate<sup>9+</sup>
6741
6742getCertificate():Promise\<[X509CertRawData](#x509certrawdata9)\>
6743
6744Obtains the local digital certificate after a TLS socket connection is established. This API is applicable to two-way authentication. It uses a promise to return the result.
6745
6746**System capability**: SystemCapability.Communication.NetStack
6747
6748**Return value**
6749
6750| Type           | Description                 |
6751| -------------- | -------------------- |
6752| Promise\<[X509CertRawData](#x509certrawdata9)\> | Promise used to return the result. If the operation fails, an error message is returned.|
6753
6754**Error codes**
6755
6756| ID| Error Message                       |
6757| ------- | ------------------------------ |
6758| 2303501 | SSL is null.                   |
6759| 2303504 | An error occurred when verifying the X.509 certificate.|
6760| 2300002 | System internal error.         |
6761
6762**Example**
6763
6764```ts
6765import { socket } from '@kit.NetworkKit';
6766import { BusinessError } from '@kit.BasicServicesKit';
6767import { util } from '@kit.ArkTS';
6768
6769let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
6770tls.getCertificate().then((data: socket.X509CertRawData) => {
6771  const decoder = util.TextDecoder.create();
6772  const str = decoder.decodeWithStream(data.data);
6773  console.log("getCertificate: " + str);
6774}).catch((err: BusinessError) => {
6775  console.error("failed" + err);
6776});
6777```
6778
6779### getRemoteCertificate<sup>9+</sup>
6780
6781getRemoteCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)\>): void
6782
6783Obtains the digital certificate of the server after a TLS socket connection is established. This API uses an asynchronous callback to return the result.
6784
6785**System capability**: SystemCapability.Communication.NetStack
6786
6787**Parameters**
6788
6789| Name   | Type                                   | Mandatory | Description          |
6790| -------- | ----------------------------------------| ---- | ---------------|
6791| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)\>  | Yes  | Callback used to return the result. If the operation fails, an error message is returned.|
6792
6793**Error codes**
6794
6795| ID| Error Message                       |
6796| ------- | ------------------------------ |
6797| 2303501 | SSL is null.                   |
6798| 2300002 | System internal error.         |
6799
6800**Example**
6801
6802```ts
6803import { socket } from '@kit.NetworkKit';
6804import { BusinessError } from '@kit.BasicServicesKit';
6805import { util } from '@kit.ArkTS';
6806
6807let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
6808tls.getRemoteCertificate((err: BusinessError, data: socket.X509CertRawData) => {
6809  if (err) {
6810    console.log("getRemoteCertificate callback error = " + err);
6811  } else {
6812    const decoder = util.TextDecoder.create();
6813    const str = decoder.decodeWithStream(data.data);
6814    console.log("getRemoteCertificate callback = " + str);
6815  }
6816});
6817```
6818
6819### getRemoteCertificate<sup>9+</sup>
6820
6821getRemoteCertificate():Promise\<[X509CertRawData](#x509certrawdata9)\>
6822
6823Obtains the digital certificate of the server after a TLS socket connection is established. This API uses a promise to return the result.
6824
6825**System capability**: SystemCapability.Communication.NetStack
6826
6827**Return value**
6828
6829| Type           | Description                 |
6830| -------------- | -------------------- |
6831| Promise\<[X509CertRawData](#x509certrawdata9)\> | Promise used to return the result. If the operation fails, an error message is returned.|
6832
6833**Error codes**
6834
6835| ID| Error Message                       |
6836| ------- | ------------------------------ |
6837| 2303501 | SSL is null.                   |
6838| 2300002 | System internal error.         |
6839
6840**Example**
6841
6842```ts
6843import { socket } from '@kit.NetworkKit';
6844import { BusinessError } from '@kit.BasicServicesKit';
6845import { util } from '@kit.ArkTS';
6846
6847let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
6848tls.getRemoteCertificate().then((data: socket.X509CertRawData) => {
6849  const decoder = util.TextDecoder.create();
6850  const str = decoder.decodeWithStream(data.data);
6851  console.log("getRemoteCertificate:" + str);
6852}).catch((err: BusinessError) => {
6853  console.error("failed" + err);
6854});
6855```
6856
6857### getProtocol<sup>9+</sup>
6858
6859getProtocol(callback: AsyncCallback\<string\>): void
6860
6861Obtains the communication protocol version after a TLS socket connection is established. This API uses an asynchronous callback to return the result.
6862
6863**System capability**: SystemCapability.Communication.NetStack
6864
6865**Parameters**
6866
6867| Name  | Type                                      | Mandatory| Description          |
6868| -------- | ----------------------------------------| ---- | ---------------|
6869| callback | AsyncCallback\<string\>                  | Yes  | Callback used to return the result. If the operation fails, an error message is returned.|
6870
6871**Error codes**
6872
6873| ID| Error Message                       |
6874| ------- | -----------------------------  |
6875| 2303501 | SSL is null.                   |
6876| 2303505 | An error occurred in the TLS system call. |
6877| 2300002 | System internal error.         |
6878
6879**Example**
6880
6881```ts
6882import { socket } from '@kit.NetworkKit';
6883import { BusinessError } from '@kit.BasicServicesKit';
6884
6885let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
6886tls.getProtocol((err: BusinessError, data: string) => {
6887  if (err) {
6888    console.log("getProtocol callback error = " + err);
6889  } else {
6890    console.log("getProtocol callback = " + data);
6891  }
6892});
6893```
6894
6895### getProtocol<sup>9+</sup>
6896
6897getProtocol():Promise\<string\>
6898
6899Obtains the communication protocol version after a TLS socket connection is established. This API uses a promise to return the result.
6900
6901**System capability**: SystemCapability.Communication.NetStack
6902
6903**Return value**
6904
6905| Type           | Description                 |
6906| -------------- | -------------------- |
6907| Promise\<string\> | Promise used to return the result. If the operation fails, an error message is returned.|
6908
6909**Error codes**
6910
6911| ID| Error Message                       |
6912| ------- | ------------------------------ |
6913| 2303501 | SSL is null.                   |
6914| 2303505 | An error occurred in the TLS system call. |
6915| 2300002 | System internal error.         |
6916
6917**Example**
6918
6919```ts
6920import { socket } from '@kit.NetworkKit';
6921import { BusinessError } from '@kit.BasicServicesKit';
6922
6923let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
6924tls.getProtocol().then((data: string) => {
6925  console.log(data);
6926}).catch((err: BusinessError) => {
6927  console.error("failed" + err);
6928});
6929```
6930
6931### getCipherSuite<sup>9+</sup>
6932
6933getCipherSuite(callback: AsyncCallback\<Array\<string\>\>): void
6934
6935Obtains the cipher suite negotiated by both communication parties after a TLS socket connection is established. This API uses an asynchronous callback to return the result.
6936
6937**System capability**: SystemCapability.Communication.NetStack
6938
6939**Parameters**
6940
6941| Name  | Type                                    | Mandatory| Description|
6942| -------- | ----------------------------------------| ---- | ---------------|
6943| callback | AsyncCallback\<Array\<string\>\>          | Yes  | Callback used to return the result. If the operation fails, an error message is returned.|
6944
6945**Error codes**
6946
6947| ID| Error Message                       |
6948| ------- | ------------------------------ |
6949| 2303501 | SSL is null.                   |
6950| 2303502 | An error occurred when reading data on the TLS socket.|
6951| 2303505 | An error occurred in the TLS system call. |
6952| 2300002 | System internal error.         |
6953
6954**Example**
6955
6956```ts
6957import { socket } from '@kit.NetworkKit';
6958import { BusinessError } from '@kit.BasicServicesKit';
6959
6960let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
6961tls.getCipherSuite((err: BusinessError, data: Array<string>) => {
6962  if (err) {
6963    console.log("getCipherSuite callback error = " + err);
6964  } else {
6965    console.log("getCipherSuite callback = " + data);
6966  }
6967});
6968```
6969
6970### getCipherSuite<sup>9+</sup>
6971
6972getCipherSuite(): Promise\<Array\<string\>\>
6973
6974Obtains the cipher suite negotiated by both communication parties after a TLS socket connection is established. This API uses a promise to return the result.
6975
6976**System capability**: SystemCapability.Communication.NetStack
6977
6978**Return value**
6979
6980| Type                   | Description                 |
6981| ---------------------- | --------------------- |
6982| Promise\<Array\<string\>\> | Promise used to return the result. If the operation fails, an error message is returned.|
6983
6984**Error codes**
6985
6986| ID| Error Message                       |
6987| ------- | ------------------------------ |
6988| 2303501 | SSL is null.                   |
6989| 2303502 | An error occurred when reading data on the TLS socket.|
6990| 2303505 | An error occurred in the TLS system call. |
6991| 2300002 | System internal error.         |
6992
6993**Example**
6994
6995```ts
6996import { socket } from '@kit.NetworkKit';
6997import { BusinessError } from '@kit.BasicServicesKit';
6998
6999let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
7000tls.getCipherSuite().then((data: Array<string>) => {
7001  console.log('getCipherSuite success:' + JSON.stringify(data));
7002}).catch((err: BusinessError) => {
7003  console.error("failed" + err);
7004});
7005```
7006
7007### getSignatureAlgorithms<sup>9+</sup>
7008
7009getSignatureAlgorithms(callback: AsyncCallback\<Array\<string\>\>): void
7010
7011Obtains the signing algorithm negotiated by both communication parties after a TLS socket connection is established. This API is applicable to two-way authentication. It uses an asynchronous callback to return the result.
7012
7013**System capability**: SystemCapability.Communication.NetStack
7014
7015**Parameters**
7016
7017| Name  | Type                                  | Mandatory| Description           |
7018| -------- | -------------------------------------| ---- | ---------------|
7019| callback | AsyncCallback\<Array\<string\>\>         | Yes  | Callback used to return the result.  |
7020
7021**Error codes**
7022
7023| ID| Error Message                       |
7024| ------- | ------------------------------ |
7025| 2303501 | SSL is null.                   |
7026| 2300002 | System internal error.         |
7027
7028**Example**
7029
7030```ts
7031import { socket } from '@kit.NetworkKit';
7032import { BusinessError } from '@kit.BasicServicesKit';
7033
7034let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
7035tls.getSignatureAlgorithms((err: BusinessError, data: Array<string>) => {
7036  if (err) {
7037    console.log("getSignatureAlgorithms callback error = " + err);
7038  } else {
7039    console.log("getSignatureAlgorithms callback = " + data);
7040  }
7041});
7042```
7043
7044### getSignatureAlgorithms<sup>9+</sup>
7045
7046getSignatureAlgorithms(): Promise\<Array\<string\>\>
7047
7048Obtains the signing algorithm negotiated by both communication parties after a TLS socket connection is established. This API is applicable to two-way authentication. It uses a promise to return the result.
7049
7050**System capability**: SystemCapability.Communication.NetStack
7051
7052**Return value**
7053
7054| Type                   | Description                 |
7055| ---------------------- | -------------------- |
7056| Promise\<Array\<string\>\> | Promise used to return the result.|
7057
7058**Error codes**
7059
7060| ID| Error Message                       |
7061| ------- | ------------------------------ |
7062| 2303501 | SSL is null.                   |
7063| 2300002 | System internal error.         |
7064
7065**Example**
7066
7067```ts
7068import { socket } from '@kit.NetworkKit';
7069import { BusinessError } from '@kit.BasicServicesKit';
7070
7071let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
7072tls.getSignatureAlgorithms().then((data: Array<string>) => {
7073  console.log("getSignatureAlgorithms success" + data);
7074}).catch((err: BusinessError) => {
7075  console.error("failed" + err);
7076});
7077```
7078
7079### getLocalAddress<sup>12+</sup>
7080
7081getLocalAddress(): Promise\<NetAddress\>
7082
7083Obtains the local socket address of a **TLSSocket** connection. This API uses a promise to return the result.
7084
7085> **NOTE**
7086> Call this API only after the **TLSSocketServer** connection is successfully established.
7087
7088**System capability**: SystemCapability.Communication.NetStack
7089
7090**Return value**
7091
7092| Type           | Description                                                |
7093|  -------------- |  --------------------------------------------------- |
7094| Promise\<[NetAddress](#netaddress)\> | Promise used to return the result.|
7095
7096**Error codes**
7097
7098| ID| Error Message                                   |
7099| -------- | ------------------------------------------- |
7100| 2300002  | System internal error.                      |
7101| 2301009  | Bad file descriptor.                            |
7102| 2303188  | Socket operation on non-socket. |
7103
7104**Example**
7105
7106```ts
7107import { socket } from '@kit.NetworkKit';
7108import { BusinessError } from '@kit.BasicServicesKit';
7109
7110let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
7111tls.getLocalAddress().then((localAddress: socket.NetAddress) => {
7112  console.info("Get success: " + JSON.stringify(localAddress));
7113}).catch((err: BusinessError) => {
7114  console.error("Get failed, error: " + JSON.stringify(err));
7115})
7116```
7117
7118### send<sup>9+</sup>
7119
7120send(data: string \| ArrayBuffer, callback: AsyncCallback\<void\>): void
7121
7122Sends a message to the server after a TLS socket connection is established. This API uses an asynchronous callback to return the result.
7123
7124**System capability**: SystemCapability.Communication.NetStack
7125
7126**Parameters**
7127
7128| Name   | Type                         | Mandatory| Description           |
7129| -------- | -----------------------------| ---- | ---------------|
7130|   data   | string \| ArrayBuffer                      | Yes  | Data content of the message to send.  |
7131| callback | AsyncCallback\<void\>         | Yes  | Callback used to return the result. If the operation fails, an error message is returned.|
7132
7133**Error codes**
7134
7135| ID| Error Message                                     |
7136| ------- | -------------------------------------------- |
7137| 401     | Parameter error.                             |
7138| 2303501 | SSL is null.                                 |
7139| 2303503 | An error occurred when writing data on the TLS socket.|
7140| 2303505 | An error occurred in the TLS system call.    |
7141| 2303506 | Failed to close the TLS connection.          |
7142| 2300002 | System internal error.                       |
7143
7144**Example**
7145
7146```ts
7147import { socket } from '@kit.NetworkKit';
7148import { BusinessError } from '@kit.BasicServicesKit';
7149
7150let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
7151tls.send("xxxx", (err: BusinessError) => {
7152  if (err) {
7153    console.log("send callback error = " + err);
7154  } else {
7155    console.log("send success");
7156  }
7157});
7158```
7159
7160### send<sup>9+</sup>
7161
7162send(data: string \| ArrayBuffer): Promise\<void\>
7163
7164Sends a message to the server after a TLS socket connection is established. This API uses a promise to return the result.
7165
7166**System capability**: SystemCapability.Communication.NetStack
7167
7168**Parameters**
7169
7170| Name   | Type                         | Mandatory| Description           |
7171| -------- | -----------------------------| ---- | ---------------|
7172|   data   | string \| ArrayBuffer                       | Yes  | Data content of the message to send.  |
7173
7174**Error codes**
7175
7176| ID| Error Message                                     |
7177| ------- | -------------------------------------------- |
7178| 401     | Parameter error.                             |
7179| 2303501 | SSL is null.                                 |
7180| 2303503 | An error occurred when writing data on the TLS socket.|
7181| 2303505 | An error occurred in the TLS system call.    |
7182| 2303506 | Failed to close the TLS connection.          |
7183| 2300002 | System internal error.                       |
7184
7185**Return value**
7186
7187| Type          | Description                 |
7188| -------------- | -------------------- |
7189| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.|
7190
7191**Example**
7192
7193```ts
7194import { socket } from '@kit.NetworkKit';
7195import { BusinessError } from '@kit.BasicServicesKit';
7196
7197let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
7198tls.send("xxxx").then(() => {
7199  console.log("send success");
7200}).catch((err: BusinessError) => {
7201  console.error("failed" + err);
7202});
7203```
7204
7205### close<sup>9+</sup>
7206
7207close(callback: AsyncCallback\<void\>): void
7208
7209Closes a TLS socket connection. This API uses an asynchronous callback to return the result.
7210
7211**System capability**: SystemCapability.Communication.NetStack
7212
7213**Parameters**
7214
7215| Name   | Type                         | Mandatory| Description           |
7216| -------- | -----------------------------| ---- | ---------------|
7217| callback | AsyncCallback\<void\>         | Yes  | Callback used to return the result. If the operation fails, an error message is returned.|
7218
7219**Error codes**
7220
7221| ID| Error Message                                     |
7222| ------- | -------------------------------------------- |
7223| 401 | Parameter error.                                 |
7224| 2303501 | SSL is null.                                 |
7225| 2303505 | An error occurred in the TLS system call.    |
7226| 2303506 | Failed to close the TLS connection.          |
7227| 2300002 | System internal error.                       |
7228
7229**Example**
7230
7231```ts
7232import { socket } from '@kit.NetworkKit';
7233import { BusinessError } from '@kit.BasicServicesKit';
7234
7235let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
7236tls.close((err: BusinessError) => {
7237  if (err) {
7238    console.log("close callback error = " + err);
7239  } else {
7240    console.log("close success");
7241  }
7242});
7243```
7244
7245### close<sup>9+</sup>
7246
7247close(): Promise\<void\>
7248
7249Closes a TLS socket connection. This API uses a promise to return the result.
7250
7251**System capability**: SystemCapability.Communication.NetStack
7252
7253**Return value**
7254
7255| Type          | Description                 |
7256| -------------- | -------------------- |
7257| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.|
7258
7259**Error codes**
7260
7261| ID| Error Message                                     |
7262| ------- | -------------------------------------------- |
7263| 401 | Parameter error.                                 |
7264| 2303501 | SSL is null.                                 |
7265| 2303505 | An error occurred in the TLS system call.    |
7266| 2303506 | Failed to close the TLS connection.          |
7267| 2300002 | System internal error.                       |
7268
7269**Example**
7270
7271```ts
7272import { socket } from '@kit.NetworkKit';
7273import { BusinessError } from '@kit.BasicServicesKit';
7274
7275let tls: socket.TLSSocket = socket.constructTLSSocketInstance();
7276tls.close().then(() => {
7277  console.log("close success");
7278}).catch((err: BusinessError) => {
7279  console.error("failed" + err);
7280});
7281```
7282
7283## TLSConnectOptions<sup>9+</sup>
7284
7285Defines TLS connection options.
7286
7287**System capability**: SystemCapability.Communication.NetStack
7288
7289| Name         | Type                                    | Mandatory| Description           |
7290| -------------- | ------------------------------------- | ---  |-------------- |
7291| address        | [NetAddress](#netaddress)             | Yes |  Gateway address.      |
7292| secureOptions  | [TLSSecureOptions](#tlssecureoptions9) | Yes| TLS security options.|
7293| ALPNProtocols  | Array\<string\>                         | No| ALPN protocol. The value range is ["spdy/1", "http/1.1"]. The default value is **[]**.     |
7294| skipRemoteValidation<sup>12+</sup>  | boolean                         | No| Whether to skip certificate authentication on the server. The default value is **false**. The value **true** means to skip certificate authentication on the server, and the value **false** means the opposite.     |
7295| proxy<sup>18+</sup>   | [ProxyOptions](#proxyoptions18) | No  | Proxy option. By default, no proxy is used.|
7296
7297## TLSSecureOptions<sup>9+</sup>
7298
7299TLS security options. When **cert** (local certificate) and **key** (private key) are not empty, the two-way authentication mode is enabled. If **cert** or **key** is empty, one-way authentication is enabled.
7300
7301**System capability**: SystemCapability.Communication.NetStack
7302
7303| Name                | Type                                                   | Mandatory| Description                               |
7304| --------------------- | ------------------------------------------------------ | --- |----------------------------------- |
7305| ca                    | string \| Array\<string\> | No| CA certificate of the server, which is used to authenticate the digital certificate of the server. The default value is the preset CA certificate<sup>12+</sup>.|
7306| cert                  | string                                                  | No| Digital certificate of the local client.                |
7307| key                   | string                                                  | No| Private key of the local digital certificate.                  |
7308| password                | string                                                  | No| Password for reading the private key.                     |
7309| protocols             | [Protocol](#protocol9) \|Array\<[Protocol](#protocol9)\> | No| TLS protocol version. The default value is **TLSv1.2**.                 |
7310| useRemoteCipherPrefer | boolean                                                 | No| Whether to use the remote cipher suite preferentially. The value **true** means to use the remote cipher suite preferentially, and the value **false** means the opposite.       |
7311| signatureAlgorithms   | string                                                 | No| Signing algorithm used during communication. The default value is **""**.             |
7312| cipherSuite           | string                                                 | No| Cipher suite used during communication. The default value is **""**.             |
7313| isBidirectionalAuthentication<sup>12+</sup>           | boolean                                                 | No| Whether to enable two-way authentication. The default value is **false**. The value **true** means to enable two-way authentication, and the value **false** means the opposite.             |
7314
7315## Protocol<sup>9+</sup>
7316
7317Enumerates TLS protocol versions.
7318
7319**System capability**: SystemCapability.Communication.NetStack
7320
7321| Name     |    Value   | Description               |
7322| --------- | --------- |------------------ |
7323| TLSv12    | "TLSv1.2" | TLSv1.2.|
7324| TLSv13    | "TLSv1.3" | TLSv1.3.|
7325
7326## X509CertRawData<sup>9+</sup>
7327
7328type X509CertRawData = cert.EncodingBlob
7329
7330Defines the certificate raw data.
7331
7332**System capability**: SystemCapability.Communication.NetStack
7333
7334|       Type      |            Description            |
7335| ---------------- | --------------------------- |
7336| cert.EncodingBlob | Certificate encoding BLOB type.    |
7337
7338## socket.constructTLSSocketServerInstance<sup>10+</sup>
7339
7340constructTLSSocketServerInstance(): TLSSocketServer
7341
7342Creates a **TLSSocketServer** object.
7343
7344**System capability**: SystemCapability.Communication.NetStack
7345
7346**Return value**
7347
7348| Type                                 | Description                         |
7349|  ------------------------------------ |  ---------------------------- |
7350| [TLSSocketServer](#tlssocketserver10) | **TLSSocketServer** object.|
7351
7352**Example**
7353
7354```ts
7355import { socket } from '@kit.NetworkKit';
7356import { BusinessError } from '@kit.BasicServicesKit';
7357
7358let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
7359```
7360
7361## TLSSocketServer<sup>10+</sup>
7362
7363Defines a TLS socket server connection. Before calling TLSSocketServer APIs, you need to call [socket.constructTLSSocketServerInstance](#socketconstructtlssocketserverinstance10) to create a **TLSSocketServer** object.
7364
7365### listen<sup>10+</sup>
7366
7367listen(options: TLSConnectOptions, callback: AsyncCallback\<void\>): void
7368
7369Listens to client connections after **bind** is successfully called. This API uses an asynchronous callback to return the result. After a connection is established, a TLS session will be created and initialized and a certificate key will be loaded and verified.
7370
7371**NOTE**<br>If the IP address is set to **0.0.0.0**, listening works for all IP addresses of the local host.
7372
7373**Required permissions**: ohos.permission.INTERNET
7374
7375**System capability**: SystemCapability.Communication.NetStack
7376
7377**Parameters**
7378
7379| Name  | Type                                    | Mandatory| Description                                            |
7380| -------- | ---------------------------------------- | ---- | ------------------------------------------------ |
7381| options  | [TLSConnectOptions](#tlsconnectoptions9) | Yes  | Parameters required for the connection.               |
7382| callback | AsyncCallback\<void\>                     | Yes  | Callback used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
7383
7384**Error codes**
7385
7386| ID| Error Message                                   |
7387| -------- | ------------------------------------------- |
7388| 401      | Parameter error.                            |
7389| 201      | Permission denied.                          |
7390| 2300002  | System internal error.                      |
7391| 2303109  | Bad file number.                            |
7392| 2303111  | Resource temporarily unavailable. Try again.|
7393| 2303198  | Address already in use.                     |
7394| 2303199  | Cannot assign requested address.            |
7395| 2303501  | SSL is null.                                |
7396| 2303502  | An error occurred when reading data on the TLS socket.|
7397| 2303503  | An error occurred when writing data on the TLS socket.|
7398| 2303505  | An error occurred in the TLS system call.   |
7399| 2303506  | Failed to close the TLS connection.         |
7400
7401**Example**
7402
7403```ts
7404import { socket } from '@kit.NetworkKit';
7405import { BusinessError } from '@kit.BasicServicesKit';
7406
7407let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
7408let netAddress: socket.NetAddress = {
7409  address: '192.168.xx.xxx',
7410  port: 8080
7411}
7412let tlsSecureOptions: socket.TLSSecureOptions = {
7413  key: "xxxx",
7414  cert: "xxxx",
7415  ca: ["xxxx"],
7416  password: "xxxx",
7417  protocols: socket.Protocol.TLSv12,
7418  useRemoteCipherPrefer: true,
7419  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
7420  cipherSuite: "AES256-SHA256"
7421}
7422let tlsConnectOptions: socket.TLSConnectOptions = {
7423  address: netAddress,
7424  secureOptions: tlsSecureOptions,
7425  ALPNProtocols: ["spdy/1", "http/1.1"],
7426  skipRemoteValidation: false
7427}
7428tlsServer.listen(tlsConnectOptions, (err: BusinessError) => {
7429  console.log("listen callback error" + err);
7430});
7431```
7432
7433### listen<sup>10+</sup>
7434
7435listen(options: TLSConnectOptions): Promise\<void\>
7436
7437Listens to client connections after **bind** is successfully called. This API uses a promise to return the result. After a connection is established, a TLS session will be created and initialized and a certificate key will be loaded and verified.
7438
7439**Required permissions**: ohos.permission.INTERNET
7440
7441**System capability**: SystemCapability.Communication.NetStack
7442
7443**Parameters**
7444
7445| Name | Type                                    | Mandatory| Description              |
7446| ------- | ---------------------------------------- | ---- | ------------------ |
7447| options | [TLSConnectOptions](#tlsconnectoptions9) | Yes  | Parameters required for the connection.|
7448
7449**Return value**
7450
7451| Type           | Description                                                     |
7452| --------------- | --------------------------------------------------------- |
7453| Promise\<void\> | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
7454
7455**Error codes**
7456
7457| ID| Error Message                                   |
7458| -------- | ------------------------------------------- |
7459| 401      | Parameter error.                            |
7460| 201      | Permission denied.                          |
7461| 2300002  | System internal error.                      |
7462| 2303109  | Bad file number.                            |
7463| 2303111  | Resource temporarily unavailable. Try again.|
7464| 2303198  | Address already in use.                     |
7465| 2303199  | Cannot assign requested address.            |
7466| 2303501  | SSL is null.                                |
7467| 2303502  | An error occurred when reading data on the TLS socket.|
7468| 2303503  | An error occurred when writing data on the TLS socket.|
7469| 2303505  | An error occurred in the TLS system call.   |
7470| 2303506  | Failed to close the TLS connection.         |
7471
7472**Example**
7473
7474```ts
7475import { socket } from '@kit.NetworkKit';
7476import { BusinessError } from '@kit.BasicServicesKit';
7477
7478let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
7479let netAddress: socket.NetAddress = {
7480  address: '192.168.xx.xxx',
7481  port: 8080
7482}
7483let tlsSecureOptions: socket.TLSSecureOptions = {
7484  key: "xxxx",
7485  cert: "xxxx",
7486  ca: ["xxxx"],
7487  password: "xxxx",
7488  protocols: socket.Protocol.TLSv12,
7489  useRemoteCipherPrefer: true,
7490  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
7491  cipherSuite: "AES256-SHA256"
7492}
7493let tlsConnectOptions: socket.TLSConnectOptions = {
7494  address: netAddress,
7495  secureOptions: tlsSecureOptions,
7496  ALPNProtocols: ["spdy/1", "http/1.1"],
7497  skipRemoteValidation: false
7498}
7499tlsServer.listen(tlsConnectOptions).then(() => {
7500  console.log("listen callback success");
7501}).catch((err: BusinessError) => {
7502  console.log("failed: " + JSON.stringify(err));
7503});
7504```
7505
7506### getState<sup>10+</sup>
7507
7508getState(callback: AsyncCallback\<SocketStateBase\>): void
7509
7510Obtains the status of the TLS socket server connection upon successful listening. This API uses an asynchronous callback to return the result.
7511
7512> **NOTE**
7513> This API can be called only after **listen** is successfully called.
7514
7515**System capability**: SystemCapability.Communication.NetStack
7516
7517**Parameters**
7518
7519| Name  | Type                                                | Mandatory| Description                                                        |
7520| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ |
7521| callback | AsyncCallback\<[SocketStateBase](#socketstatebase)\> | Yes  | Callback used to return the result. If the operation is successful, the status of the TLS socket server connection is returned. If the operation fails, an error message is returned.|
7522
7523**Error codes**
7524
7525| ID| Error Message                       |
7526| -------- | ------------------------------- |
7527| 401      | Parameter error.                |
7528| 2303188  | Socket operation on non-socket. |
7529| 2300002  | System internal error.          |
7530
7531**Example**
7532
7533```ts
7534import { socket } from '@kit.NetworkKit';
7535import { BusinessError } from '@kit.BasicServicesKit';
7536
7537let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
7538let netAddress: socket.NetAddress = {
7539  address: '192.168.xx.xxx',
7540  port: 8080
7541}
7542let tlsSecureOptions: socket.TLSSecureOptions = {
7543  key: "xxxx",
7544  cert: "xxxx",
7545  ca: ["xxxx"],
7546  password: "xxxx",
7547  protocols: socket.Protocol.TLSv12,
7548  useRemoteCipherPrefer: true,
7549  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
7550  cipherSuite: "AES256-SHA256"
7551}
7552let tlsConnectOptions: socket.TLSConnectOptions = {
7553  address: netAddress,
7554  secureOptions: tlsSecureOptions,
7555  ALPNProtocols: ["spdy/1", "http/1.1"]
7556}
7557tlsServer.listen(tlsConnectOptions).then(() => {
7558  console.log("listen callback success");
7559}).catch((err: BusinessError) => {
7560  console.log("failed: " + JSON.stringify(err));
7561});
7562tlsServer.getState((err: BusinessError, data: socket.SocketStateBase) => {
7563  if (err) {
7564    console.log('getState fail');
7565    return;
7566  }
7567  console.log('getState success:' + JSON.stringify(data));
7568});
7569```
7570
7571### getState<sup>10+</sup>
7572
7573getState(): Promise\<SocketStateBase\>
7574
7575Obtains the status of the TLS socket server connection upon successful listening. This API uses a promise to return the result.
7576
7577> **NOTE**
7578> This API can be called only after **listen** is successfully called.
7579
7580**System capability**: SystemCapability.Communication.NetStack
7581
7582**Return value**
7583
7584| Type                                          | Description                                                        |
7585|  --------------------------------------------- |  ----------------------------------------------------------- |
7586| Promise\<[SocketStateBase](#socketstatebase)\> | Promise used to return the result. If the operation fails, an error message is returned.|
7587
7588**Error codes**
7589
7590| ID| Error Message                       |
7591| -------- | ------------------------------- |
7592| 2303188  | Socket operation on non-socket. |
7593| 2300002  | System internal error.          |
7594
7595**Example**
7596
7597```ts
7598import { socket } from '@kit.NetworkKit';
7599import { BusinessError } from '@kit.BasicServicesKit';
7600
7601let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
7602let netAddress: socket.NetAddress = {
7603  address: '192.168.xx.xxx',
7604  port: 8080
7605}
7606let tlsSecureOptions: socket.TLSSecureOptions = {
7607  key: "xxxx",
7608  cert: "xxxx",
7609  ca: ["xxxx"],
7610  password: "xxxx",
7611  protocols: socket.Protocol.TLSv12,
7612  useRemoteCipherPrefer: true,
7613  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
7614  cipherSuite: "AES256-SHA256"
7615}
7616let tlsConnectOptions: socket.TLSConnectOptions = {
7617  address: netAddress,
7618  secureOptions: tlsSecureOptions,
7619  ALPNProtocols: ["spdy/1", "http/1.1"]
7620}
7621tlsServer.listen(tlsConnectOptions).then(() => {
7622  console.log("listen callback success");
7623}).catch((err: BusinessError) => {
7624  console.log("failed: " + JSON.stringify(err));
7625});
7626tlsServer.getState().then(() => {
7627  console.log('getState success');
7628}).catch((err: BusinessError) => {
7629  console.log('getState fail');
7630});
7631```
7632
7633### setExtraOptions<sup>10+</sup>
7634
7635setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\<void\>): void
7636
7637Sets other properties of the TLS socket server connection upon successful listening. This API uses an asynchronous callback to return the result.
7638
7639> **NOTE**
7640> This API can be called only after **listen** is successfully called.
7641
7642**System capability**: SystemCapability.Communication.NetStack
7643
7644**Parameters**
7645
7646| Name  | Type                                | Mandatory| Description                                            |
7647| -------- | ------------------------------------ | ---- | ------------------------------------------------ |
7648| options  | [TCPExtraOptions](#tcpextraoptions) | Yes  | Other properties of the TLS socket server connection.                 |
7649| callback | AsyncCallback\<void\>                | Yes  | Callback used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
7650
7651**Error codes**
7652
7653| ID| Error Message                       |
7654| -------- | ------------------------------- |
7655| 401      | Parameter error.                |
7656| 2303188  | Socket operation on non-socket. |
7657| 2300002  | System internal error.          |
7658
7659**Example**
7660
7661```ts
7662import { socket } from '@kit.NetworkKit';
7663import { BusinessError } from '@kit.BasicServicesKit';
7664
7665let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
7666let netAddress: socket.NetAddress = {
7667  address: '192.168.xx.xxx',
7668  port: 8080
7669}
7670let tlsSecureOptions: socket.TLSSecureOptions = {
7671  key: "xxxx",
7672  cert: "xxxx",
7673  ca: ["xxxx"],
7674  password: "xxxx",
7675  protocols: socket.Protocol.TLSv12,
7676  useRemoteCipherPrefer: true,
7677  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
7678  cipherSuite: "AES256-SHA256"
7679}
7680let tlsConnectOptions: socket.TLSConnectOptions = {
7681  address: netAddress,
7682  secureOptions: tlsSecureOptions,
7683  ALPNProtocols: ["spdy/1", "http/1.1"]
7684}
7685tlsServer.listen(tlsConnectOptions).then(() => {
7686  console.log("listen callback success");
7687}).catch((err: BusinessError) => {
7688  console.log("failed: " + JSON.stringify(err));
7689});
7690
7691interface SocketLinger {
7692  on: boolean;
7693  linger: number;
7694}
7695
7696let tcpExtraOptions: socket.TCPExtraOptions = {
7697  keepAlive: true,
7698  OOBInline: true,
7699  TCPNoDelay: true,
7700  socketLinger: { on: true, linger: 10 } as SocketLinger,
7701  receiveBufferSize: 1000,
7702  sendBufferSize: 1000,
7703  reuseAddress: true,
7704  socketTimeout: 3000
7705}
7706tlsServer.setExtraOptions(tcpExtraOptions, (err: BusinessError) => {
7707  if (err) {
7708    console.log('setExtraOptions fail');
7709    return;
7710  }
7711  console.log('setExtraOptions success');
7712});
7713```
7714
7715### setExtraOptions<sup>10+</sup>
7716
7717setExtraOptions(options: TCPExtraOptions): Promise\<void\>
7718
7719Sets other properties of the TLS socket server connection upon successful listening. This API uses a promise to return the result.
7720
7721> **NOTE**
7722> This API can be called only after **listen** is successfully called.
7723
7724**System capability**: SystemCapability.Communication.NetStack
7725
7726**Parameters**
7727
7728| Name | Type                                | Mandatory| Description                           |
7729| ------- | ------------------------------------ | ---- | ------------------------------- |
7730| options | [TCPExtraOptions](#tcpextraoptions) | Yes  | Other properties of the TLS socket server connection.|
7731
7732**Return value**
7733
7734| Type           | Description                                                     |
7735|  -------------- |  -------------------------------------------------------- |
7736| Promise\<void\> | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
7737
7738**Error codes**
7739
7740| ID| Error Message                       |
7741| -------- | ------------------------------- |
7742| 401      | Parameter error.                |
7743| 2303188  | Socket operation on non-socket. |
7744| 2300002  | System internal error.          |
7745
7746**Example**
7747
7748```ts
7749import { socket } from '@kit.NetworkKit';
7750import { BusinessError } from '@kit.BasicServicesKit';
7751
7752let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
7753let netAddress: socket.NetAddress = {
7754  address: '192.168.xx.xxx',
7755  port: 8080
7756}
7757let tlsSecureOptions: socket.TLSSecureOptions = {
7758  key: "xxxx",
7759  cert: "xxxx",
7760  ca: ["xxxx"],
7761  password: "xxxx",
7762  protocols: socket.Protocol.TLSv12,
7763  useRemoteCipherPrefer: true,
7764  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
7765  cipherSuite: "AES256-SHA256"
7766}
7767let tlsConnectOptions: socket.TLSConnectOptions = {
7768  address: netAddress,
7769  secureOptions: tlsSecureOptions,
7770  ALPNProtocols: ["spdy/1", "http/1.1"]
7771}
7772tlsServer.listen(tlsConnectOptions).then(() => {
7773  console.log("listen callback success");
7774}).catch((err: BusinessError) => {
7775  console.log("failed: " + JSON.stringify(err));
7776});
7777
7778interface SocketLinger {
7779  on: boolean;
7780  linger: number;
7781}
7782
7783let tcpExtraOptions: socket.TCPExtraOptions = {
7784  keepAlive: true,
7785  OOBInline: true,
7786  TCPNoDelay: true,
7787  socketLinger: { on: true, linger: 10 } as SocketLinger,
7788  receiveBufferSize: 1000,
7789  sendBufferSize: 1000,
7790  reuseAddress: true,
7791  socketTimeout: 3000
7792}
7793tlsServer.setExtraOptions(tcpExtraOptions).then(() => {
7794  console.log('setExtraOptions success');
7795}).catch((err: BusinessError) => {
7796  console.log('setExtraOptions fail');
7797});
7798```
7799
7800### getCertificate<sup>10+</sup>
7801
7802getCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)\>): void
7803
7804Obtains the local digital certificate after a TLS socket server connection is established. This API uses an asynchronous callback to return the result.
7805
7806> **NOTE**
7807> This API can be called only after **listen** is successfully called.
7808
7809**System capability**: SystemCapability.Communication.NetStack
7810
7811**Parameters**
7812
7813| Name  | Type                                                 | Mandatory| Description                                                    |
7814| -------- | ----------------------------------------------------- | ---- | -------------------------------------------------------- |
7815| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)\> | Yes  | Callback used to return the result. If the operation is successful, the local certificate is returned. If the operation fails, an error message is returned.|
7816
7817**Error codes**
7818
7819| ID| Error Message              |
7820| -------- | ---------------------- |
7821| 401      | Parameter error.       |
7822| 2303501  | SSL is null.           |
7823| 2303504  | An error occurred when verifying the X.509 certificate. |
7824| 2300002  | System internal error. |
7825
7826**Example**
7827
7828```ts
7829import { socket } from '@kit.NetworkKit';
7830import { BusinessError } from '@kit.BasicServicesKit';
7831import { util } from '@kit.ArkTS';
7832
7833let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
7834let netAddress: socket.NetAddress = {
7835  address: '192.168.xx.xxx',
7836  port: 8080
7837}
7838let tlsSecureOptions: socket.TLSSecureOptions = {
7839  key: "xxxx",
7840  cert: "xxxx",
7841  ca: ["xxxx"],
7842  password: "xxxx",
7843  protocols: socket.Protocol.TLSv12,
7844  useRemoteCipherPrefer: true,
7845  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
7846  cipherSuite: "AES256-SHA256"
7847}
7848let tlsConnectOptions: socket.TLSConnectOptions = {
7849  address: netAddress,
7850  secureOptions: tlsSecureOptions,
7851  ALPNProtocols: ["spdy/1", "http/1.1"]
7852}
7853tlsServer.listen(tlsConnectOptions).then(() => {
7854  console.log("listen callback success");
7855}).catch((err: BusinessError) => {
7856  console.log("failed: " + JSON.stringify(err));
7857});
7858tlsServer.getCertificate((err: BusinessError, data: socket.X509CertRawData) => {
7859  if (err) {
7860    console.log("getCertificate callback error = " + err);
7861  } else {
7862    const decoder = util.TextDecoder.create();
7863    const str = decoder.decodeWithStream(data.data);
7864    console.log("getCertificate callback: " + str);
7865  }
7866});
7867```
7868
7869### getCertificate<sup>10+</sup>
7870
7871getCertificate():Promise\<[X509CertRawData](#x509certrawdata9)\>
7872
7873Obtains the local digital certificate after a TLS socket server connection is established. This API uses a promise to return the result.
7874
7875> **NOTE**
7876> This API can be called only after **listen** is successfully called.
7877
7878**System capability**: SystemCapability.Communication.NetStack
7879
7880**Return value**
7881
7882| Type                                           | Description                                                        |
7883| ----------------------------------------------- | ------------------------------------------------------------ |
7884| Promise\<[X509CertRawData](#x509certrawdata9)\> | Promise used to return the result. If the operation fails, an error message is returned.|
7885
7886**Error codes**
7887
7888| ID| Error Message              |
7889| -------- | ---------------------- |
7890| 2303501  | SSL is null.           |
7891| 2303504  | An error occurred when verifying the X.509 certificate. |
7892| 2300002  | System internal error. |
7893
7894**Example**
7895
7896```ts
7897import { socket } from '@kit.NetworkKit';
7898import { BusinessError } from '@kit.BasicServicesKit';
7899import { util } from '@kit.ArkTS';
7900
7901let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
7902let netAddress: socket.NetAddress = {
7903  address: '192.168.xx.xxx',
7904  port: 8080
7905}
7906let tlsSecureOptions: socket.TLSSecureOptions = {
7907  key: "xxxx",
7908  cert: "xxxx",
7909  ca: ["xxxx"],
7910  password: "xxxx",
7911  protocols: socket.Protocol.TLSv12,
7912  useRemoteCipherPrefer: true,
7913  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
7914  cipherSuite: "AES256-SHA256"
7915}
7916let tlsConnectOptions: socket.TLSConnectOptions = {
7917  address: netAddress,
7918  secureOptions: tlsSecureOptions,
7919  ALPNProtocols: ["spdy/1", "http/1.1"]
7920}
7921tlsServer.listen(tlsConnectOptions).then(() => {
7922  console.log("listen callback success");
7923}).catch((err: BusinessError) => {
7924  console.log("failed: " + JSON.stringify(err));
7925});
7926tlsServer.getCertificate().then((data: socket.X509CertRawData) => {
7927  const decoder = util.TextDecoder.create();
7928  const str = decoder.decodeWithStream(data.data);
7929  console.log("getCertificate: " + str);
7930}).catch((err: BusinessError) => {
7931  console.error("failed" + err);
7932});
7933```
7934
7935### getProtocol<sup>10+</sup>
7936
7937getProtocol(callback: AsyncCallback\<string\>): void
7938
7939Obtains the communication protocol version after a TLS socket server connection is established. This API uses an asynchronous callback to return the result.
7940
7941> **NOTE**
7942> This API can be called only after **listen** is successfully called.
7943
7944**System capability**: SystemCapability.Communication.NetStack
7945
7946**Parameters**
7947
7948| Name  | Type                   | Mandatory| Description                                                |
7949| -------- | ----------------------- | ---- | ---------------------------------------------------- |
7950| callback | AsyncCallback\<string\> | Yes  | Callback used to return the result. If the operation fails, an error message is returned.|
7951
7952**Error codes**
7953
7954| ID| Error Message                              |
7955| -------- | -------------------------------------- |
7956| 401      | Parameter error.                       |
7957| 2303501  | SSL is null.                           |
7958| 2303505  | An error occurred in the TLS system call. |
7959| 2300002  | System internal error.                 |
7960
7961**Example**
7962
7963```ts
7964import { socket } from '@kit.NetworkKit';
7965import { BusinessError } from '@kit.BasicServicesKit';
7966
7967let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
7968let netAddress: socket.NetAddress = {
7969  address: '192.168.xx.xxx',
7970  port: 8080
7971}
7972let tlsSecureOptions: socket.TLSSecureOptions = {
7973  key: "xxxx",
7974  cert: "xxxx",
7975  ca: ["xxxx"],
7976  password: "xxxx",
7977  protocols: socket.Protocol.TLSv12,
7978  useRemoteCipherPrefer: true,
7979  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
7980  cipherSuite: "AES256-SHA256"
7981}
7982let tlsConnectOptions: socket.TLSConnectOptions = {
7983  address: netAddress,
7984  secureOptions: tlsSecureOptions,
7985  ALPNProtocols: ["spdy/1", "http/1.1"]
7986}
7987tlsServer.listen(tlsConnectOptions).then(() => {
7988  console.log("listen callback success");
7989}).catch((err: BusinessError) => {
7990  console.log("failed: " + JSON.stringify(err));
7991});
7992tlsServer.getProtocol((err: BusinessError, data: string) => {
7993  if (err) {
7994    console.log("getProtocol callback error = " + err);
7995  } else {
7996    console.log("getProtocol callback = " + data);
7997  }
7998});
7999```
8000
8001### getProtocol<sup>10+</sup>
8002
8003getProtocol():Promise\<string\>
8004
8005Obtains the communication protocol version after a TLS socket server connection is established. This API uses a promise to return the result.
8006
8007> **NOTE**
8008> This API can be called only after **listen** is successfully called.
8009
8010**System capability**: SystemCapability.Communication.NetStack
8011
8012**Return value**
8013
8014| Type             | Description                                                   |
8015| ----------------- | ------------------------------------------------------- |
8016| Promise\<string\> | Promise used to return the result. If the operation fails, an error message is returned.|
8017
8018**Error codes**
8019
8020| ID| Error Message                              |
8021| -------- | -------------------------------------- |
8022| 2303501  | SSL is null.                           |
8023| 2303505  | An error occurred in the TLS system call. |
8024| 2300002  | System internal error.                 |
8025
8026**Example**
8027
8028```ts
8029import { socket } from '@kit.NetworkKit';
8030import { BusinessError } from '@kit.BasicServicesKit';
8031
8032let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
8033let netAddress: socket.NetAddress = {
8034  address: '192.168.xx.xxx',
8035  port: 8080
8036}
8037let tlsSecureOptions: socket.TLSSecureOptions = {
8038  key: "xxxx",
8039  cert: "xxxx",
8040  ca: ["xxxx"],
8041  password: "xxxx",
8042  protocols: socket.Protocol.TLSv12,
8043  useRemoteCipherPrefer: true,
8044  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
8045  cipherSuite: "AES256-SHA256"
8046}
8047let tlsConnectOptions: socket.TLSConnectOptions = {
8048  address: netAddress,
8049  secureOptions: tlsSecureOptions,
8050  ALPNProtocols: ["spdy/1", "http/1.1"]
8051}
8052tlsServer.listen(tlsConnectOptions).then(() => {
8053  console.log("listen callback success");
8054}).catch((err: BusinessError) => {
8055  console.log("failed: " + JSON.stringify(err));
8056});
8057tlsServer.getProtocol().then((data: string) => {
8058  console.log(data);
8059}).catch((err: BusinessError) => {
8060  console.error("failed" + err);
8061});
8062```
8063
8064### getLocalAddress<sup>12+</sup>
8065
8066getLocalAddress(): Promise\<NetAddress\>
8067
8068Obtains the local socket address of a **TLSSocketServer** connection. This API uses a promise to return the result.
8069
8070> **NOTE**
8071> Call this API only after the **TLSSocketServer** connection is successfully established.
8072
8073**System capability**: SystemCapability.Communication.NetStack
8074
8075**Return value**
8076
8077| Type           | Description                                                |
8078|  -------------- |  --------------------------------------------------- |
8079| Promise\<[NetAddress](#netaddress)\> | Promise used to return the result.|
8080
8081**Error codes**
8082
8083| ID| Error Message                                   |
8084| -------- | ------------------------------------------- |
8085| 2300002  | System internal error.                      |
8086| 2301009  | Bad file descriptor.                            |
8087| 2303188  | Socket operation on non-socket. |
8088
8089**Example**
8090
8091```ts
8092import { socket } from '@kit.NetworkKit';
8093import { BusinessError } from '@kit.BasicServicesKit';
8094
8095let tlsServer: socket.TLSSocket = socket.constructTLSSocketServerInstance();
8096tlsServer.getLocalAddress().then((localAddress: socket.NetAddress) => {
8097  console.info("Get success: " + JSON.stringify(localAddress));
8098}).catch((err: BusinessError) => {
8099  console.error("Get failed, error: " + JSON.stringify(err));
8100})
8101```
8102
8103### on('connect')<sup>10+</sup>
8104
8105on(type: 'connect', callback: Callback\<TLSSocketConnection\>): void
8106
8107Subscribes to TLS socket server connection events. This API uses an asynchronous callback to return the result.
8108
8109> **NOTE**
8110> This API can be called only after **listen** is successfully called.
8111
8112**System capability**: SystemCapability.Communication.NetStack
8113
8114**Parameters**
8115
8116| Name  | Type                                                   | Mandatory| Description                                 |
8117| -------- | ------------------------------------------------------- | ---- | ------------------------------------- |
8118| type     | string                                                  | Yes  | Event type.<br/> **connect**: connection event.|
8119| callback | Callback\<[TLSSocketConnection](#tlssocketconnection10)\> | Yes  | Callback used to return the result. If the operation fails, an error message is returned.   |
8120
8121**Error codes**
8122
8123| ID| Error Message        |
8124| -------- | ---------------- |
8125| 401      | Parameter error. |
8126
8127**Example**
8128
8129```ts
8130import { socket } from '@kit.NetworkKit';
8131import { BusinessError } from '@kit.BasicServicesKit';
8132
8133let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
8134let netAddress: socket.NetAddress = {
8135  address: '192.168.xx.xxx',
8136  port: 8080
8137}
8138let tlsSecureOptions: socket.TLSSecureOptions = {
8139  key: "xxxx",
8140  cert: "xxxx",
8141  ca: ["xxxx"],
8142  password: "xxxx",
8143  protocols: socket.Protocol.TLSv12,
8144  useRemoteCipherPrefer: true,
8145  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
8146  cipherSuite: "AES256-SHA256"
8147}
8148let tlsConnectOptions: socket.TLSConnectOptions = {
8149  address: netAddress,
8150  secureOptions: tlsSecureOptions,
8151  ALPNProtocols: ["spdy/1", "http/1.1"]
8152}
8153tlsServer.listen(tlsConnectOptions).then(() => {
8154  console.log("listen callback success");
8155}).catch((err: BusinessError) => {
8156  console.log("failed: " + JSON.stringify(err));
8157});
8158tlsServer.on('connect', (data: socket.TLSSocketConnection) => {
8159  console.log(JSON.stringify(data))
8160});
8161```
8162
8163### off('connect')<sup>10+</sup>
8164
8165off(type: 'connect', callback?: Callback\<TLSSocketConnection\>): void
8166
8167Unsubscribes from **connect** events of a **TLSSocketServer** object. This API uses an asynchronous callback to return the result.
8168
8169> **NOTE**
8170> This API can be called only after **listen** is successfully called.
8171> You can pass the callback of the **on** function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
8172
8173**System capability**: SystemCapability.Communication.NetStack
8174
8175**Parameters**
8176
8177| Name  | Type                                                   | Mandatory| Description                                 |
8178| -------- | ------------------------------------------------------- | ---- | ------------------------------------- |
8179| type     | string                                                  | Yes  | Event type.<br/> **connect**: connection event.|
8180| callback | Callback\<[TLSSocketConnection](#tlssocketconnection10)\> | No  | Callback used to return the result. If the operation fails, an error message is returned.     |
8181
8182**Error codes**
8183
8184| ID| Error Message        |
8185| -------- | ---------------- |
8186| 401      | Parameter error. |
8187
8188**Example**
8189
8190```ts
8191import { socket } from '@kit.NetworkKit';
8192import { BusinessError } from '@kit.BasicServicesKit';
8193
8194let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
8195let netAddress: socket.NetAddress = {
8196  address: '192.168.xx.xxx',
8197  port: 8080
8198}
8199let tlsSecureOptions: socket.TLSSecureOptions = {
8200  key: "xxxx",
8201  cert: "xxxx",
8202  ca: ["xxxx"],
8203  password: "xxxx",
8204  protocols: socket.Protocol.TLSv12,
8205  useRemoteCipherPrefer: true,
8206  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
8207  cipherSuite: "AES256-SHA256"
8208}
8209let tlsConnectOptions: socket.TLSConnectOptions = {
8210  address: netAddress,
8211  secureOptions: tlsSecureOptions,
8212  ALPNProtocols: ["spdy/1", "http/1.1"]
8213}
8214tlsServer.listen(tlsConnectOptions).then(() => {
8215  console.log("listen callback success");
8216}).catch((err: BusinessError) => {
8217  console.log("failed: " + JSON.stringify(err));
8218});
8219
8220let callback = (data: socket.TLSSocketConnection) => {
8221  console.log('on connect message: ' + JSON.stringify(data));
8222}
8223tlsServer.on('connect', callback);
8224// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
8225tlsServer.off('connect', callback);
8226tlsServer.off('connect');
8227```
8228
8229### on('error')<sup>10+</sup>
8230
8231on(type: 'error', callback: ErrorCallback): void
8232
8233Subscribes to **error** events of a **TLSSocketServer** object. This API uses an asynchronous callback to return the result.
8234
8235> **NOTE**
8236> This API can be called only after **listen** is successfully called.
8237
8238**System capability**: SystemCapability.Communication.NetStack
8239
8240**Parameters**
8241
8242| Name  | Type         | Mandatory| Description                                |
8243| -------- | ------------- | ---- | ------------------------------------ |
8244| type     | string        | Yes  | Event type.<br/> **error**: error event.|
8245| callback | ErrorCallback | Yes  | Callback used to return the result. If the operation fails, an error message is returned.    |
8246
8247**Error codes**
8248
8249| ID| Error Message        |
8250| -------- | ---------------- |
8251| 401      | Parameter error. |
8252
8253**Example**
8254
8255```ts
8256import { socket } from '@kit.NetworkKit';
8257import { BusinessError } from '@kit.BasicServicesKit';
8258
8259let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
8260let netAddress: socket.NetAddress = {
8261  address: '192.168.xx.xxx',
8262  port: 8080
8263}
8264let tlsSecureOptions: socket.TLSSecureOptions = {
8265  key: "xxxx",
8266  cert: "xxxx",
8267  ca: ["xxxx"],
8268  password: "xxxx",
8269  protocols: socket.Protocol.TLSv12,
8270  useRemoteCipherPrefer: true,
8271  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
8272  cipherSuite: "AES256-SHA256"
8273}
8274let tlsConnectOptions: socket.TLSConnectOptions = {
8275  address: netAddress,
8276  secureOptions: tlsSecureOptions,
8277  ALPNProtocols: ["spdy/1", "http/1.1"]
8278}
8279tlsServer.listen(tlsConnectOptions).then(() => {
8280  console.log("listen callback success");
8281}).catch((err: BusinessError) => {
8282  console.log("failed: " + JSON.stringify(err));
8283});
8284tlsServer.on('error', (err: BusinessError) => {
8285  console.log("on error, err:" + JSON.stringify(err))
8286});
8287```
8288
8289### off('error')<sup>10+</sup>
8290
8291off(type: 'error', callback?: ErrorCallback): void
8292
8293Unsubscribes from **error** events of a **TLSSocketServer** object. This API uses an asynchronous callback to return the result.
8294
8295> **NOTE**
8296> This API can be called only after **listen** is successfully called.
8297> You can pass the callback of the **on** function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
8298
8299**System capability**: SystemCapability.Communication.NetStack
8300
8301**Parameters**
8302
8303| Name  | Type         | Mandatory| Description                                |
8304| -------- | ------------- | ---- | ------------------------------------ |
8305| type     | string        | Yes  | Event type.<br/> **error**: error event.|
8306| callback | ErrorCallback | No  | Callback used to return the result. If the operation fails, an error message is returned.    |
8307
8308**Error codes**
8309
8310| ID| Error Message        |
8311| -------- | ---------------- |
8312| 401      | Parameter error. |
8313
8314**Example**
8315
8316```ts
8317import { socket } from '@kit.NetworkKit';
8318import { BusinessError } from '@kit.BasicServicesKit';
8319
8320let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
8321let netAddress: socket.NetAddress = {
8322  address: '192.168.xx.xxx',
8323  port: 8080
8324}
8325let tlsSecureOptions: socket.TLSSecureOptions = {
8326  key: "xxxx",
8327  cert: "xxxx",
8328  ca: ["xxxx"],
8329  password: "xxxx",
8330  protocols: socket.Protocol.TLSv12,
8331  useRemoteCipherPrefer: true,
8332  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
8333  cipherSuite: "AES256-SHA256"
8334}
8335let tlsConnectOptions: socket.TLSConnectOptions = {
8336  address: netAddress,
8337  secureOptions: tlsSecureOptions,
8338  ALPNProtocols: ["spdy/1", "http/1.1"]
8339}
8340tlsServer.listen(tlsConnectOptions).then(() => {
8341  console.log("listen callback success");
8342}).catch((err: BusinessError) => {
8343  console.log("failed: " + JSON.stringify(err));
8344});
8345
8346let callback = (err: BusinessError) => {
8347  console.log("on error, err:" + JSON.stringify(err));
8348}
8349tlsServer.on('error', callback);
8350// You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
8351tlsServer.off('error', callback);
8352tlsServer.off('error');
8353```
8354
8355## TLSSocketConnection<sup>10+</sup>
8356
8357Defines a **TLSSocketConnection** object, that is, the connection between the TLSSocket client and the server. Before calling TLSSocketConnection APIs, you need to obtain a **TLSSocketConnection** object.
8358
8359> **NOTE**
8360> The TLSSocket client can call related APIs through the **TLSSocketConnection** object only after a connection is successfully established between the TLSSocket client and the server.
8361
8362**System capability**: SystemCapability.Communication.NetStack
8363
8364### Attributes
8365
8366| Name    | Type  | Mandatory| Description                                 |
8367| -------- | ------ | ---- | ------------------------------------- |
8368| clientId | number | Yes  | ID of the connection between the client and TLSSocketServer.|
8369
8370### send<sup>10+</sup>
8371
8372send(data: string \| ArrayBuffer, callback: AsyncCallback\<void\>): void
8373
8374Sends a message to the client after a TLS socket server connection is established. This API uses an asynchronous callback to return the result.
8375
8376**System capability**: SystemCapability.Communication.NetStack
8377
8378**Parameters**
8379
8380| Name  | Type                 | Mandatory| Description                                            |
8381| -------- | --------------------- | ---- | ------------------------------------------------ |
8382| data     | string \| ArrayBuffer                | Yes  | Parameters for sending data over a TLS socket server connection.           |
8383| callback | AsyncCallback\<void\> | Yes  | Callback used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
8384
8385**Error codes**
8386
8387| ID| Error Message                              |
8388| -------- | -------------------------------------- |
8389| 401      | Parameter error.                       |
8390| 2303501  | SSL is null.                           |
8391| 2303503  | An error occurred when writing data on the TLS socket.|
8392| 2303505  | An error occurred in the TLS system call.|
8393| 2303506  | Failed to close the TLS connection.    |
8394| 2300002  | System internal error.                 |
8395
8396**Example**
8397
8398```ts
8399import { socket } from '@kit.NetworkKit';
8400import { BusinessError } from '@kit.BasicServicesKit';
8401
8402let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
8403let netAddress: socket.NetAddress = {
8404  address: '192.168.xx.xxx',
8405  port: 8080
8406}
8407let tlsSecureOptions: socket.TLSSecureOptions = {
8408  key: "xxxx",
8409  cert: "xxxx",
8410  ca: ["xxxx"],
8411  password: "xxxx",
8412  protocols: socket.Protocol.TLSv12,
8413  useRemoteCipherPrefer: true,
8414  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
8415  cipherSuite: "AES256-SHA256"
8416}
8417let tlsConnectOptions: socket.TLSConnectOptions = {
8418  address: netAddress,
8419  secureOptions: tlsSecureOptions,
8420  ALPNProtocols: ["spdy/1", "http/1.1"]
8421}
8422tlsServer.listen(tlsConnectOptions).then(() => {
8423  console.log("listen callback success");
8424}).catch((err: BusinessError) => {
8425  console.log("failed" + err);
8426});
8427
8428tlsServer.on('connect', (client: socket.TLSSocketConnection) => {
8429  client.send('Hello, client!', (err: BusinessError) => {
8430    if (err) {
8431      console.log('send fail');
8432      return;
8433    }
8434    console.log('send success');
8435  });
8436});
8437```
8438
8439### send<sup>10+</sup>
8440
8441send(data: string \| ArrayBuffer): Promise\<void\>
8442
8443Sends a message to the server after a TLS socket server connection is established. This API uses a promise to return the result.
8444
8445**System capability**: SystemCapability.Communication.NetStack
8446
8447**Parameters**
8448
8449| Name| Type  | Mandatory| Description                                 |
8450| ------ | ------ | ---- | ------------------------------------- |
8451| data   | string \| ArrayBuffer | Yes  | Parameters for sending data over a TLS socket server connection.|
8452
8453**Return value**
8454
8455| Type           | Description                                                     |
8456| --------------- | --------------------------------------------------------- |
8457| Promise\<void\> | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
8458
8459**Error codes**
8460
8461| ID| Error Message                              |
8462| -------- | -------------------------------------- |
8463| 401      | Parameter error.                       |
8464| 2303501  | SSL is null.                           |
8465| 2303503  | An error occurred when writing data on the TLS socket.|
8466| 2303505  | An error occurred in the TLS system call.|
8467| 2303506  | Failed to close the TLS connection.    |
8468| 2300002  | System internal error.                 |
8469
8470**Example**
8471
8472```ts
8473import { socket } from '@kit.NetworkKit';
8474import { BusinessError } from '@kit.BasicServicesKit';
8475
8476let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
8477let netAddress: socket.NetAddress = {
8478  address: '192.168.xx.xxx',
8479  port: 8080
8480}
8481let tlsSecureOptions: socket.TLSSecureOptions = {
8482  key: "xxxx",
8483  cert: "xxxx",
8484  ca: ["xxxx"],
8485  password: "xxxx",
8486  protocols: socket.Protocol.TLSv12,
8487  useRemoteCipherPrefer: true,
8488  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
8489  cipherSuite: "AES256-SHA256"
8490}
8491let tlsConnectOptions: socket.TLSConnectOptions = {
8492  address: netAddress,
8493  secureOptions: tlsSecureOptions,
8494  ALPNProtocols: ["spdy/1", "http/1.1"]
8495}
8496tlsServer.listen(tlsConnectOptions).then(() => {
8497  console.log("listen callback success");
8498}).catch((err: BusinessError) => {
8499  console.log("failed" + err);
8500});
8501
8502tlsServer.on('connect', (client: socket.TLSSocketConnection) => {
8503  client.send('Hello, client!').then(() => {
8504    console.log('send success');
8505  }).catch((err: BusinessError) => {
8506    console.log('send fail');
8507  });
8508});
8509```
8510
8511### close<sup>10+</sup>
8512
8513close(callback: AsyncCallback\<void\>): void
8514
8515Closes a TLS socket server connection. This API uses an asynchronous callback to return the result.
8516
8517**System capability**: SystemCapability.Communication.NetStack
8518
8519**Parameters**
8520
8521| Name  | Type                 | Mandatory| Description                                            |
8522| -------- | --------------------- | ---- | ------------------------------------------------ |
8523| callback | AsyncCallback\<void\> | Yes  | Callback used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
8524
8525**Error codes**
8526
8527| ID| Error Message                              |
8528| -------- | -------------------------------------- |
8529| 401      | Parameter error.                       |
8530| 2303501  | SSL is null.                           |
8531| 2303505  | An error occurred in the TLS system call. |
8532| 2303506  | Failed to close the TLS connection.    |
8533| 2300002  | System internal error.                 |
8534
8535**Example**
8536
8537```ts
8538import { socket } from '@kit.NetworkKit';
8539import { BusinessError } from '@kit.BasicServicesKit';
8540
8541let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
8542let netAddress: socket.NetAddress = {
8543  address: '192.168.xx.xxx',
8544  port: 8080
8545}
8546let tlsSecureOptions: socket.TLSSecureOptions = {
8547  key: "xxxx",
8548  cert: "xxxx",
8549  ca: ["xxxx"],
8550  password: "xxxx",
8551  protocols: socket.Protocol.TLSv12,
8552  useRemoteCipherPrefer: true,
8553  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
8554  cipherSuite: "AES256-SHA256"
8555}
8556let tlsConnectOptions: socket.TLSConnectOptions = {
8557  address: netAddress,
8558  secureOptions: tlsSecureOptions,
8559  ALPNProtocols: ["spdy/1", "http/1.1"]
8560}
8561tlsServer.listen(tlsConnectOptions).then(() => {
8562  console.log("listen callback success");
8563}).catch((err: BusinessError) => {
8564  console.log("failed" + err);
8565});
8566
8567tlsServer.on('connect', (client: socket.TLSSocketConnection) => {
8568  client.close((err: BusinessError) => {
8569    if (err) {
8570      console.log('close fail');
8571      return;
8572    }
8573    console.log('close success');
8574  });
8575});
8576```
8577
8578### close<sup>10+</sup>
8579
8580close(): Promise\<void\>
8581
8582Closes a TLS socket server connection. This API uses a promise to return the result.
8583
8584**System capability**: SystemCapability.Communication.NetStack
8585
8586**Return value**
8587
8588| Type           | Description                                                     |
8589| --------------- | --------------------------------------------------------- |
8590| Promise\<void\> | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned. If the operation fails, an error message is returned.|
8591
8592**Error codes**
8593
8594| ID| Error Message                              |
8595| -------- | -------------------------------------- |
8596| 2303501  | SSL is null.                           |
8597| 2303505  | An error occurred in the TLS system call. |
8598| 2303506  | Failed to close the TLS connection.    |
8599| 2300002  | System internal error.                 |
8600
8601**Example**
8602
8603```ts
8604import { socket } from '@kit.NetworkKit';
8605import { BusinessError } from '@kit.BasicServicesKit';
8606
8607let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
8608let netAddress: socket.NetAddress = {
8609  address: '192.168.xx.xxx',
8610  port: 8080
8611}
8612let tlsSecureOptions: socket.TLSSecureOptions = {
8613  key: "xxxx",
8614  cert: "xxxx",
8615  ca: ["xxxx"],
8616  password: "xxxx",
8617  protocols: socket.Protocol.TLSv12,
8618  useRemoteCipherPrefer: true,
8619  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
8620  cipherSuite: "AES256-SHA256"
8621}
8622let tlsConnectOptions: socket.TLSConnectOptions = {
8623  address: netAddress,
8624  secureOptions: tlsSecureOptions,
8625  ALPNProtocols: ["spdy/1", "http/1.1"]
8626}
8627tlsServer.listen(tlsConnectOptions).then(() => {
8628  console.log("listen callback success");
8629}).catch((err: BusinessError) => {
8630  console.log("failed" + err);
8631});
8632tlsServer.on('connect', (client: socket.TLSSocketConnection) => {
8633  client.close().then(() => {
8634    console.log('close success');
8635  }).catch((err: BusinessError) => {
8636    console.log('close fail');
8637  });
8638});
8639```
8640
8641### getRemoteAddress<sup>10+</sup>
8642
8643getRemoteAddress(callback: AsyncCallback\<NetAddress\>): void
8644
8645Obtains the remote address of a TLS socket server connection. This API uses an asynchronous callback to return the result.
8646
8647**System capability**: SystemCapability.Communication.NetStack
8648
8649**Parameters**
8650
8651| Name  | Type                                       | Mandatory| Description                                                        |
8652| -------- | ------------------------------------------- | ---- | ------------------------------------------------------------ |
8653| callback | AsyncCallback\<[NetAddress](#netaddress)\> | Yes  | Callback used to return the result. If the operation is successful, the remote address is returned. If the operation fails, an error message is returned.|
8654
8655**Error codes**
8656
8657| ID| Error Message                       |
8658| -------- | ------------------------------- |
8659| 401      | Parameter error.                |
8660| 2303188  | Socket operation on non-socket. |
8661| 2300002  | System internal error.          |
8662
8663**Example**
8664
8665```ts
8666import { socket } from '@kit.NetworkKit';
8667import { BusinessError } from '@kit.BasicServicesKit';
8668
8669let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
8670let netAddress: socket.NetAddress = {
8671  address: '192.168.xx.xxx',
8672  port: 8080
8673}
8674let tlsSecureOptions: socket.TLSSecureOptions = {
8675  key: "xxxx",
8676  cert: "xxxx",
8677  ca: ["xxxx"],
8678  password: "xxxx",
8679  protocols: socket.Protocol.TLSv12,
8680  useRemoteCipherPrefer: true,
8681  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
8682  cipherSuite: "AES256-SHA256"
8683}
8684let tlsConnectOptions: socket.TLSConnectOptions = {
8685  address: netAddress,
8686  secureOptions: tlsSecureOptions,
8687  ALPNProtocols: ["spdy/1", "http/1.1"]
8688}
8689tlsServer.listen(tlsConnectOptions).then(() => {
8690  console.log("listen callback success");
8691}).catch((err: BusinessError) => {
8692  console.log("failed" + err);
8693});
8694tlsServer.on('connect', (client: socket.TLSSocketConnection) => {
8695  client.getRemoteAddress((err: BusinessError, data: socket.NetAddress) => {
8696    if (err) {
8697      console.log('getRemoteAddress fail');
8698      return;
8699    }
8700    console.log('getRemoteAddress success:' + JSON.stringify(data));
8701  });
8702});
8703```
8704
8705### getRemoteAddress<sup>10+</sup>
8706
8707getRemoteAddress(): Promise\<NetAddress\>
8708
8709Obtains the remote address of a TLS socket server connection. This API uses a promise to return the result.
8710
8711**System capability**: SystemCapability.Communication.NetStack
8712
8713**Return value**
8714
8715| Type                                | Description                                                        |
8716|  ----------------------------------- |  ----------------------------------------------------------- |
8717| Promise\<[NetAddress](#netaddress)\> | Promise used to return the result. If the operation fails, an error message is returned.|
8718
8719**Error codes**
8720
8721| ID| Error Message                       |
8722| -------- | ------------------------------- |
8723| 2303188  | Socket operation on non-socket. |
8724| 2300002  | System internal error.          |
8725
8726**Example**
8727
8728```ts
8729import { socket } from '@kit.NetworkKit';
8730import { BusinessError } from '@kit.BasicServicesKit';
8731
8732let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
8733let netAddress: socket.NetAddress = {
8734  address: '192.168.xx.xxx',
8735  port: 8080
8736}
8737let tlsSecureOptions: socket.TLSSecureOptions = {
8738  key: "xxxx",
8739  cert: "xxxx",
8740  ca: ["xxxx"],
8741  password: "xxxx",
8742  protocols: socket.Protocol.TLSv12,
8743  useRemoteCipherPrefer: true,
8744  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
8745  cipherSuite: "AES256-SHA256"
8746}
8747let tlsConnectOptions: socket.TLSConnectOptions = {
8748  address: netAddress,
8749  secureOptions: tlsSecureOptions,
8750  ALPNProtocols: ["spdy/1", "http/1.1"]
8751}
8752tlsServer.listen(tlsConnectOptions).then(() => {
8753  console.log("listen callback success");
8754}).catch((err: BusinessError) => {
8755  console.log("failed" + err);
8756});
8757tlsServer.on('connect', (client: socket.TLSSocketConnection) => {
8758  client.getRemoteAddress().then((data: socket.NetAddress) => {
8759    console.log('getRemoteAddress success:' + JSON.stringify(data));
8760  }).catch((err: BusinessError) => {
8761    console.error("failed" + err);
8762  });
8763});
8764```
8765
8766### getRemoteCertificate<sup>10+</sup>
8767
8768getRemoteCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)\>): void
8769
8770Obtains the digital certificate of the peer end after a TLS socket server connection is established. This API uses an asynchronous callback to return the result. It applies only to the scenario where the client sends a certificate to the server.
8771
8772**System capability**: SystemCapability.Communication.NetStack
8773
8774**Parameters**
8775
8776| Name  | Type                                                 | Mandatory| Description                                                |
8777| -------- | ----------------------------------------------------- | ---- | ---------------------------------------------------- |
8778| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)\> | Yes  | Callback used to return the result. If the operation fails, an error message is returned.|
8779
8780**Error codes**
8781
8782| ID| Error Message              |
8783| -------- | ---------------------- |
8784| 401      | Parameter error.       |
8785| 2303501  | SSL is null.           |
8786| 2300002  | System internal error. |
8787
8788**Example**
8789
8790```ts
8791import { socket } from '@kit.NetworkKit';
8792import { BusinessError } from '@kit.BasicServicesKit';
8793import { util } from '@kit.ArkTS';
8794
8795let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
8796let netAddress: socket.NetAddress = {
8797  address: '192.168.xx.xxx',
8798  port: 8080
8799}
8800let tlsSecureOptions: socket.TLSSecureOptions = {
8801  key: "xxxx",
8802  cert: "xxxx",
8803  ca: ["xxxx"],
8804  password: "xxxx",
8805  protocols: socket.Protocol.TLSv12,
8806  useRemoteCipherPrefer: true,
8807  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
8808  cipherSuite: "AES256-SHA256"
8809}
8810let tlsConnectOptions: socket.TLSConnectOptions = {
8811  address: netAddress,
8812  secureOptions: tlsSecureOptions,
8813  ALPNProtocols: ["spdy/1", "http/1.1"]
8814}
8815tlsServer.listen(tlsConnectOptions).then(() => {
8816  console.log("listen callback success");
8817}).catch((err: BusinessError) => {
8818  console.log("failed" + err);
8819});
8820tlsServer.on('connect', (client: socket.TLSSocketConnection) => {
8821  client.getRemoteCertificate((err: BusinessError, data: socket.X509CertRawData) => {
8822    if (err) {
8823      console.log("getRemoteCertificate callback error: " + err);
8824    } else {
8825      const decoder = util.TextDecoder.create();
8826      const str = decoder.decodeWithStream(data.data);
8827      console.log("getRemoteCertificate callback: " + str);
8828    }
8829  });
8830});
8831```
8832
8833### getRemoteCertificate<sup>10+</sup>
8834
8835getRemoteCertificate():Promise\<[X509CertRawData](#x509certrawdata9)\>
8836
8837Obtains the digital certificate of the peer end after a TLS socket server connection is established. This API uses a promise to return the result. It applies only to the scenario where the client sends a certificate to the server.
8838
8839**System capability**: SystemCapability.Communication.NetStack
8840
8841**Return value**
8842
8843| Type                                           | Description                                                        |
8844| ----------------------------------------------- | ------------------------------------------------------------ |
8845| Promise\<[X509CertRawData](#x509certrawdata9)\> | Promise used to return the result. If the operation fails, an error message is returned.|
8846
8847**Error codes**
8848
8849| ID| Error Message              |
8850| -------- | ---------------------- |
8851| 2303501  | SSL is null.           |
8852| 2300002  | System internal error. |
8853
8854**Example**
8855
8856```ts
8857import { socket } from '@kit.NetworkKit';
8858import { BusinessError } from '@kit.BasicServicesKit';
8859import { util } from '@kit.ArkTS';
8860
8861let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
8862let netAddress: socket.NetAddress = {
8863  address: '192.168.xx.xxx',
8864  port: 8080
8865}
8866let tlsSecureOptions: socket.TLSSecureOptions = {
8867  key: "xxxx",
8868  cert: "xxxx",
8869  ca: ["xxxx"],
8870  password: "xxxx",
8871  protocols: socket.Protocol.TLSv12,
8872  useRemoteCipherPrefer: true,
8873  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
8874  cipherSuite: "AES256-SHA256"
8875}
8876let tlsConnectOptions: socket.TLSConnectOptions = {
8877  address: netAddress,
8878  secureOptions: tlsSecureOptions,
8879  ALPNProtocols: ["spdy/1", "http/1.1"]
8880}
8881tlsServer.listen(tlsConnectOptions).then(() => {
8882  console.log("listen callback success");
8883}).catch((err: BusinessError) => {
8884  console.log("failed" + err);
8885});
8886tlsServer.on('connect', (client: socket.TLSSocketConnection) => {
8887  client.getRemoteCertificate().then((data: socket.X509CertRawData) => {
8888    const decoder = util.TextDecoder.create();
8889    const str = decoder.decodeWithStream(data.data);
8890    console.log("getRemoteCertificate success: " + str);
8891  }).catch((err: BusinessError) => {
8892    console.error("failed" + err);
8893  });
8894});
8895```
8896
8897### getCipherSuite<sup>10+</sup>
8898
8899getCipherSuite(callback: AsyncCallback\<Array\<string\>\>): void
8900
8901Obtains the cipher suite negotiated by both communication parties after a TLS socket server connection is established. This API uses an asynchronous callback to return the result.
8902
8903**System capability**: SystemCapability.Communication.NetStack
8904
8905**Parameters**
8906
8907| Name  | Type                            | Mandatory| Description                                                        |
8908| -------- | -------------------------------- | ---- | ------------------------------------------------------------ |
8909| callback | AsyncCallback\<Array\<string\>\> | Yes  | Callback used to return the result. If the operation fails, an error message is returned.|
8910
8911**Error codes**
8912
8913| ID| Error Message                              |
8914| -------- | -------------------------------------- |
8915| 401      | Parameter error.                       |
8916| 2303501  | SSL is null.                           |
8917| 2303502  | An error occurred when reading data on the TLS socket.|
8918| 2303505  | An error occurred in the TLS system call.|
8919| 2300002  | System internal error.                 |
8920
8921**Example**
8922
8923```ts
8924import { socket } from '@kit.NetworkKit';
8925import { BusinessError } from '@kit.BasicServicesKit';
8926
8927let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
8928let netAddress: socket.NetAddress = {
8929  address: '192.168.xx.xxx',
8930  port: 8080
8931}
8932let tlsSecureOptions: socket.TLSSecureOptions = {
8933  key: "xxxx",
8934  cert: "xxxx",
8935  ca: ["xxxx"],
8936  password: "xxxx",
8937  protocols: socket.Protocol.TLSv12,
8938  useRemoteCipherPrefer: true,
8939  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
8940  cipherSuite: "AES256-SHA256"
8941}
8942let tlsConnectOptions: socket.TLSConnectOptions = {
8943  address: netAddress,
8944  secureOptions: tlsSecureOptions,
8945  ALPNProtocols: ["spdy/1", "http/1.1"]
8946}
8947tlsServer.listen(tlsConnectOptions).then(() => {
8948  console.log("listen callback success");
8949}).catch((err: BusinessError) => {
8950  console.log("failed" + err);
8951});
8952tlsServer.on('connect', (client: socket.TLSSocketConnection) => {
8953  client.getCipherSuite((err: BusinessError, data: Array<string>) => {
8954    if (err) {
8955      console.log("getCipherSuite callback error = " + err);
8956    } else {
8957      console.log("getCipherSuite callback = " + data);
8958    }
8959  });
8960});
8961```
8962
8963### getCipherSuite<sup>10+</sup>
8964
8965getCipherSuite(): Promise\<Array\<string\>\>
8966
8967Obtains the cipher suite negotiated by both communication parties after a TLS socket server connection is established. This API uses a promise to return the result.
8968
8969**System capability**: SystemCapability.Communication.NetStack
8970
8971**Return value**
8972
8973| Type                      | Description                                                        |
8974| -------------------------- | ------------------------------------------------------------ |
8975| Promise\<Array\<string\>\> | Promise used to return the result. If the operation fails, an error message is returned.|
8976
8977**Error codes**
8978
8979| ID| Error Message                              |
8980| -------- | -------------------------------------- |
8981| 2303501  | SSL is null.                           |
8982| 2303502  | An error occurred when reading data on the TLS socket.|
8983| 2303505  | An error occurred in the TLS system call. |
8984| 2300002  | System internal error.                 |
8985
8986**Example**
8987
8988```ts
8989import { socket } from '@kit.NetworkKit';
8990import { BusinessError } from '@kit.BasicServicesKit';
8991
8992let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
8993let netAddress: socket.NetAddress = {
8994  address: '192.168.xx.xxx',
8995  port: 8080
8996}
8997let tlsSecureOptions: socket.TLSSecureOptions = {
8998  key: "xxxx",
8999  cert: "xxxx",
9000  ca: ["xxxx"],
9001  password: "xxxx",
9002  protocols: socket.Protocol.TLSv12,
9003  useRemoteCipherPrefer: true,
9004  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
9005  cipherSuite: "AES256-SHA256"
9006}
9007let tlsConnectOptions: socket.TLSConnectOptions = {
9008  address: netAddress,
9009  secureOptions: tlsSecureOptions,
9010  ALPNProtocols: ["spdy/1", "http/1.1"]
9011}
9012tlsServer.listen(tlsConnectOptions).then(() => {
9013  console.log("listen callback success");
9014}).catch((err: BusinessError) => {
9015  console.log("failed" + err);
9016});
9017tlsServer.on('connect', (client: socket.TLSSocketConnection) => {
9018  client.getCipherSuite().then((data: Array<string>) => {
9019    console.log('getCipherSuite success:' + JSON.stringify(data));
9020  }).catch((err: BusinessError) => {
9021    console.error("failed" + err);
9022  });
9023});
9024```
9025
9026### getSignatureAlgorithms<sup>10+</sup>
9027
9028getSignatureAlgorithms(callback: AsyncCallback\<Array\<string\>\>): void
9029
9030Obtains the signing algorithm negotiated by both communication parties after a TLS socket server connection is established. This API uses an asynchronous callback to return the result.
9031
9032**System capability**: SystemCapability.Communication.NetStack
9033
9034**Parameters**
9035
9036| Name  | Type                            | Mandatory| Description                              |
9037| -------- | -------------------------------- | ---- | ---------------------------------- |
9038| callback | AsyncCallback\<Array\<string\>\> | Yes  | Callback used to return the result. |
9039
9040**Error codes**
9041
9042| ID| Error Message              |
9043| -------- | ---------------------- |
9044| 401      | Parameter error.       |
9045| 2303501  | SSL is null.           |
9046| 2300002  | System internal error. |
9047
9048**Example**
9049
9050```ts
9051import { socket } from '@kit.NetworkKit';
9052import { BusinessError } from '@kit.BasicServicesKit';
9053
9054let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
9055let netAddress: socket.NetAddress = {
9056  address: '192.168.xx.xxx',
9057  port: 8080
9058}
9059let tlsSecureOptions: socket.TLSSecureOptions = {
9060  key: "xxxx",
9061  cert: "xxxx",
9062  ca: ["xxxx"],
9063  password: "xxxx",
9064  protocols: socket.Protocol.TLSv12,
9065  useRemoteCipherPrefer: true,
9066  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
9067  cipherSuite: "AES256-SHA256"
9068}
9069let tlsConnectOptions: socket.TLSConnectOptions = {
9070  address: netAddress,
9071  secureOptions: tlsSecureOptions,
9072  ALPNProtocols: ["spdy/1", "http/1.1"]
9073}
9074tlsServer.listen(tlsConnectOptions).then(() => {
9075  console.log("listen callback success");
9076}).catch((err: BusinessError) => {
9077  console.log("failed" + err);
9078});
9079tlsServer.on('connect', (client: socket.TLSSocketConnection) => {
9080  client.getSignatureAlgorithms((err: BusinessError, data: Array<string>) => {
9081    if (err) {
9082      console.log("getSignatureAlgorithms callback error = " + err);
9083    } else {
9084      console.log("getSignatureAlgorithms callback = " + data);
9085    }
9086  });
9087});
9088```
9089
9090### getSignatureAlgorithms<sup>10+</sup>
9091
9092getSignatureAlgorithms(): Promise\<Array\<string\>\>
9093
9094Obtains the signing algorithm negotiated by both communication parties after a TLS socket server connection is established. This API uses a promise to return the result.
9095
9096**System capability**: SystemCapability.Communication.NetStack
9097
9098**Return value**
9099
9100| Type                      | Description                                         |
9101| -------------------------- | --------------------------------------------- |
9102| Promise\<Array\<string\>\> | Promise used to return the result.|
9103
9104**Error codes**
9105
9106| ID| Error Message              |
9107| -------- | ---------------------- |
9108| 2303501  | SSL is null.           |
9109| 2300002  | System internal error. |
9110
9111**Example**
9112
9113```ts
9114import { socket } from '@kit.NetworkKit';
9115import { BusinessError } from '@kit.BasicServicesKit';
9116
9117let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
9118let netAddress: socket.NetAddress = {
9119  address: '192.168.xx.xxx',
9120  port: 8080
9121}
9122let tlsSecureOptions: socket.TLSSecureOptions = {
9123  key: "xxxx",
9124  cert: "xxxx",
9125  ca: ["xxxx"],
9126  password: "xxxx",
9127  protocols: socket.Protocol.TLSv12,
9128  useRemoteCipherPrefer: true,
9129  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
9130  cipherSuite: "AES256-SHA256"
9131}
9132let tlsConnectOptions: socket.TLSConnectOptions = {
9133  address: netAddress,
9134  secureOptions: tlsSecureOptions,
9135  ALPNProtocols: ["spdy/1", "http/1.1"]
9136}
9137tlsServer.listen(tlsConnectOptions).then(() => {
9138  console.log("listen callback success");
9139}).catch((err: BusinessError) => {
9140  console.log("failed" + err);
9141});
9142tlsServer.on('connect', (client: socket.TLSSocketConnection) => {
9143  client.getSignatureAlgorithms().then((data: Array<string>) => {
9144    console.log("getSignatureAlgorithms success" + data);
9145  }).catch((err: BusinessError) => {
9146    console.error("failed" + err);
9147  });
9148});
9149```
9150
9151### getLocalAddress<sup>12+</sup>
9152
9153getLocalAddress(): Promise\<NetAddress\>
9154
9155Obtains the local socket address of a **TLSSocketConnection** connection. This API uses a promise to return the result.
9156
9157> **NOTE**
9158> Call this API only after the **TLSSocketServer** connection is successfully established.
9159
9160**System capability**: SystemCapability.Communication.NetStack
9161
9162**Return value**
9163
9164| Type           | Description                                                |
9165|  -------------- |  --------------------------------------------------- |
9166| Promise\<[NetAddress](#netaddress)\> | Promise used to return the result.|
9167
9168**Error codes**
9169
9170| ID| Error Message                                   |
9171| -------- | ------------------------------------------- |
9172| 2300002  | System internal error.                      |
9173| 2301009  | Bad file descriptor.                            |
9174| 2303188  | Socket operation on non-socket. |
9175
9176**Example**
9177
9178```ts
9179import { socket } from '@kit.NetworkKit';
9180import { BusinessError } from '@kit.BasicServicesKit';
9181
9182let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
9183let netAddress: socket.NetAddress = {
9184  address: '192.168.xx.xxx',
9185  port: 8080
9186}
9187let tlsSecureOptions: socket.TLSSecureOptions = {
9188  key: "xxxx",
9189  cert: "xxxx",
9190  ca: ["xxxx"],
9191  password: "xxxx",
9192  protocols: socket.Protocol.TLSv12,
9193  useRemoteCipherPrefer: true,
9194  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
9195  cipherSuite: "AES256-SHA256"
9196}
9197let tlsConnectOptions: socket.TLSConnectOptions = {
9198  address: netAddress,
9199  secureOptions: tlsSecureOptions,
9200  ALPNProtocols: ["spdy/1", "http/1.1"]
9201}
9202tlsServer.listen(tlsConnectOptions).then(() => {
9203  console.info("listen callback success");
9204}).catch((err: BusinessError) => {
9205  console.error("failed" + err);
9206});
9207
9208tlsServer.on('connect', (client: socket.TLSSocketConnection) => {
9209  client.getLocalAddress().then((localAddress: socket.NetAddress) => {
9210    console.info("Family IP Port: " + JSON.stringify(localAddress));
9211  }).catch((err: BusinessError) => {
9212    console.error("TLS Client Get Family IP Port failed, error: " + JSON.stringify(err));
9213  })
9214});
9215```
9216
9217### on('message')<sup>10+</sup>
9218
9219on(type: 'message', callback: Callback\<SocketMessageInfo\>): void
9220
9221Subscribes to **message** events of a **TLSSocketConnection** object. This API uses an asynchronous callback to return the result.
9222
9223**System capability**: SystemCapability.Communication.NetStack
9224
9225**Parameters**
9226
9227| Name  | Type                                                        | Mandatory| Description                                     |
9228| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
9229| type     | string                                                       | Yes  | Event type.<br/> **message**: message receiving event.|
9230| callback | Callback\<[SocketMessageInfo](#socketmessageinfo11)\> | Yes  | Callback used to return the result. If the operation is successful, the TLS socket connection information is returned. If the operation fails, an error message is returned.                              |
9231
9232**Error codes**
9233
9234| ID| Error Message        |
9235| -------- | ---------------- |
9236| 401      | Parameter error. |
9237
9238**Example**
9239
9240```ts
9241import { socket } from '@kit.NetworkKit';
9242import { BusinessError } from '@kit.BasicServicesKit';
9243
9244let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
9245let netAddress: socket.NetAddress = {
9246  address: '192.168.xx.xxx',
9247  port: 8080
9248}
9249let tlsSecureOptions: socket.TLSSecureOptions = {
9250  key: "xxxx",
9251  cert: "xxxx",
9252  ca: ["xxxx"],
9253  password: "xxxx",
9254  protocols: socket.Protocol.TLSv12,
9255  useRemoteCipherPrefer: true,
9256  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
9257  cipherSuite: "AES256-SHA256"
9258}
9259let tlsConnectOptions: socket.TLSConnectOptions = {
9260  address: netAddress,
9261  secureOptions: tlsSecureOptions,
9262  ALPNProtocols: ["spdy/1", "http/1.1"]
9263}
9264tlsServer.listen(tlsConnectOptions).then(() => {
9265  console.log("listen callback success");
9266}).catch((err: BusinessError) => {
9267  console.log("failed" + err);
9268});
9269
9270tlsServer.on('connect', (client: socket.TLSSocketConnection) => {
9271  client.on('message', (value: socket.SocketMessageInfo) => {
9272    let messageView = '';
9273    for (let i: number = 0; i < value.message.byteLength; i++) {
9274      let uint8Array = new Uint8Array(value.message)
9275      let messages = uint8Array[i]
9276      let message = String.fromCharCode(messages);
9277      messageView += message;
9278    }
9279    console.log('on message message: ' + JSON.stringify(messageView));
9280    console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo));
9281  });
9282});
9283```
9284
9285### off('message')<sup>10+</sup>
9286
9287off(type: 'message', callback?: Callback\<SocketMessageInfo\>): void
9288
9289Unsubscribes from **message** events of a **TLSSocketConnection** object. This API uses an asynchronous callback to return the result.
9290
9291**System capability**: SystemCapability.Communication.NetStack
9292
9293**Parameters**
9294
9295| Name  | Type                                                        | Mandatory| Description                                     |
9296| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
9297| type     | string                                                       | Yes  | Event type.<br/> **message**: message receiving event.|
9298| callback | Callback\<[SocketMessageInfo](#socketmessageinfo11)\> | No  | Callback used to return the result. If the operation is successful, the TLS socket connection information is returned. If the operation fails, an error message is returned. |
9299
9300**Error codes**
9301
9302| ID| Error Message        |
9303| -------- | ---------------- |
9304| 401      | Parameter error. |
9305
9306**Example**
9307
9308```ts
9309import { socket } from '@kit.NetworkKit';
9310import { BusinessError } from '@kit.BasicServicesKit';
9311
9312let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
9313let netAddress: socket.NetAddress = {
9314  address: '192.168.xx.xxx',
9315  port: 8080
9316}
9317let tlsSecureOptions: socket.TLSSecureOptions = {
9318  key: "xxxx",
9319  cert: "xxxx",
9320  ca: ["xxxx"],
9321  password: "xxxx",
9322  protocols: socket.Protocol.TLSv12,
9323  useRemoteCipherPrefer: true,
9324  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
9325  cipherSuite: "AES256-SHA256"
9326}
9327let tlsConnectOptions: socket.TLSConnectOptions = {
9328  address: netAddress,
9329  secureOptions: tlsSecureOptions,
9330  ALPNProtocols: ["spdy/1", "http/1.1"]
9331}
9332tlsServer.listen(tlsConnectOptions).then(() => {
9333  console.log("listen callback success");
9334}).catch((err: BusinessError) => {
9335  console.log("failed" + err);
9336});
9337
9338let callback = (value: socket.SocketMessageInfo) => {
9339  let messageView = '';
9340  for (let i: number = 0; i < value.message.byteLength; i++) {
9341    let uint8Array = new Uint8Array(value.message)
9342    let messages = uint8Array[i]
9343    let message = String.fromCharCode(messages);
9344    messageView += message;
9345  }
9346  console.log('on message message: ' + JSON.stringify(messageView));
9347  console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo));
9348}
9349tlsServer.on('connect', (client: socket.TLSSocketConnection) => {
9350  client.on('message', callback);
9351  // You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
9352  client.off('message', callback);
9353  client.off('message');
9354});
9355```
9356
9357### on('close')<sup>10+</sup>
9358
9359on(type: 'close', callback: Callback\<void\>): void
9360
9361Subscribes to **close** events of a **TLSSocketConnection** object. This API uses an asynchronous callback to return the result.
9362
9363**System capability**: SystemCapability.Communication.NetStack
9364
9365**Parameters**
9366
9367| Name  | Type            | Mandatory| Description                               |
9368| -------- | ---------------- | ---- | ----------------------------------- |
9369| type     | string           | Yes  | Event type.<br/> **close**: close event.|
9370| callback | Callback\<void\> | Yes  | Callback used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.   |
9371
9372**Error codes**
9373
9374| ID| Error Message        |
9375| -------- | ---------------- |
9376| 401      | Parameter error. |
9377
9378**Example**
9379
9380```ts
9381import { socket } from '@kit.NetworkKit';
9382import { BusinessError } from '@kit.BasicServicesKit';
9383
9384let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
9385let netAddress: socket.NetAddress = {
9386  address: '192.168.xx.xxx',
9387  port: 8080
9388}
9389let tlsSecureOptions: socket.TLSSecureOptions = {
9390  key: "xxxx",
9391  cert: "xxxx",
9392  ca: ["xxxx"],
9393  password: "xxxx",
9394  protocols: socket.Protocol.TLSv12,
9395  useRemoteCipherPrefer: true,
9396  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
9397  cipherSuite: "AES256-SHA256"
9398}
9399let tlsConnectOptions: socket.TLSConnectOptions = {
9400  address: netAddress,
9401  secureOptions: tlsSecureOptions,
9402  ALPNProtocols: ["spdy/1", "http/1.1"]
9403}
9404tlsServer.listen(tlsConnectOptions).then(() => {
9405  console.log("listen callback success");
9406}).catch((err: BusinessError) => {
9407  console.log("failed" + err);
9408});
9409tlsServer.on('connect', (client: socket.TLSSocketConnection) => {
9410  client.on('close', () => {
9411    console.log("on close success")
9412  });
9413});
9414```
9415
9416### off('close')<sup>10+</sup>
9417
9418off(type: 'close', callback?: Callback\<void\>): void
9419
9420Unsubscribes from **close** events of a **TLSSocketConnection** object. This API uses an asynchronous callback to return the result.
9421
9422**System capability**: SystemCapability.Communication.NetStack
9423
9424**Parameters**
9425
9426| Name  | Type            | Mandatory| Description                               |
9427| -------- | ---------------- | ---- | ----------------------------------- |
9428| type     | string           | Yes  | Event type.<br/> **close**: close event.|
9429| callback | Callback\<void\> | No  | Callback used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.                        |
9430
9431**Error codes**
9432
9433| ID| Error Message        |
9434| -------- | ---------------- |
9435| 401      | Parameter error. |
9436
9437**Example**
9438
9439```ts
9440import { socket } from '@kit.NetworkKit';
9441import { BusinessError } from '@kit.BasicServicesKit';
9442
9443let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
9444let netAddress: socket.NetAddress = {
9445  address: '192.168.xx.xxx',
9446  port: 8080
9447}
9448let tlsSecureOptions: socket.TLSSecureOptions = {
9449  key: "xxxx",
9450  cert: "xxxx",
9451  ca: ["xxxx"],
9452  password: "xxxx",
9453  protocols: socket.Protocol.TLSv12,
9454  useRemoteCipherPrefer: true,
9455  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
9456  cipherSuite: "AES256-SHA256"
9457}
9458let tlsConnectOptions: socket.TLSConnectOptions = {
9459  address: netAddress,
9460  secureOptions: tlsSecureOptions,
9461  ALPNProtocols: ["spdy/1", "http/1.1"]
9462}
9463tlsServer.listen(tlsConnectOptions).then(() => {
9464  console.log("listen callback success");
9465}).catch((err: BusinessError) => {
9466  console.log("failed" + err);
9467});
9468
9469let callback = () => {
9470  console.log("on close success");
9471}
9472tlsServer.on('connect', (client: socket.TLSSocketConnection) => {
9473  client.on('close', callback);
9474  // You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
9475  client.off('close', callback);
9476  client.off('close');
9477});
9478```
9479
9480### on('error')<sup>10+</sup>
9481
9482on(type: 'error', callback: ErrorCallback): void
9483
9484Subscribes to **error** events of a **TLSSocketConnection** object. This API uses an asynchronous callback to return the result.
9485
9486**System capability**: SystemCapability.Communication.NetStack
9487
9488**Parameters**
9489
9490| Name  | Type         | Mandatory| Description                                |
9491| -------- | ------------- | ---- | ------------------------------------ |
9492| type     | string        | Yes  | Event type.<br/> **error**: error event.|
9493| callback | ErrorCallback | Yes  | Callback used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.                       |
9494
9495**Error codes**
9496
9497| ID| Error Message        |
9498| -------- | ---------------- |
9499| 401      | Parameter error. |
9500
9501**Example**
9502
9503```ts
9504import { socket } from '@kit.NetworkKit';
9505import { BusinessError } from '@kit.BasicServicesKit';
9506
9507let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
9508let netAddress: socket.NetAddress = {
9509  address: '192.168.xx.xxx',
9510  port: 8080
9511}
9512let tlsSecureOptions: socket.TLSSecureOptions = {
9513  key: "xxxx",
9514  cert: "xxxx",
9515  ca: ["xxxx"],
9516  password: "xxxx",
9517  protocols: socket.Protocol.TLSv12,
9518  useRemoteCipherPrefer: true,
9519  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
9520  cipherSuite: "AES256-SHA256"
9521}
9522let tlsConnectOptions: socket.TLSConnectOptions = {
9523  address: netAddress,
9524  secureOptions: tlsSecureOptions,
9525  ALPNProtocols: ["spdy/1", "http/1.1"]
9526}
9527tlsServer.listen(tlsConnectOptions).then(() => {
9528  console.log("listen callback success");
9529}).catch((err: BusinessError) => {
9530  console.log("failed" + err);
9531});
9532
9533tlsServer.on('connect', (client: socket.TLSSocketConnection) => {
9534  client.on('error', (err: BusinessError) => {
9535    console.log("on error, err:" + JSON.stringify(err))
9536  });
9537});
9538```
9539
9540### off('error')<sup>10+</sup>
9541
9542off(type: 'error', callback?: ErrorCallback): void
9543
9544Unsubscribes from **error** events of a **TLSSocketConnection** object. This API uses an asynchronous callback to return the result.
9545
9546**System capability**: SystemCapability.Communication.NetStack
9547
9548**Parameters**
9549
9550| Name  | Type         | Mandatory| Description                                |
9551| -------- | ------------- | ---- | ------------------------------------ |
9552| type     | string        | Yes  | Event type.<br/> **error**: error event.|
9553| callback | ErrorCallback | No  | Callback used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.                       |
9554
9555**Error codes**
9556
9557| ID| Error Message        |
9558| -------- | ---------------- |
9559| 401      | Parameter error. |
9560
9561**Example**
9562
9563```ts
9564import { socket } from '@kit.NetworkKit';
9565import { BusinessError } from '@kit.BasicServicesKit';
9566
9567let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
9568let netAddress: socket.NetAddress = {
9569  address: '192.168.xx.xxx',
9570  port: 8080
9571}
9572let tlsSecureOptions: socket.TLSSecureOptions = {
9573  key: "xxxx",
9574  cert: "xxxx",
9575  ca: ["xxxx"],
9576  password: "xxxx",
9577  protocols: socket.Protocol.TLSv12,
9578  useRemoteCipherPrefer: true,
9579  signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
9580  cipherSuite: "AES256-SHA256"
9581}
9582let tlsConnectOptions: socket.TLSConnectOptions = {
9583  address: netAddress,
9584  secureOptions: tlsSecureOptions,
9585  ALPNProtocols: ["spdy/1", "http/1.1"]
9586}
9587tlsServer.listen(tlsConnectOptions).then(() => {
9588  console.log("listen callback success");
9589}).catch((err: BusinessError) => {
9590  console.log("failed" + err);
9591});
9592
9593let callback = (err: BusinessError) => {
9594  console.log("on error, err:" + JSON.stringify(err));
9595}
9596tlsServer.on('connect', (client: socket.TLSSocketConnection) => {
9597  client.on('error', callback);
9598  // You can pass the callback of the on function if you want to cancel listening for a certain type of events. If you do not pass the callback, you will cancel listening for all events.
9599  client.off('error', callback);
9600  client.off('error');
9601});
9602```
9603