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