• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# # @ohos.net.socket (Socket Connection)
2
3The **socket** module implements data transfer over TCPSocket, UDPSocket, WebSocket, and TLSSocket connections.
4
5> **NOTE**
6>
7> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8
9## Modules to Import
10
11```js
12import socket from '@ohos.net.socket';
13```
14
15## socket.constructUDPSocketInstance
16
17constructUDPSocketInstance(): UDPSocket
18
19Creates a **UDPSocket** object.
20
21**System capability**: SystemCapability.Communication.NetStack
22
23**Return value**
24
25| Type                              | Description                   |
26| :--------------------------------- | :---------------------- |
27| [UDPSocket](#udpsocket) | **UDPSocket** object.|
28
29**Example**
30
31```js
32let udp = socket.constructUDPSocketInstance();
33```
34
35## UDPSocket<sup>7+</sup>
36
37Defines a **UDPSocket** connection. Before invoking UDPSocket APIs, you need to call [socket.constructUDPSocketInstance](#socketconstructudpsocketinstance) to create a **UDPSocket** object.
38
39### bind<sup>7+</sup>
40
41bind(address: NetAddress, callback: AsyncCallback\<void\>): void
42
43Binds 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.
44
45> **NOTE**
46> This API is used for the client to create a socket.
47
48**Required permissions**: ohos.permission.INTERNET
49
50**System capability**: SystemCapability.Communication.NetStack
51
52**Parameters**
53
54| Name  | Type                              | Mandatory| Description                                                  |
55| -------- | ---------------------------------- | ---- | ------------------------------------------------------ |
56| address  | [NetAddress](#netaddress) | Yes  | Destination address. For details, see [NetAddress](#netaddress).|
57| callback | AsyncCallback\<void\>              | Yes  | Callback used to return the result.                                            |
58
59**Error codes**
60
61| ID| Error Message                |
62| ------- | ----------------------- |
63| 401     | Parameter error.        |
64| 201     | Permission denied.      |
65
66**Example**
67
68```js
69let udp = socket.constructUDPSocketInstance();
70udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
71  if (err) {
72    console.log('bind fail');
73    return;
74  }
75  console.log('bind success');
76})
77```
78
79### bind<sup>7+</sup>
80
81bind(address: NetAddress): Promise\<void\>
82
83Binds 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.
84
85> **NOTE**
86> This API is used for the client to create a socket.
87
88**Required permissions**: ohos.permission.INTERNET
89
90**System capability**: SystemCapability.Communication.NetStack
91
92**Parameters**
93
94| Name | Type                              | Mandatory| Description                                                  |
95| ------- | ---------------------------------- | ---- | ------------------------------------------------------ |
96| address | [NetAddress](#netaddress) | Yes  | Destination address. For details, see [NetAddress](#netaddress).|
97
98**Error codes**
99
100| ID| Error Message                |
101| ------- | ----------------------- |
102| 401     | Parameter error.        |
103| 201     | Permission denied.      |
104
105**Return value**
106
107| Type           | Description                                      |
108| :-------------- | :----------------------------------------- |
109| Promise\<void\> | Promise used to return the result.|
110
111**Example**
112
113```js
114let udp = socket.constructUDPSocketInstance();
115let promise = udp.bind({address: '192.168.xx.xxx', port: 8080, family: 1});
116promise.then(() => {
117  console.log('bind success');
118}).catch(err => {
119  console.log('bind fail');
120});
121```
122
123### send<sup>7+</sup>
124
125send(options: UDPSendOptions, callback: AsyncCallback\<void\>): void
126
127Sends data over a UDPSocket connection. This API uses an asynchronous callback to return the result.
128
129Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and port.
130
131**Required permissions**: ohos.permission.INTERNET
132
133**System capability**: SystemCapability.Communication.NetStack
134
135**Parameters**
136
137| Name  | Type                                    | Mandatory| Description                                                        |
138| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
139| options  | [UDPSendOptions](#udpsendoptions) | Yes  | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).|
140| callback | AsyncCallback\<void\>                    | Yes  | Callback used to return the result.                                                  |
141
142**Error codes**
143
144| ID| Error Message                |
145| ------- | ----------------------- |
146| 401     | Parameter error.        |
147| 201     | Permission denied.      |
148
149**Example**
150
151```js
152let udp = socket.constructUDPSocketInstance();
153udp.send({
154  data: 'Hello, server!',
155  address: {
156    address: '192.168.xx.xxx',
157    port: xxxx,
158    family: 1
159  }
160}, err => {
161  if (err) {
162    console.log('send fail');
163    return;
164  }
165  console.log('send success');
166})
167```
168
169### send<sup>7+</sup>
170
171send(options: UDPSendOptions): Promise\<void\>
172
173Sends data over a UDPSocket connection. This API uses a promise to return the result.
174
175Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and port.
176
177**Required permissions**: ohos.permission.INTERNET
178
179**System capability**: SystemCapability.Communication.NetStack
180
181**Parameters**
182
183| Name | Type                                    | Mandatory| Description                                                        |
184| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
185| options | [UDPSendOptions](#udpsendoptions) | Yes  | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).|
186
187**Error codes**
188
189| ID| Error Message                |
190| ------- | ----------------------- |
191| 401     | Parameter error.        |
192| 201     | Permission denied.      |
193
194**Return value**
195
196| Type           | Description                                          |
197| :-------------- | :--------------------------------------------- |
198| Promise\<void\> | Promise used to return the result.|
199
200**Example**
201
202```js
203let udp = socket.constructUDPSocketInstance();
204let promise = udp.send({
205  data: 'Hello, server!',
206  address: {
207    address: '192.168.xx.xxx',
208    port: xxxx,
209    family: 1
210  }
211});
212promise.then(() => {
213  console.log('send success');
214}).catch(err => {
215  console.log('send fail');
216});
217```
218
219### close<sup>7+</sup>
220
221close(callback: AsyncCallback\<void\>): void
222
223Closes a UDPSocket connection. This API uses an asynchronous callback to return the result.
224
225**Required permissions**: ohos.permission.INTERNET
226
227**System capability**: SystemCapability.Communication.NetStack
228
229**Parameters**
230
231| Name  | Type                 | Mandatory| Description      |
232| -------- | --------------------- | ---- | ---------- |
233| callback | AsyncCallback\<void\> | Yes  | Callback used to return the result.|
234
235**Example**
236
237```js
238let udp = socket.constructUDPSocketInstance();
239udp.close(err => {
240  if (err) {
241    console.log('close fail');
242    return;
243  }
244  console.log('close success');
245})
246```
247
248### close<sup>7+</sup>
249
250close(): Promise\<void\>
251
252Closes a UDPSocket connection. This API uses a promise to return the result.
253
254**Required permissions**: ohos.permission.INTERNET
255
256**System capability**: SystemCapability.Communication.NetStack
257
258**Return value**
259
260| Type           | Description                                      |
261| :-------------- | :----------------------------------------- |
262| Promise\<void\> | Promise used to return the result.|
263
264**Example**
265
266```js
267let udp = socket.constructUDPSocketInstance();
268let promise = udp.close();
269promise.then(() => {
270  console.log('close success');
271}).catch(err => {
272  console.log('close fail');
273});
274```
275
276### getState<sup>7+</sup>
277
278getState(callback: AsyncCallback\<SocketStateBase\>): void
279
280Obtains the status of the UDPSocket connection. This API uses an asynchronous callback to return the result.
281
282> **NOTE**
283> This API can be called only after **bind** is successfully called.
284
285**Required permissions**: ohos.permission.INTERNET
286
287**System capability**: SystemCapability.Communication.NetStack
288
289**Parameters**
290
291| Name  | Type                                                  | Mandatory| Description      |
292| -------- | ------------------------------------------------------ | ---- | ---------- |
293| callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | Yes  | Callback used to return the result.|
294
295**Error codes**
296
297| ID| Error Message                |
298| ------- | ----------------------- |
299| 201     | Permission denied.      |
300
301**Example**
302
303```js
304let udp = socket.constructUDPSocketInstance();
305udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
306  if (err) {
307    console.log('bind fail');
308    return;
309  }
310  console.log('bind success');
311  udp.getState((err, data) => {
312    if (err) {
313      console.log('getState fail');
314      return;
315    }
316    console.log('getState success:' + JSON.stringify(data));
317  })
318})
319```
320
321### getState<sup>7+</sup>
322
323getState(): Promise\<SocketStateBase\>
324
325Obtains the status of the UDPSocket connection. This API uses a promise to return the result.
326
327> **NOTE**
328> This API can be called only after **bind** is successfully called.
329
330**Required permissions**: ohos.permission.INTERNET
331
332**System capability**: SystemCapability.Communication.NetStack
333
334**Return value**
335
336| Type                                            | Description                                      |
337| :----------------------------------------------- | :----------------------------------------- |
338| Promise\<[SocketStateBase](#socketstatebase)\> | Promise used to return the result.|
339
340**Example**
341
342```js
343let udp = socket.constructUDPSocketInstance();
344let promise = udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1});
345promise.then(err => {
346  if (err) {
347    console.log('bind fail');
348    return;
349  }
350  console.log('bind success');
351  let promise = udp.getState();
352  promise.then(data => {
353    console.log('getState success:' + JSON.stringify(data));
354  }).catch(err => {
355    console.log('getState fail');
356  });
357});
358```
359
360### setExtraOptions<sup>7+</sup>
361
362setExtraOptions(options: UDPExtraOptions, callback: AsyncCallback\<void\>): void
363
364Sets other attributes of the UDPSocket connection. This API uses an asynchronous callback to return the result.
365
366> **NOTE**
367> This API can be called only after **bind** is successfully called.
368
369**Required permissions**: ohos.permission.INTERNET
370
371**System capability**: SystemCapability.Communication.NetStack
372
373**Parameters**
374
375| Name  | Type                                    | Mandatory| Description                                                        |
376| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
377| options  | [UDPExtraOptions](#udpextraoptions) | Yes  | Other properties of the UDPSocket connection. For details, see [UDPExtraOptions](#udpextraoptions).|
378| callback | AsyncCallback\<void\>                    | Yes  | Callback used to return the result.                                                  |
379
380**Error codes**
381
382| ID| Error Message                |
383| ------- | ----------------------- |
384| 401     | Parameter error.        |
385| 201     | Permission denied.      |
386
387**Example**
388
389```js
390let udp = socket.constructUDPSocketInstance();
391udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
392  if (err) {
393    console.log('bind fail');
394    return;
395  }
396  console.log('bind success');
397  udp.setExtraOptions({
398    receiveBufferSize: 1000,
399    sendBufferSize: 1000,
400    reuseAddress: false,
401    socketTimeout: 6000,
402    broadcast: true
403  }, err => {
404    if (err) {
405      console.log('setExtraOptions fail');
406      return;
407    }
408    console.log('setExtraOptions success');
409  })
410})
411```
412
413### setExtraOptions<sup>7+</sup>
414
415setExtraOptions(options: UDPExtraOptions): Promise\<void\>
416
417Sets other attributes of the UDPSocket connection. This API uses a promise to return the result.
418
419> **NOTE**
420> This API can be called only after **bind** is successfully called.
421
422**Required permissions**: ohos.permission.INTERNET
423
424**System capability**: SystemCapability.Communication.NetStack
425
426**Parameters**
427
428| Name | Type                                    | Mandatory| Description                                                        |
429| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
430| options | [UDPExtraOptions](#udpextraoptions) | Yes  | Other properties of the UDPSocket connection. For details, see [UDPExtraOptions](#udpextraoptions).|
431
432**Return value**
433
434| Type           | Description                                                |
435| :-------------- | :--------------------------------------------------- |
436| Promise\<void\> | Promise used to return the result.|
437
438**Error codes**
439
440| ID| Error Message                |
441| ------- | ----------------------- |
442| 401     | Parameter error.        |
443| 201     | Permission denied.      |
444
445**Example**
446
447```js
448let udp = socket.constructUDPSocketInstance();
449let promise = udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1});
450promise.then(() => {
451  console.log('bind success');
452  let promise1 = udp.setExtraOptions({
453    receiveBufferSize: 1000,
454    sendBufferSize: 1000,
455    reuseAddress: false,
456    socketTimeout: 6000,
457    broadcast: true
458  });
459  promise1.then(() => {
460    console.log('setExtraOptions success');
461  }).catch(err => {
462    console.log('setExtraOptions fail');
463  });
464}).catch(err => {
465  console.log('bind fail');
466});
467```
468
469### on('message')<sup>7+</sup>
470
471on(type: 'message', callback: Callback\<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void
472
473Enables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
474
475**System capability**: SystemCapability.Communication.NetStack
476
477**Parameters**
478
479| Name  | Type                                                        | Mandatory| Description                                     |
480| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
481| type     | string                                                       | Yes  | Type of the event to subscribe to.<br /> **message**: message receiving event|
482| callback | Callback\<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}\> | Yes  | Callback used to return the result.                               |
483
484**Example**
485
486```js
487let udp = socket.constructUDPSocketInstance();
488udp.on('message', value => {
489  console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
490});
491```
492
493### off('message')<sup>7+</sup>
494
495off(type: 'message', callback?: Callback\<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void
496
497Disables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
498
499> **NOTE**
500> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
501
502**System capability**: SystemCapability.Communication.NetStack
503
504**Parameters**
505
506| Name  | Type                                                        | Mandatory| Description                                     |
507| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
508| type     | string                                                       | Yes  | Type of the event to subscribe to.<br /> **message**: message receiving event|
509| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No  | Callback used to return the result.                               |
510
511**Example**
512
513```js
514let udp = socket.constructUDPSocketInstance();
515let callback = value => {
516  console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
517}
518udp.on('message', callback);
519// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
520udp.off('message', callback);
521udp.off('message');
522```
523
524### on('listening' | 'close')<sup>7+</sup>
525
526on(type: 'listening' | 'close', callback: Callback\<void\>): void
527
528Enables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
529
530**System capability**: SystemCapability.Communication.NetStack
531
532**Parameters**
533
534| Name  | Type            | Mandatory| Description                                                        |
535| -------- | ---------------- | ---- | ------------------------------------------------------------ |
536| type     | string           | Yes  | Type of the event to subscribe to.<br /><br>- **listening**: data packet message event<br>- **close**: close event|
537| callback | Callback\<void\> | Yes  | Callback used to return the result.                                                  |
538
539**Example**
540
541```js
542let udp = socket.constructUDPSocketInstance();
543udp.on('listening', () => {
544  console.log("on listening success");
545});
546udp.on('close', () => {
547  console.log("on close success");
548});
549```
550
551### off('listening' | 'close')<sup>7+</sup>
552
553off(type: 'listening' | 'close', callback?: Callback\<void\>): void
554
555Disables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
556
557> **NOTE**
558> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
559
560**System capability**: SystemCapability.Communication.NetStack
561
562**Parameters**
563
564| Name  | Type            | Mandatory| Description                                                        |
565| -------- | ---------------- | ---- | ------------------------------------------------------------ |
566| type     | string           | Yes  | Type of the event to subscribe to.<br>- **listening**: data packet message event<br>- **close**: close event|
567| callback | Callback\<void\> | No  | Callback used to return the result.                                                  |
568
569**Example**
570
571```js
572let udp = socket.constructUDPSocketInstance();
573let callback1 = () => {
574  console.log("on listening, success");
575}
576udp.on('listening', callback1);
577// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
578udp.off('listening', callback1);
579udp.off('listening');
580let callback2 = () => {
581  console.log("on close, success");
582}
583udp.on('close', callback2);
584// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
585udp.off('close', callback2);
586udp.off('close');
587```
588
589### on('error')<sup>7+</sup>
590
591on(type: 'error', callback: ErrorCallback): void
592
593Enables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
594
595**System capability**: SystemCapability.Communication.NetStack
596
597**Parameters**
598
599| Name  | Type         | Mandatory| Description                                |
600| -------- | ------------- | ---- | ------------------------------------ |
601| type     | string        | Yes  | Type of the event to subscribe to.<br /> **error**: error event|
602| callback | ErrorCallback | Yes  | Callback used to return the result.                          |
603
604**Example**
605
606```js
607let udp = socket.constructUDPSocketInstance();
608udp.on('error', err => {
609  console.log("on error, err:" + JSON.stringify(err))
610});
611```
612
613### off('error')<sup>7+</sup>
614
615off(type: 'error', callback?: ErrorCallback): void
616
617Disables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
618
619> **NOTE**
620> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
621
622**System capability**: SystemCapability.Communication.NetStack
623
624**Parameters**
625
626| Name  | Type         | Mandatory| Description                                |
627| -------- | ------------- | ---- | ------------------------------------ |
628| type     | string        | Yes  | Type of the event to subscribe to.<br /> **error**: error event|
629| callback | ErrorCallback | No  | Callback used to return the result.                          |
630
631**Example**
632
633```js
634let udp = socket.constructUDPSocketInstance();
635let callback = err => {
636  console.log("on error, err:" + JSON.stringify(err));
637}
638udp.on('error', callback);
639// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
640udp.off('error', callback);
641udp.off('error');
642```
643
644## NetAddress<sup>7+</sup>
645
646Defines the destination address.
647
648**System capability**: SystemCapability.Communication.NetStack
649
650| Name | Type  | Mandatory| Description                                                        |
651| ------- | ------ | ---- | ------------------------------------------------------------ |
652| address | string | Yes  | Bound IP address.                                          |
653| port    | number | No  | Port number. The value ranges from **0** to **65535**. If this parameter is not specified, the system randomly allocates a port.          |
654| family  | number | No  | Network protocol type.<br>- **1**: IPv4<br>- **2**: IPv6<br>The default value is **1**.|
655
656## UDPSendOptions<sup>7+</sup>
657
658Defines the parameters for sending data over the UDPSocket connection.
659
660**System capability**: SystemCapability.Communication.NetStack
661
662| Name | Type                              | Mandatory| Description          |
663| ------- | ---------------------------------- | ---- | -------------- |
664| data    | string \| ArrayBuffer<sup>7+</sup>                          | Yes  | Data to send.  |
665| address | [NetAddress](#netaddress) | Yes  | Destination address.|
666
667## UDPExtraOptions<sup>7+</sup>
668
669Defines other properties of the UDPSocket connection.
670
671**System capability**: SystemCapability.Communication.NetStack
672
673| Name           | Type   | Mandatory| Description                            |
674| ----------------- | ------- | ---- | -------------------------------- |
675| broadcast         | boolean | No  | Whether to send broadcast messages. The default value is **false**. |
676| receiveBufferSize | number  | No  | Size of the receive buffer, in bytes. The default value is **0**.  |
677| sendBufferSize    | number  | No  | Size of the send buffer, in bytes. The default value is **0**.  |
678| reuseAddress      | boolean | No  | Whether to reuse addresses. The default value is **false**.     |
679| socketTimeout     | number  | No  | Timeout duration of the UDPSocket connection, in ms. The default value is **0**.|
680
681## SocketStateBase<sup>7+</sup>
682
683Defines the status of the socket connection.
684
685**System capability**: SystemCapability.Communication.NetStack
686
687| Name     | Type   | Mandatory| Description      |
688| ----------- | ------- | ---- | ---------- |
689| isBound     | boolean | Yes  | Whether the connection is in the bound state.|
690| isClose     | boolean | Yes  | Whether the connection is in the closed state.|
691| isConnected | boolean | Yes  | Whether the connection is in the connected state.|
692
693## SocketRemoteInfo<sup>7+</sup>
694
695Defines information about the socket connection.
696
697**System capability**: SystemCapability.Communication.NetStack
698
699| Name | Type  | Mandatory| Description                                                        |
700| ------- | ------ | ---- | ------------------------------------------------------------ |
701| address | string | Yes  | Bound IP address.                                          |
702| family  | string | Yes  | Network protocol type.<br>- IPv4<br>- IPv6<br>The default value is **IPv4**.|
703| port    | number | Yes  | Port number. The value ranges from **0** to **65535**.                                       |
704| size    | number | Yes  | Length of the server response message, in bytes.                                  |
705
706## Description of UDP Error Codes
707
708The UDP error code mapping is in the format of 2301000 + Linux kernel error code.
709
710For details about error codes, see [Socket Error Codes](../errorcodes/errorcode-net-socket.md).
711
712## socket.constructTCPSocketInstance<sup>7+</sup>
713
714constructTCPSocketInstance(): TCPSocket
715
716Creates a **TCPSocket** object.
717
718**System capability**: SystemCapability.Communication.NetStack
719
720**Return value**
721
722| Type                              | Description                   |
723  | :--------------------------------- | :---------------------- |
724| [TCPSocket](#tcpsocket) | **TCPSocket** object.|
725
726**Example**
727
728```js
729let tcp = socket.constructTCPSocketInstance();
730```
731
732## TCPSocket<sup>7+</sup>
733
734Defines a TCPSocket connection. Before invoking TCPSocket APIs, you need to call [socket.constructTCPSocketInstance](#socketconstructtcpsocketinstance) to create a **TCPSocket** object.
735
736### bind<sup>7+</sup>
737
738bind(address: NetAddress, callback: AsyncCallback\<void\>): void
739
740Binds 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.
741
742> **NOTE**
743> This API is used for the client to create a socket.
744
745**Required permissions**: ohos.permission.INTERNET
746
747**System capability**: SystemCapability.Communication.NetStack
748
749**Parameters**
750
751| Name  | Type                              | Mandatory| Description                                                  |
752| -------- | ---------------------------------- | ---- | ------------------------------------------------------ |
753| address  | [NetAddress](#netaddress) | Yes  | Destination address. For details, see [NetAddress](#netaddress).|
754| callback | AsyncCallback\<void\>              | Yes  | Callback used to return the result.                                            |
755
756**Error codes**
757
758| ID| Error Message                |
759| ------- | ----------------------- |
760| 401     | Parameter error.        |
761| 201     | Permission denied.      |
762
763**Example**
764
765```js
766let tcp = socket.constructTCPSocketInstance();
767tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
768  if (err) {
769    console.log('bind fail');
770    return;
771  }
772  console.log('bind success');
773})
774```
775
776### bind<sup>7+</sup>
777
778bind(address: NetAddress): Promise\<void\>
779
780Binds 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.
781
782> **NOTE**
783> This API is used for the client to create a socket.
784
785**Required permissions**: ohos.permission.INTERNET
786
787**System capability**: SystemCapability.Communication.NetStack
788
789**Parameters**
790
791| Name | Type                              | Mandatory| Description                                                  |
792| ------- | ---------------------------------- | ---- | ------------------------------------------------------ |
793| address | [NetAddress](#netaddress) | Yes  | Destination address. For details, see [NetAddress](#netaddress).|
794
795**Return value**
796
797| Type           | Description                                                    |
798| :-------------- | :------------------------------------------------------- |
799| Promise\<void\> | Promise used to return the result.|
800
801**Error codes**
802
803| ID| Error Message                |
804| ------- | ----------------------- |
805| 401     | Parameter error.        |
806| 201     | Permission denied.      |
807
808**Example**
809
810```js
811let tcp = socket.constructTCPSocketInstance();
812let promise = tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1});
813promise.then(() => {
814  console.log('bind success');
815}).catch(err => {
816  console.log('bind fail');
817});
818```
819
820### connect<sup>7+</sup>
821
822connect(options: TCPConnectOptions, callback: AsyncCallback\<void\>): void
823
824Sets up a connection to the specified IP address and port number. This API uses an asynchronous callback to return the result.
825
826> **NOTE**
827> This API can be called only after **bind** is successfully called.
828
829**Required permissions**: ohos.permission.INTERNET
830
831**System capability**: SystemCapability.Communication.NetStack
832
833**Parameters**
834
835| Name  | Type                                    | Mandatory| Description                                                        |
836| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
837| options  | [TCPConnectOptions](#tcpconnectoptions) | Yes  | TCPSocket connection parameters. For details, see [TCPConnectOptions](#tcpconnectoptions).|
838| callback | AsyncCallback\<void\>                    | Yes  | Callback used to return the result.                                                  |
839
840**Error codes**
841
842| ID| Error Message                |
843| ------- | ----------------------- |
844| 401     | Parameter error.        |
845| 201     | Permission denied.      |
846
847**Example**
848
849```js
850let tcp = socket.constructTCPSocketInstance();
851tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}, err => {
852  if (err) {
853    console.log('connect fail');
854    return;
855  }
856  console.log('connect success');
857})
858```
859
860### connect<sup>7+</sup>
861
862connect(options: TCPConnectOptions): Promise\<void\>
863
864Sets up a connection to the specified IP address and port number. This API uses a promise to return the result.
865
866**Required permissions**: ohos.permission.INTERNET
867
868**System capability**: SystemCapability.Communication.NetStack
869
870**Parameters**
871
872| Name | Type                                    | Mandatory| Description                                                        |
873| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
874| options | [TCPConnectOptions](#tcpconnectoptions) | Yes  | TCPSocket connection parameters. For details, see [TCPConnectOptions](#tcpconnectoptions).|
875
876**Return value**
877
878| Type           | Description                                                      |
879| :-------------- | :--------------------------------------------------------- |
880| Promise\<void\> | Promise used to return the result.|
881
882**Error codes**
883
884| ID| Error Message                |
885| ------- | ----------------------- |
886| 401     | Parameter error.        |
887| 201     | Permission denied.      |
888
889**Example**
890
891```js
892let tcp = socket.constructTCPSocketInstance();
893let promise = tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000});
894promise.then(() => {
895  console.log('connect success')
896}).catch(err => {
897  console.log('connect fail');
898});
899```
900
901### send<sup>7+</sup>
902
903send(options: TCPSendOptions, callback: AsyncCallback\<void\>): void
904
905Sends data over a TCPSocket connection. This API uses an asynchronous callback to return the result.
906
907> **NOTE**
908> This API can be called only after **connect** is successfully called.
909
910**Required permissions**: ohos.permission.INTERNET
911
912**System capability**: SystemCapability.Communication.NetStack
913
914**Parameters**
915
916| Name  | Type                                   | Mandatory| Description                                                        |
917| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
918| options  | [TCPSendOptions](#tcpsendoptions) | Yes  | Parameters for sending data over the TCPSocket connection. For details, see [TCPSendOptions](#tcpsendoptions).|
919| callback | AsyncCallback\<void\>                   | Yes  | Callback used to return the result.                                                  |
920
921**Error codes**
922
923| ID| Error Message                |
924| ------- | ----------------------- |
925| 401     | Parameter error.        |
926| 201     | Permission denied.      |
927
928**Example**
929
930```js
931let tcp = socket.constructTCPSocketInstance();
932tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}, () => {
933  console.log('connect success');
934  tcp.send({
935    data: 'Hello, server!'
936    // Encoding is omitted here. The UTF-8 encoding format is used by default.
937  }, err => {
938    if (err) {
939      console.log('send fail');
940      return;
941    }
942    console.log('send success');
943  })
944})
945```
946
947### send<sup>7+</sup>
948
949send(options: TCPSendOptions): Promise\<void\>
950
951Sends data over a TCPSocket connection. This API uses a promise to return the result.
952
953> **NOTE**
954> This API can be called only after **connect** is successfully called.
955
956**Required permissions**: ohos.permission.INTERNET
957
958**System capability**: SystemCapability.Communication.NetStack
959
960**Parameters**
961
962| Name | Type                                   | Mandatory| Description                                                        |
963| ------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
964| options | [TCPSendOptions](#tcpsendoptions) | Yes  | Parameters for sending data over the TCPSocket connection. For details, see [TCPSendOptions](#tcpsendoptions).|
965
966**Return value**
967
968| Type           | Description                                              |
969| :-------------- | :------------------------------------------------- |
970| Promise\<void\> | Promise used to return the result.|
971
972**Error codes**
973
974| ID| Error Message                |
975| ------- | ----------------------- |
976| 401     | Parameter error.        |
977| 201     | Permission denied.      |
978
979**Example**
980
981```js
982let tcp = socket.constructTCPSocketInstance();
983let promise1 = tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000});
984promise1.then(() => {
985  console.log('connect success');
986  let promise2 = tcp.send({
987    data: 'Hello, server!'
988  });
989  promise2.then(() => {
990    console.log('send success');
991  }).catch(err => {
992    console.log('send fail');
993  });
994}).catch(err => {
995  console.log('connect fail');
996});
997```
998
999### close<sup>7+</sup>
1000
1001close(callback: AsyncCallback\<void\>): void
1002
1003Closes a TCPSocket connection. This API uses an asynchronous callback to return the result.
1004
1005**Required permissions**: ohos.permission.INTERNET
1006
1007**System capability**: SystemCapability.Communication.NetStack
1008
1009**Parameters**
1010
1011| Name  | Type                 | Mandatory| Description      |
1012| -------- | --------------------- | ---- | ---------- |
1013| callback | AsyncCallback\<void\> | Yes  | Callback used to return the result.|
1014
1015**Error codes**
1016
1017| ID| Error Message                |
1018| ------- | ----------------------- |
1019| 201     | Permission denied.      |
1020
1021**Example**
1022
1023```js
1024let tcp = socket.constructTCPSocketInstance();
1025tcp.close(err => {
1026  if (err) {
1027    console.log('close fail');
1028    return;
1029  }
1030  console.log('close success');
1031})
1032```
1033
1034### close<sup>7+</sup>
1035
1036close(): Promise\<void\>
1037
1038Closes a TCPSocket connection. This API uses a promise to return the result.
1039
1040**Required permissions**: ohos.permission.INTERNET
1041
1042**System capability**: SystemCapability.Communication.NetStack
1043
1044**Return value**
1045
1046| Type           | Description                                      |
1047| :-------------- | :----------------------------------------- |
1048| Promise\<void\> | Promise used to return the result.|
1049
1050**Error codes**
1051
1052| ID| Error Message                |
1053| ------- | ----------------------- |
1054| 201     | Permission denied.      |
1055
1056**Example**
1057
1058```js
1059let tcp = socket.constructTCPSocketInstance();
1060let promise = tcp.close();
1061promise.then(() => {
1062  console.log('close success');
1063}).catch(err => {
1064  console.log('close fail');
1065});
1066```
1067
1068### getRemoteAddress<sup>7+</sup>
1069
1070getRemoteAddress(callback: AsyncCallback\<NetAddress\>): void
1071
1072Obtains the remote address of a socket connection. This API uses an asynchronous callback to return the result.
1073
1074> **NOTE**
1075> This API can be called only after **connect** is successfully called.
1076
1077**Required permissions**: ohos.permission.INTERNET
1078
1079**System capability**: SystemCapability.Communication.NetStack
1080
1081**Parameters**
1082
1083| Name  | Type                                             | Mandatory| Description      |
1084| -------- | ------------------------------------------------- | ---- | ---------- |
1085| callback | AsyncCallback<[NetAddress](#netaddress)> | Yes  | Callback used to return the result.|
1086
1087**Error codes**
1088
1089| ID| Error Message                |
1090| ------- | ----------------------- |
1091| 201     | Permission denied.      |
1092
1093**Example**
1094
1095```js
1096let tcp = socket.constructTCPSocketInstance();
1097tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}, () => {
1098  console.log('connect success');
1099  tcp.getRemoteAddress((err, data) => {
1100    if (err) {
1101      console.log('getRemoteAddressfail');
1102      return;
1103    }
1104    console.log('getRemoteAddresssuccess:' + JSON.stringify(data));
1105  })
1106});
1107```
1108
1109### getRemoteAddress<sup>7+</sup>
1110
1111getRemoteAddress(): Promise\<NetAddress\>
1112
1113Obtains the remote address of a socket connection. This API uses a promise to return the result.
1114
1115> **NOTE**
1116> This API can be called only after **connect** is successfully called.
1117
1118**Required permissions**: ohos.permission.INTERNET
1119
1120**System capability**: SystemCapability.Communication.NetStack
1121
1122**Return value**
1123
1124| Type                                       | Description                                       |
1125| :------------------------------------------ | :------------------------------------------ |
1126| Promise<[NetAddress](#netaddress)> | Promise used to return the result.|
1127
1128**Error codes**
1129
1130| ID| Error Message                |
1131| ------- | ----------------------- |
1132| 201     | Permission denied.      |
1133
1134**Example**
1135
1136```js
1137let tcp = socket.constructTCPSocketInstance();
1138let promise1 = tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000});
1139promise1.then(() => {
1140  console.log('connect success');
1141  let promise2 = tcp.getRemoteAddress();
1142  promise2.then(() => {
1143    console.log('getRemoteAddress success');
1144  }).catch(err => {
1145    console.log('getRemoteAddressfail');
1146  });
1147}).catch(err => {
1148  console.log('connect fail');
1149});
1150```
1151
1152### getState<sup>7+</sup>
1153
1154getState(callback: AsyncCallback\<SocketStateBase\>): void
1155
1156Obtains the status of the TCPSocket connection. This API uses an asynchronous callback to return the result.
1157
1158> **NOTE**
1159> This API can be called only after **bind** or **connect** is successfully called.
1160
1161**Required permissions**: ohos.permission.INTERNET
1162
1163**System capability**: SystemCapability.Communication.NetStack
1164
1165**Parameters**
1166
1167| Name  | Type                                                  | Mandatory| Description      |
1168| -------- | ------------------------------------------------------ | ---- | ---------- |
1169| callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | Yes  | Callback used to return the result.|
1170
1171**Error codes**
1172
1173| ID| Error Message                |
1174| ------- | ----------------------- |
1175| 201     | Permission denied.      |
1176
1177**Example**
1178
1179```js
1180let tcp = socket.constructTCPSocketInstance();
1181let promise = tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}, () => {
1182  console.log('connect success');
1183  tcp.getState((err, data) => {
1184    if (err) {
1185      console.log('getState fail');
1186      return;
1187    }
1188    console.log('getState success:' + JSON.stringify(data));
1189  });
1190});
1191```
1192
1193### getState<sup>7+</sup>
1194
1195getState(): Promise\<SocketStateBase\>
1196
1197Obtains the status of the TCPSocket connection. This API uses a promise to return the result.
1198
1199> **NOTE**
1200> This API can be called only after **bind** or **connect** is successfully called.
1201
1202**Required permissions**: ohos.permission.INTERNET
1203
1204**System capability**: SystemCapability.Communication.NetStack
1205
1206**Return value**
1207
1208| Type                                            | Description                                      |
1209| :----------------------------------------------- | :----------------------------------------- |
1210| Promise<[SocketStateBase](#socketstatebase)> | Promise used to return the result.|
1211
1212**Error codes**
1213
1214| ID| Error Message                |
1215| ------- | ----------------------- |
1216| 201     | Permission denied.      |
1217
1218**Example**
1219
1220```js
1221let tcp = socket.constructTCPSocketInstance();
1222let promise = tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000});
1223promise.then(() => {
1224  console.log('connect success');
1225  let promise1 = tcp.getState();
1226  promise1.then(() => {
1227    console.log('getState success');
1228  }).catch(err => {
1229    console.log('getState fail');
1230  });
1231}).catch(err => {
1232  console.log('connect fail');
1233});
1234```
1235
1236### setExtraOptions<sup>7+</sup>
1237
1238setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\<void\>): void
1239
1240Sets other properties of the TCPSocket connection. This API uses an asynchronous callback to return the result.
1241
1242> **NOTE**
1243> This API can be called only after **bind** or **connect** is successfully called.
1244
1245**Required permissions**: ohos.permission.INTERNET
1246
1247**System capability**: SystemCapability.Communication.NetStack
1248
1249**Parameters**
1250
1251| Name  | Type                                     | Mandatory| Description                                                        |
1252| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
1253| options  | [TCPExtraOptions](#tcpextraoptions) | Yes  | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).|
1254| callback | AsyncCallback\<void\>                     | Yes  | Callback used to return the result.                                                  |
1255
1256**Error codes**
1257
1258| ID| Error Message                |
1259| ------- | ----------------------- |
1260| 401     | Parameter error.        |
1261| 201     | Permission denied.      |
1262
1263**Example**
1264
1265```js
1266let tcp = socket.constructTCPSocketInstance();
1267let promise = tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}, () => {
1268  console.log('connect success');
1269  tcp.setExtraOptions({
1270    keepAlive: true,
1271    OOBInline: true,
1272    TCPNoDelay: true,
1273    socketLinger: {on: true, linger: 10},
1274    receiveBufferSize: 1000,
1275    sendBufferSize: 1000,
1276    reuseAddress: true,
1277    socketTimeout: 3000,
1278  }, err => {
1279    if (err) {
1280      console.log('setExtraOptions fail');
1281      return;
1282    }
1283    console.log('setExtraOptions success');
1284  });
1285});
1286```
1287
1288### setExtraOptions<sup>7+</sup>
1289
1290setExtraOptions(options: TCPExtraOptions): Promise\<void\>
1291
1292Sets other properties of the TCPSocket connection. This API uses a promise to return the result.
1293
1294> **NOTE**
1295> This API can be called only after **bind** or **connect** is successfully called.
1296
1297**Required permissions**: ohos.permission.INTERNET
1298
1299**System capability**: SystemCapability.Communication.NetStack
1300
1301**Parameters**
1302
1303| Name | Type                                     | Mandatory| Description                                                        |
1304| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
1305| options | [TCPExtraOptions](#tcpextraoptions) | Yes  | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).|
1306
1307**Return value**
1308
1309| Type           | Description                                                |
1310| :-------------- | :--------------------------------------------------- |
1311| Promise\<void\> | Promise used to return the result.|
1312
1313**Error codes**
1314
1315| ID| Error Message                |
1316| ------- | ----------------------- |
1317| 401     | Parameter error.        |
1318| 201     | Permission denied.      |
1319
1320**Example**
1321
1322```js
1323let tcp = socket.constructTCPSocketInstance();
1324let promise = tcp.connect({address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000});
1325promise.then(() => {
1326  console.log('connect success');
1327  let promise1 = tcp.setExtraOptions({
1328    keepAlive: true,
1329    OOBInline: true,
1330    TCPNoDelay: true,
1331    socketLinger: {on: true, linger: 10},
1332    receiveBufferSize: 1000,
1333    sendBufferSize: 1000,
1334    reuseAddress: true,
1335    socketTimeout: 3000,
1336  });
1337  promise1.then(() => {
1338    console.log('setExtraOptions success');
1339  }).catch(err => {
1340    console.log('setExtraOptions fail');
1341  });
1342}).catch(err => {
1343  console.log('connect fail');
1344});
1345```
1346
1347### on('message')<sup>7+</sup>
1348
1349on(type: 'message', callback: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void
1350
1351Enables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
1352
1353**System capability**: SystemCapability.Communication.NetStack
1354
1355**Parameters**
1356
1357| Name  | Type                                                        | Mandatory| Description                                     |
1358| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
1359| type     | string                                                       | Yes  | Type of the event to subscribe to.<br /> **message**: message receiving event|
1360| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | Yes  | Callback used to return the result.                               |
1361
1362**Example**
1363
1364```js
1365let tcp = socket.constructTCPSocketInstance();
1366tcp.on('message', value => {
1367  console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo)
1368});
1369```
1370
1371### off('message')<sup>7+</sup>
1372
1373off(type: 'message', callback?: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void
1374
1375Disables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
1376
1377> **NOTE**
1378> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
1379
1380**System capability**: SystemCapability.Communication.NetStack
1381
1382**Parameters**
1383
1384| Name  | Type                                                        | Mandatory| Description                                     |
1385| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
1386| type     | string                                                       | Yes  | Type of the event to subscribe to.<br /> **message**: message receiving event|
1387| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No  | Callback used to return the result.                               |
1388
1389**Example**
1390
1391```js
1392let tcp = socket.constructTCPSocketInstance();
1393let callback = value => {
1394  console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
1395}
1396tcp.on('message', callback);
1397// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
1398tcp.off('message', callback);
1399tcp.off('message');
1400```
1401
1402### on('connect' | 'close')<sup>7+</sup>
1403
1404on(type: 'connect' | 'close', callback: Callback\<void\>): void
1405
1406Enables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
1407
1408**System capability**: SystemCapability.Communication.NetStack
1409
1410**Parameters**
1411
1412| Name  | Type            | Mandatory| Description                                                        |
1413| -------- | ---------------- | ---- | ------------------------------------------------------------ |
1414| type     | string           | Yes  | Type of the event to subscribe to.<br /><br>- **connect**: connection event<br>- **close**: close event|
1415| callback | Callback\<void\> | Yes  | Callback used to return the result.                                                  |
1416
1417**Example**
1418
1419```js
1420let tcp = socket.constructTCPSocketInstance();
1421tcp.on('connect', () => {
1422  console.log("on connect success")
1423});
1424tcp.on('close', data => {
1425  console.log("on close success")
1426});
1427```
1428
1429### off('connect' | 'close')<sup>7+</sup>
1430
1431off(type: 'connect' | 'close', callback?: Callback\<void\>): void
1432
1433Disables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
1434
1435> **NOTE**
1436> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
1437
1438**System capability**: SystemCapability.Communication.NetStack
1439
1440**Parameters**
1441
1442| Name  | Type            | Mandatory| Description                                                        |
1443| -------- | ---------------- | ---- | ------------------------------------------------------------ |
1444| type     | string           | Yes  | Type of the event to subscribe to.<br /><br>- **connect**: connection event<br>- **close**: close event|
1445| callback | Callback\<void\> | No  | Callback used to return the result.                                                  |
1446
1447**Example**
1448
1449```js
1450let tcp = socket.constructTCPSocketInstance();
1451let callback1 = () => {
1452  console.log("on connect success");
1453}
1454tcp.on('connect', callback1);
1455// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
1456tcp.off('connect', callback1);
1457tcp.off('connect');
1458let callback2 = () => {
1459  console.log("on close success");
1460}
1461tcp.on('close', callback2);
1462// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
1463tcp.off('close', callback2);
1464tcp.off('close');
1465```
1466
1467### on('error')<sup>7+</sup>
1468
1469on(type: 'error', callback: ErrorCallback): void
1470
1471Enables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
1472
1473**System capability**: SystemCapability.Communication.NetStack
1474
1475**Parameters**
1476
1477| Name  | Type         | Mandatory| Description                                |
1478| -------- | ------------- | ---- | ------------------------------------ |
1479| type     | string        | Yes  | Type of the event to subscribe to.<br /> **error**: error event|
1480| callback | ErrorCallback | Yes  | Callback used to return the result.                          |
1481
1482**Example**
1483
1484```js
1485let tcp = socket.constructTCPSocketInstance();
1486tcp.on('error', err => {
1487  console.log("on error, err:" + JSON.stringify(err))
1488});
1489```
1490
1491### off('error')<sup>7+</sup>
1492
1493off(type: 'error', callback?: ErrorCallback): void
1494
1495Disables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
1496
1497> **NOTE**
1498> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
1499
1500**System capability**: SystemCapability.Communication.NetStack
1501
1502**Parameters**
1503
1504| Name  | Type         | Mandatory| Description                                |
1505| -------- | ------------- | ---- | ------------------------------------ |
1506| type     | string        | Yes  | Type of the event to subscribe to.<br /> **error**: error event|
1507| callback | ErrorCallback | No  | Callback used to return the result.                          |
1508
1509**Example**
1510
1511```js
1512let tcp = socket.constructTCPSocketInstance();
1513let callback = err => {
1514  console.log("on error, err:" + JSON.stringify(err));
1515}
1516tcp.on('error', callback);
1517// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
1518tcp.off('error', callback);
1519tcp.off('error');
1520```
1521
1522## TCPConnectOptions<sup>7+</sup>
1523
1524Defines TCPSocket connection parameters.
1525
1526**System capability**: SystemCapability.Communication.NetStack
1527
1528| Name | Type                              | Mandatory| Description                      |
1529| ------- | ---------------------------------- | ---- | -------------------------- |
1530| address | [NetAddress](#netaddress) | Yes  | Bound IP address and port number.      |
1531| timeout | number                             | No  | Timeout duration of the TCPSocket connection, in ms.|
1532
1533## TCPSendOptions<sup>7+</sup>
1534
1535Defines the parameters for sending data over the TCPSocket connection.
1536
1537**System capability**: SystemCapability.Communication.NetStack
1538
1539| Name  | Type  | Mandatory| Description                                                        |
1540| -------- | ------ | ---- | ------------------------------------------------------------ |
1541| data     | string\| ArrayBuffer<sup>7+</sup>  | Yes  | Data to send.                                                |
1542| 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**.|
1543
1544## TCPExtraOptions<sup>7+</sup>
1545
1546Defines other properties of the TCPSocket connection.
1547
1548**System capability**: SystemCapability.Communication.NetStack
1549
1550| Name           | Type   | Mandatory| Description                                                        |
1551| ----------------- | ------- | ---- | ------------------------------------------------------------ |
1552| keepAlive         | boolean | No  | Whether to keep the connection alive. The default value is **false**.                                 |
1553| OOBInline         | boolean | No  | Whether to enable OOBInline. The default value is **false**.                                |
1554| TCPNoDelay        | boolean | No  | Whether to enable no-delay on the TCPSocket connection. The default value is **false**.                      |
1555| 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**.|
1556| receiveBufferSize | number  | No  | Size of the receive buffer, in bytes. The default value is **0**.                              |
1557| sendBufferSize    | number  | No  | Size of the send buffer, in bytes. The default value is **0**.                              |
1558| reuseAddress      | boolean | No  | Whether to reuse addresses. The default value is **false**.                                 |
1559| socketTimeout     | number  | No  | Timeout duration of the TCPSocket connection, in ms. The default value is **0**.                            |
1560
1561## Description of TCP Error Codes
1562
1563The TCP error code mapping is in the format of 2301000 + Linux kernel error code.
1564
1565For details about error codes, see [Socket Error Codes](../errorcodes/errorcode-net-socket.md).
1566
1567## socket.constructTLSSocketInstance<sup>9+</sup>
1568
1569constructTLSSocketInstance(): TLSSocket
1570
1571Creates a **TLSSocket** object.
1572
1573**System capability**: SystemCapability.Communication.NetStack
1574
1575**Return value**
1576
1577| Type                              | Description                   |
1578| :--------------------------------- | :---------------------- |
1579| [TLSSocket](#tlssocket9) | **TLSSocket** object.|
1580
1581**Example**
1582
1583```js
1584let tls = socket.constructTLSSocketInstance();
1585```
1586
1587## TLSSocket<sup>9+</sup>
1588
1589Defines a TLSSocket connection. Before invoking TLSSocket APIs, you need to call [socket.constructTLSSocketInstance](#socketconstructtlssocketinstance9) to create a **TLSSocket** object.
1590
1591### bind<sup>9+</sup>
1592
1593bind(address: NetAddress, callback: AsyncCallback\<void\>): void
1594
1595Binds the IP address and port number. This API uses an asynchronous callback to return the result.
1596
1597**Required permissions**: ohos.permission.INTERNET
1598
1599**System capability**: SystemCapability.Communication.NetStack
1600
1601**Parameters**
1602
1603| Name  | Type                              | Mandatory| Description                                                  |
1604| -------- | ---------------------------------- | ---- | ------------------------------------------------------ |
1605| address  | [NetAddress](#netaddress) | Yes  | Destination address. For details, see [NetAddress](#netaddress).|
1606| 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.|
1607
1608**Error codes**
1609
1610| ID| Error Message                |
1611| ------- | ----------------------- |
1612| 401     | Parameter error.        |
1613| 201     | Permission denied.      |
1614| 2303198 | Address already in use. |
1615| 2300002 | System internal error.  |
1616
1617**Example**
1618
1619```js
1620tls.bind({ address: '192.168.xx.xxx', port: xxxx, family: 1 }, err => {
1621  if (err) {
1622    console.log('bind fail');
1623    return;
1624  }
1625  console.log('bind success');
1626});
1627```
1628
1629### bind<sup>9+</sup>
1630
1631bind(address: NetAddress): Promise\<void\>
1632
1633Binds the IP address and port number. This API uses a promise to return the result.
1634
1635**Required permissions**: ohos.permission.INTERNET
1636
1637**System capability**: SystemCapability.Communication.NetStack
1638
1639**Parameters**
1640
1641| Name | Type                              | Mandatory| Description                                                  |
1642| ------- | ---------------------------------- | ---- | ------------------------------------------------------ |
1643| address | [NetAddress](#netaddress)          | Yes  | Destination address. For details, see [NetAddress](#netaddress).|
1644
1645**Return value**
1646
1647| Type           | Description                                                    |
1648| :-------------- | :------------------------------------------------------- |
1649| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.|
1650
1651**Error codes**
1652
1653| ID| Error Message                |
1654| ------- | ----------------------- |
1655| 401     | Parameter error.        |
1656| 201     | Permission denied.      |
1657| 2303198 | Address already in use. |
1658| 2300002 | System internal error.  |
1659
1660**Example**
1661
1662```js
1663let promise = tls.bind({ address: '192.168.xx.xxx', port: xxxx, family: 1 });
1664promise.then(() => {
1665  console.log('bind success');
1666}).catch(err => {
1667  console.log('bind fail');
1668});
1669```
1670
1671### getState<sup>9+</sup>
1672
1673getState(callback: AsyncCallback\<SocketStateBase\>): void
1674
1675Obtains the status of the TLSSocket connection. This API uses an asynchronous callback to return the result.
1676
1677**System capability**: SystemCapability.Communication.NetStack
1678
1679**Parameters**
1680
1681| Name  | Type                                                  | Mandatory| Description      |
1682| -------- | ------------------------------------------------------ | ---- | ---------- |
1683| callback | AsyncCallback\<[SocketStateBase](#socketstatebase)> | Yes  | Callback used to return the result. If the operation is successful, the status of the TLSSocket connection is returned. If the operation fails, an error message is returned.|
1684
1685**Error codes**
1686
1687| ID| Error Message                       |
1688| ------- | ------------------------------ |
1689| 2303188 | Socket operation on non-socket.|
1690| 2300002 | System internal error.         |
1691
1692**Example**
1693
1694```js
1695let promise = tls.bind({ address: '192.168.xx.xxx', port: xxxx, family: 1 }, err => {
1696  if (err) {
1697    console.log('bind fail');
1698    return;
1699  }
1700  console.log('bind success');
1701});
1702tls.getState((err, data) => {
1703  if (err) {
1704    console.log('getState fail');
1705    return;
1706  }
1707  console.log('getState success:' + JSON.stringify(data));
1708});
1709```
1710
1711### getState<sup>9+</sup>
1712
1713getState(): Promise\<SocketStateBase\>
1714
1715Obtains the status of the TLSSocket connection. This API uses a promise to return the result.
1716
1717**System capability**: SystemCapability.Communication.NetStack
1718
1719**Return value**
1720
1721| Type                                            | Description                                      |
1722| :----------------------------------------------- | :----------------------------------------- |
1723| Promise\<[SocketStateBase](#socketstatebase)> | Promise used to return the result. If the operation fails, an error message is returned.|
1724
1725**Error codes**
1726
1727| ID| Error Message                       |
1728| ------- | ------------------------------ |
1729| 2303188 | Socket operation on non-socket.|
1730| 2300002 | System internal error.         |
1731
1732**Example**
1733
1734```js
1735let promiseBind = tls.bind({ address: '192.168.xx.xxx', port: xxxx, family: 1 });
1736promiseBind.then(() => {
1737  console.log('bind success');
1738}).catch((err) => {
1739  console.log('bind fail');
1740});
1741let promise = tls.getState();
1742promise.then(() => {
1743  console.log('getState success');
1744}).catch(err => {
1745  console.log('getState fail');
1746});
1747```
1748
1749### setExtraOptions<sup>9+</sup>
1750
1751setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\<void\>): void
1752
1753Sets other properties of the TCPSocket connection after successful binding of the local IP address and port number of the TLSSocket connection. This API uses an asynchronous callback to return the result.
1754
1755**System capability**: SystemCapability.Communication.NetStack
1756
1757**Parameters**
1758
1759| Name  | Type                                     | Mandatory| Description                                                        |
1760| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
1761| options  | [TCPExtraOptions](#tcpextraoptions) | Yes  | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).|
1762| callback | AsyncCallback\<void\>                     | Yes  | Callback used to return the result. If the operation is successful, the result of setting other properties of the TCPSocket connection is returned. If the operation fails, an error message is returned.|
1763
1764**Error codes**
1765
1766| ID| Error Message                       |
1767| ------- | -----------------------------  |
1768| 401     | Parameter error.               |
1769| 2303188 | Socket operation on non-socket.|
1770| 2300002 | System internal error.         |
1771
1772**Example**
1773
1774```js
1775tls.bind({ address: '192.168.xx.xxx', port: xxxx, family: 1 }, err => {
1776  if (err) {
1777    console.log('bind fail');
1778    return;
1779  }
1780  console.log('bind success');
1781});
1782
1783tls.setExtraOptions({
1784  keepAlive: true,
1785  OOBInline: true,
1786  TCPNoDelay: true,
1787  socketLinger: { on: true, linger: 10 },
1788  receiveBufferSize: 1000,
1789  sendBufferSize: 1000,
1790  reuseAddress: true,
1791  socketTimeout: 3000,
1792}, err => {
1793  if (err) {
1794    console.log('setExtraOptions fail');
1795    return;
1796  }
1797  console.log('setExtraOptions success');
1798});
1799```
1800
1801### setExtraOptions<sup>9+</sup>
1802
1803setExtraOptions(options: TCPExtraOptions): Promise\<void\>
1804
1805Sets other properties of the TCPSocket connection after successful binding of the local IP address and port number of the TLSSocket connection. This API uses a promise to return the result.
1806
1807**System capability**: SystemCapability.Communication.NetStack
1808
1809**Parameters**
1810
1811| Name | Type                                     | Mandatory| Description                                                        |
1812| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
1813| options | [TCPExtraOptions](#tcpextraoptions) | Yes  | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).|
1814
1815**Return value**
1816
1817| Type           | Description                                                |
1818| :-------------- | :--------------------------------------------------- |
1819| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.|
1820
1821**Error codes**
1822
1823| ID| Error Message                       |
1824| ------- | ------------------------------ |
1825| 401     | Parameter error.               |
1826| 2303188 | Socket operation on non-socket.|
1827| 2300002 | System internal error.         |
1828
1829**Example**
1830
1831```js
1832tls.bind({ address: '192.168.xx.xxx', port: xxxx, family: 1 }, err => {
1833  if (err) {
1834    console.log('bind fail');
1835    return;
1836  }
1837  console.log('bind success');
1838});
1839let promise = tls.setExtraOptions({
1840  keepAlive: true,
1841  OOBInline: true,
1842  TCPNoDelay: true,
1843  socketLinger: { on: true, linger: 10 },
1844  receiveBufferSize: 1000,
1845  sendBufferSize: 1000,
1846  reuseAddress: true,
1847  socketTimeout: 3000,
1848});
1849promise.then(() => {
1850  console.log('setExtraOptions success');
1851}).catch(err => {
1852  console.log('setExtraOptions fail');
1853});
1854```
1855
1856### on('message')<sup>9+</sup>
1857
1858on(type: 'message', callback: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}>): void;
1859
1860Subscribes to **message** events of the TLSSocket connection. This API uses an asynchronous callback to return the result.
1861
1862**System capability**: SystemCapability.Communication.NetStack
1863
1864**Parameters**
1865
1866| Name  | Type                                                        | Mandatory| Description                                     |
1867| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
1868| type     | string                                                       | Yes  | Type of the event to subscribe to.<br /> **message**: message receiving event|
1869| callback | Callback\<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}\> | Yes  | Callback used to return the result.<br> **message**: received message.<br>**remoteInfo**: socket connection information.|
1870
1871**Example**
1872
1873```js
1874let tls = socket.constructTLSSocketInstance();
1875tls.on('message', value => {
1876  for (var i = 0; i < value.message.length; i++) {
1877    let messages = value.message[i]
1878    let message = String.fromCharCode(messages);
1879    let messageView = '';
1880    messageView += item;
1881  }
1882  console.log('on message message: ' + JSON.stringify(messageView));
1883  console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo));
1884});
1885```
1886
1887### off('message')<sup>9+</sup>
1888
1889off(type: 'message', callback?: Callback\<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void
1890
1891Unsubscribes from **message** events of the TLSSocket connection. This API uses an asynchronous callback to return the result.
1892
1893> **NOTE**
1894> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
1895
1896**System capability**: SystemCapability.Communication.NetStack
1897
1898**Parameters**
1899
1900| Name  | Type                                                        | Mandatory| Description                                     |
1901| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
1902| type     | string                                                       | Yes  | Type of the event to subscribe to.<br /> **message**: message receiving event|
1903| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No  | Callback used to return the result. **message**: received message.<br>**remoteInfo**: socket connection information.|
1904
1905**Example**
1906
1907```js
1908let tls = socket.constructTLSSocketInstance();
1909let callback = value => {
1910  for (var i = 0; i < value.message.length; i++) {
1911    let messages = value.message[i]
1912    let message = String.fromCharCode(messages);
1913    let messageView = '';
1914    messageView += item;
1915  }
1916  console.log('on message message: ' + JSON.stringify(messageView));
1917  console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo));
1918}
1919tls.on('message', callback);
1920// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
1921tls.off('message', callback);
1922```
1923### on('connect' | 'close')<sup>9+</sup>
1924
1925on(type: 'connect' | 'close', callback: Callback\<void\>): void
1926
1927Enables listening for connection or close events of the TLSSocket connection. This API uses an asynchronous callback to return the result.
1928
1929**System capability**: SystemCapability.Communication.NetStack
1930
1931**Parameters**
1932
1933| Name  | Type            | Mandatory| Description                                                        |
1934| -------- | ---------------- | ---- | ------------------------------------------------------------ |
1935| type     | string           | Yes  | Type of the event to subscribe to.<br /><br>- **connect**: connection event<br>- **close**: close event|
1936| callback | Callback\<void\> | Yes  | Callback used to return the result.                                                  |
1937
1938**Example**
1939
1940```js
1941let tls = socket.constructTLSSocketInstance();
1942tls.on('connect', () => {
1943  console.log("on connect success")
1944});
1945tls.on('close', () => {
1946  console.log("on close success")
1947});
1948```
1949
1950### off('connect' | 'close')<sup>9+</sup>
1951
1952off(type: 'connect' | 'close', callback?: Callback\<void\>): void
1953
1954Disables listening for connection or close events of the TLSSocket connection. This API uses an asynchronous callback to return the result.
1955
1956> **NOTE**
1957> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
1958
1959**System capability**: SystemCapability.Communication.NetStack
1960
1961**Parameters**
1962
1963| Name  | Type            | Mandatory| Description                                                        |
1964| -------- | ---------------- | ---- | ------------------------------------------------------------ |
1965| type     | string           | Yes  | Type of the event to subscribe to.<br /><br>- **connect**: connection event<br>- **close**: close event|
1966| callback | Callback\<void\> | No  | Callback used to return the result.                                                  |
1967
1968**Example**
1969
1970```js
1971let tls = socket.constructTLSSocketInstance();
1972let callback1 = () => {
1973  console.log("on connect success");
1974}
1975tls.on('connect', callback1);
1976// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
1977tls.off('connect', callback1);
1978tls.off('connect');
1979let callback2 = () => {
1980  console.log("on close success");
1981}
1982tls.on('close', callback2);
1983// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
1984tls.off('close', callback2);
1985```
1986
1987### on('error')<sup>9+</sup>
1988
1989on(type: 'error', callback: ErrorCallback): void
1990
1991Enables listening for error events of the TLSSocket connection. This API uses an asynchronous callback to return the result.
1992
1993**System capability**: SystemCapability.Communication.NetStack
1994
1995**Parameters**
1996
1997| Name  | Type         | Mandatory| Description                                |
1998| -------- | ------------- | ---- | ------------------------------------ |
1999| type     | string        | Yes  | Type of the event to subscribe to.<br /> **error**: error event|
2000| callback | ErrorCallback | Yes  | Callback used to return the result.                          |
2001
2002**Example**
2003
2004```js
2005let tls = socket.constructTLSSocketInstance();
2006tls.on('error', err => {
2007  console.log("on error, err:" + JSON.stringify(err))
2008});
2009```
2010
2011### off('error')<sup>9+</sup>
2012
2013off(type: 'error', callback?: ErrorCallback): void
2014
2015Disables listening for error events of the TLSSocket connection. This API uses an asynchronous callback to return the result.
2016
2017> **NOTE**
2018> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
2019
2020**System capability**: SystemCapability.Communication.NetStack
2021
2022**Parameters**
2023
2024| Name  | Type         | Mandatory| Description                                |
2025| -------- | ------------- | ---- | ------------------------------------ |
2026| type     | string        | Yes  | Type of the event to subscribe to.<br /> **error**: error event|
2027| callback | ErrorCallback | No  | Callback used to return the result.                          |
2028
2029**Example**
2030
2031```js
2032let tls = socket.constructTLSSocketInstance();
2033let callback = err => {
2034  console.log("on error, err:" + JSON.stringify(err));
2035}
2036tls.on('error', callback);
2037// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
2038tls.off('error', callback);
2039```
2040
2041### connect<sup>9+</sup>
2042
2043connect(options: TLSConnectOptions, callback: AsyncCallback\<void\>): void
2044
2045Sets up a TLSSocket connection, and creates and initializes a TLS session after successful binding of the local IP address and port number of the TLSSocket connection. 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.
2046
2047**System capability**: SystemCapability.Communication.NetStack
2048
2049**Parameters**
2050
2051| Name  | Type                                  | Mandatory| Description|
2052| -------- | ---------------------------------------| ----| --------------- |
2053| options  | [TLSConnectOptions](#tlsconnectoptions9) | Yes  | Parameters required for the TLSSocket connection.|
2054| 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.|
2055
2056**Error codes**
2057
2058| ID| Error Message                                     |
2059| ------- | -------------------------------------------- |
2060| 401     | Parameter error.                             |
2061| 2303104 | Interrupted system call.                     |
2062| 2303109 | Bad file number.                             |
2063| 2303111 | Resource temporarily unavailable try again.  |
2064| 2303188 | Socket operation on non-socket.              |
2065| 2303191 | Protocol wrong type for socket.              |
2066| 2303198 | Address already in use.                      |
2067| 2303199 | Cannot assign requested address.             |
2068| 2303210 | Connection timed out.                        |
2069| 2303501 | SSL is null.                                 |
2070| 2303502 | Error in tls reading.                        |
2071| 2303503 | Error in tls writing                         |
2072| 2303505 | Error occurred in the tls system call.       |
2073| 2303506 | Error clearing tls connection.               |
2074| 2300002 | System internal error.                       |
2075
2076**Example**
2077
2078```js
2079let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication
2080tlsTwoWay.bind({ address: '192.168.xxx.xxx', port: 8080, family: 1 }, err => {
2081  if (err) {
2082    console.log('bind fail');
2083    return;
2084  }
2085  console.log('bind success');
2086});
2087let options = {
2088  ALPNProtocols: ["spdy/1", "http/1.1"],
2089  address: {
2090    address: "192.168.xx.xxx",
2091    port: 8080,
2092    family: 1,
2093  },
2094  secureOptions: {
2095    key: "xxxx",
2096    cert: "xxxx",
2097    ca: ["xxxx"],
2098    password: "xxxx",
2099    protocols: [socket.Protocol.TLSv12],
2100    useRemoteCipherPrefer: true,
2101    signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
2102    cipherSuite: "AES256-SHA256",
2103  },
2104};
2105tlsTwoWay.connect(options, (err, data) => {
2106  console.error("connect callback error" + err);
2107  console.log(JSON.stringify(data));
2108});
2109
2110let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
2111tlsOneWay.bind({ address: '192.168.xxx.xxx', port: 8080, family: 1 }, err => {
2112  if (err) {
2113    console.log('bind fail');
2114    return;
2115  }
2116  console.log('bind success');
2117});
2118let oneWayOptions = {
2119  address: {
2120    address: "192.168.xxx.xxx",
2121    port: 8080,
2122    family: 1,
2123  },
2124  secureOptions: {
2125    ca: ["xxxx", "xxxx"],
2126    cipherSuite: "AES256-SHA256",
2127  },
2128};
2129tlsOneWay.connect(oneWayOptions, (err, data) => {
2130  console.error("connect callback error" + err);
2131  console.log(JSON.stringify(data));
2132});
2133```
2134
2135### connect<sup>9+</sup>
2136
2137connect(options: TLSConnectOptions): Promise\<void\>
2138
2139Sets up a TLSSocket connection, and creates and initializes a TLS session after successful binding of the local IP address and port number of the TLSSocket connection. 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.
2140
2141**System capability**: SystemCapability.Communication.NetStack
2142
2143**Parameters**
2144
2145| Name  | Type                                  | Mandatory| Description|
2146| -------- | --------------------------------------| ----| --------------- |
2147| options  | [TLSConnectOptions](#tlsconnectoptions9) | Yes  | Parameters required for the connection.|
2148
2149**Return value**
2150
2151| Type                                       | Description                         |
2152| ------------------------------------------- | ----------------------------- |
2153| 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.|
2154
2155**Error codes**
2156
2157| ID| Error Message                                     |
2158| ------- | -------------------------------------------- |
2159| 401     | Parameter error.                             |
2160| 2303104 | Interrupted system call.                     |
2161| 2303109 | Bad file number.                             |
2162| 2303111 | Resource temporarily unavailable try again.  |
2163| 2303188 | Socket operation on non-socket.              |
2164| 2303191 | Protocol wrong type for socket.              |
2165| 2303198 | Address already in use.                      |
2166| 2303199 | Cannot assign requested address.             |
2167| 2303210 | Connection timed out.                        |
2168| 2303501 | SSL is null.                                 |
2169| 2303502 | Error in tls reading.                        |
2170| 2303503 | Error in tls writing                         |
2171| 2303505 | Error occurred in the tls system call.       |
2172| 2303506 | Error clearing tls connection.               |
2173| 2300002 | System internal error.                       |
2174
2175**Example**
2176
2177```js
2178let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication
2179tlsTwoWay.bind({ address: '192.168.xxx.xxx', port: 8080, family: 1 }, err => {
2180  if (err) {
2181    console.log('bind fail');
2182    return;
2183  }
2184  console.log('bind success');
2185});
2186let options = {
2187  ALPNProtocols: ["spdy/1", "http/1.1"],
2188  address: {
2189    address: "xxxx",
2190    port: 8080,
2191    family: 1,
2192  },
2193  secureOptions: {
2194    key: "xxxx",
2195    cert: "xxxx",
2196    ca: ["xxxx"],
2197    password: "xxxx",
2198    protocols: [socket.Protocol.TLSv12],
2199    useRemoteCipherPrefer: true,
2200    signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
2201    cipherSuite: "AES256-SHA256",
2202  },
2203};
2204tlsTwoWay.connect(options).then(data => {
2205  console.log(JSON.stringify(data));
2206}).catch(err => {
2207  console.error(err);
2208});
2209
2210let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
2211tlsOneWay.bind({ address: '192.168.xxx.xxx', port: 8080, family: 1 }, err => {
2212  if (err) {
2213    console.log('bind fail');
2214    return;
2215  }
2216  console.log('bind success');
2217});
2218let oneWayOptions = {
2219  address: {
2220    address: "192.168.xxx.xxx",
2221    port: 8080,
2222    family: 1,
2223  },
2224  secureOptions: {
2225    ca: ["xxxx", "xxxx"],
2226    cipherSuite: "AES256-SHA256",
2227  },
2228};
2229tlsOneWay.connect(oneWayOptions).then(data => {
2230  console.log(JSON.stringify(data));
2231}).catch(err => {
2232  console.error(err);
2233});
2234```
2235
2236### getRemoteAddress<sup>9+</sup>
2237
2238getRemoteAddress(callback: AsyncCallback\<NetAddress\>): void
2239
2240Obtains the remote address of a TLSSocket connection. This API uses an asynchronous callback to return the result.
2241
2242**System capability**: SystemCapability.Communication.NetStack
2243
2244**Parameters**
2245
2246| Name  | Type                                             | Mandatory| Description      |
2247| -------- | ------------------------------------------------- | ---- | ---------- |
2248| 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.|
2249
2250**Error codes**
2251
2252| ID| Error Message                       |
2253| ------- | -----------------------------  |
2254| 2303188 | Socket operation on non-socket.|
2255| 2300002 | System internal error.         |
2256
2257**Example**
2258
2259```js
2260tls.getRemoteAddress((err, data) => {
2261  if (err) {
2262    console.log('getRemoteAddress fail');
2263    return;
2264  }
2265  console.log('getRemoteAddress success:' + JSON.stringify(data));
2266});
2267```
2268
2269### getRemoteAddress<sup>9+</sup>
2270
2271getRemoteAddress(): Promise\<NetAddress\>
2272
2273Obtains the remote address of a TLSSocket connection. This API uses a promise to return the result.
2274
2275**System capability**: SystemCapability.Communication.NetStack
2276
2277**Return value**
2278
2279| Type                                       | Description                                       |
2280| :------------------------------------------ | :------------------------------------------ |
2281| Promise\<[NetAddress](#netaddress)> | Promise used to return the result. If the operation fails, an error message is returned.|
2282
2283**Error codes**
2284
2285| ID| Error Message                       |
2286| ------- | ------------------------------ |
2287| 2303188 | Socket operation on non-socket.|
2288| 2300002 | System internal error.         |
2289
2290**Example**
2291
2292```js
2293let promise = tls.getRemoteAddress();
2294promise.then(() => {
2295  console.log('getRemoteAddress success');
2296}).catch(err => {
2297  console.log('getRemoteAddress fail');
2298});
2299```
2300
2301### getCertificate<sup>9+</sup>
2302
2303getCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)\>): void
2304
2305Obtains the local digital certificate after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses an asynchronous callback to return the result.
2306
2307**System capability**: SystemCapability.Communication.NetStack
2308
2309**Parameters**
2310
2311| Name  | Type                                  | Mandatory| Description|
2312| -------- | ----------------------------------------| ---- | ---------------|
2313| 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.|
2314
2315**Error codes**
2316
2317| ID| Error Message                       |
2318| ------- | ------------------------------ |
2319| 2303501 | SSL is null.                   |
2320| 2303504 | Error looking up x509.         |
2321| 2300002 | System internal error.         |
2322
2323**Example**
2324
2325```js
2326tls.getCertificate((err, data) => {
2327  if (err) {
2328    console.log("getCertificate callback error = " + err);
2329  } else {
2330    console.log("getCertificate callback = " + data);
2331  }
2332});
2333```
2334
2335### getCertificate<sup>9+</sup>
2336
2337getCertificate():Promise\<[X509CertRawData](#x509certrawdata9)\>
2338
2339Obtains the local digital certificate after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses a promise to return the result.
2340
2341**System capability**: SystemCapability.Communication.NetStack
2342
2343**Return value**
2344
2345| Type           | Description                 |
2346| -------------- | -------------------- |
2347| Promise\<[X509CertRawData](#x509certrawdata9)\> | Promise used to return the result. If the operation fails, an error message is returned.|
2348
2349**Error codes**
2350
2351| ID| Error Message                       |
2352| ------- | ------------------------------ |
2353| 2303501 | SSL is null.                   |
2354| 2303504 | Error looking up x509.         |
2355| 2300002 | System internal error.         |
2356
2357**Example**
2358
2359```js
2360tls.getCertificate().then(data => {
2361  console.log(data);
2362}).catch(err => {
2363  console.error(err);
2364});
2365```
2366
2367### getRemoteCertificate<sup>9+</sup>
2368
2369getRemoteCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)\>): void
2370
2371Obtains the digital certificate of the server after a TLSSocket connection is established. This API uses an asynchronous callback to return the result.
2372
2373**System capability**: SystemCapability.Communication.NetStack
2374
2375**Parameters**
2376
2377| Name   | Type                                   | Mandatory | Description          |
2378| -------- | ----------------------------------------| ---- | ---------------|
2379| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)\>  | Yes  | Callback used to return the result. If the operation fails, an error message is returned.|
2380
2381**Error codes**
2382
2383| ID| Error Message                       |
2384| ------- | ------------------------------ |
2385| 2303501 | SSL is null.                   |
2386| 2300002 | System internal error.         |
2387
2388**Example**
2389
2390```js
2391tls.getRemoteCertificate((err, data) => {
2392  if (err) {
2393    console.log("getRemoteCertificate callback error = " + err);
2394  } else {
2395    console.log("getRemoteCertificate callback = " + data);
2396  }
2397});
2398```
2399
2400### getRemoteCertificate<sup>9+</sup>
2401
2402getRemoteCertificate():Promise\<[X509CertRawData](#x509certrawdata9)\>
2403
2404Obtains the digital certificate of the server after a TLSSocket connection is established. This API uses a promise to return the result.
2405
2406**System capability**: SystemCapability.Communication.NetStack
2407
2408**Return value**
2409
2410| Type           | Description                 |
2411| -------------- | -------------------- |
2412| Promise\<[X509CertRawData](#x509certrawdata9)\> | Promise used to return the result. If the operation fails, an error message is returned.|
2413
2414**Error codes**
2415
2416| ID| Error Message                       |
2417| ------- | ------------------------------ |
2418| 2303501 | SSL is null.                   |
2419| 2300002 | System internal error.         |
2420
2421**Example**
2422
2423```js
2424tls.getRemoteCertificate().then(data => {
2425  console.log(data);
2426}).catch(err => {
2427  console.error(err);
2428});
2429```
2430
2431### getProtocol<sup>9+</sup>
2432
2433getProtocol(callback: AsyncCallback\<string\>): void
2434
2435Obtains the communication protocol version after a TLSSocket connection is established. This API uses an asynchronous callback to return the result.
2436
2437**System capability**: SystemCapability.Communication.NetStack
2438
2439**Parameters**
2440
2441| Name  | Type                                      | Mandatory| Description          |
2442| -------- | ----------------------------------------| ---- | ---------------|
2443| callback | AsyncCallback\<string\>                  | Yes  | Callback used to return the result. If the operation fails, an error message is returned.|
2444
2445**Error codes**
2446
2447| ID| Error Message                       |
2448| ------- | -----------------------------  |
2449| 2303501 | SSL is null.                   |
2450| 2303505 | Error occurred in the tls system call. |
2451| 2300002 | System internal error.         |
2452
2453**Example**
2454
2455```js
2456tls.getProtocol((err, data) => {
2457  if (err) {
2458    console.log("getProtocol callback error = " + err);
2459  } else {
2460    console.log("getProtocol callback = " + data);
2461  }
2462});
2463```
2464
2465### getProtocol<sup>9+</sup>
2466
2467getProtocol():Promise\<string\>
2468
2469Obtains the communication protocol version after a TLSSocket connection is established. This API uses a promise to return the result.
2470
2471**System capability**: SystemCapability.Communication.NetStack
2472
2473**Return value**
2474
2475| Type           | Description                 |
2476| -------------- | -------------------- |
2477| Promise\<string\> | Promise used to return the result. If the operation fails, an error message is returned.|
2478
2479**Error codes**
2480
2481| ID| Error Message                       |
2482| ------- | ------------------------------ |
2483| 2303501 | SSL is null.                   |
2484| 2303505 | Error occurred in the tls system call. |
2485| 2300002 | System internal error.         |
2486
2487**Example**
2488
2489```js
2490tls.getProtocol().then(data => {
2491  console.log(data);
2492}).catch(err => {
2493  console.error(err);
2494});
2495```
2496
2497### getCipherSuite<sup>9+</sup>
2498
2499getCipherSuite(callback: AsyncCallback\<Array\<string\>\>): void
2500
2501Obtains the cipher suite negotiated by both communication parties after a TLSSocket connection is established. This API uses an asynchronous callback to return the result.
2502
2503**System capability**: SystemCapability.Communication.NetStack
2504
2505**Parameters**
2506
2507| Name  | Type                                    | Mandatory| Description|
2508| -------- | ----------------------------------------| ---- | ---------------|
2509| callback | AsyncCallback\<Array\<string\>\>          | Yes  | Callback used to return the result. If the operation fails, an error message is returned.|
2510
2511**Error codes**
2512
2513| ID| Error Message                       |
2514| ------- | ------------------------------ |
2515| 2303501 | SSL is null.                   |
2516| 2303502 | Error in tls reading.          |
2517| 2303505 | Error occurred in the tls system call. |
2518| 2300002 | System internal error.         |
2519
2520**Example**
2521
2522```js
2523tls.getCipherSuite((err, data) => {
2524  if (err) {
2525    console.log("getCipherSuite callback error = " + err);
2526  } else {
2527    console.log("getCipherSuite callback = " + data);
2528  }
2529});
2530```
2531
2532### getCipherSuite<sup>9+</sup>
2533
2534getCipherSuite(): Promise\<Array\<string\>\>
2535
2536Obtains the cipher suite negotiated by both communication parties after a TLSSocket connection is established. This API uses a promise to return the result.
2537
2538**System capability**: SystemCapability.Communication.NetStack
2539
2540**Return value**
2541
2542| Type                   | Description                 |
2543| ---------------------- | --------------------- |
2544| Promise\<Array\<string\>\> | Promise used to return the result. If the operation fails, an error message is returned.|
2545
2546**Error codes**
2547
2548| ID| Error Message                       |
2549| ------- | ------------------------------ |
2550| 2303501 | SSL is null.                   |
2551| 2303502 | Error in tls reading.          |
2552| 2303505 | Error occurred in the tls system call. |
2553| 2300002 | System internal error.         |
2554
2555**Example**
2556
2557```js
2558tls.getCipherSuite().then(data => {
2559  console.log('getCipherSuite success:' + JSON.stringify(data));
2560}).catch(err => {
2561  console.error(err);
2562});
2563```
2564
2565### getSignatureAlgorithms<sup>9+</sup>
2566
2567getSignatureAlgorithms(callback: AsyncCallback\<Array\<string\>\>): void
2568
2569Obtains the signing algorithm negotiated by both communication parties after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses an asynchronous callback to return the result.
2570
2571**System capability**: SystemCapability.Communication.NetStack
2572
2573**Parameters**
2574
2575| Name  | Type                                  | Mandatory| Description           |
2576| -------- | -------------------------------------| ---- | ---------------|
2577| callback | AsyncCallback\<Array\<string\>\>         | Yes  | Callback used to return the result.  |
2578
2579**Error codes**
2580
2581| ID| Error Message                       |
2582| ------- | ------------------------------ |
2583| 2303501 | SSL is null.                   |
2584| 2300002 | System internal error.         |
2585
2586**Example**
2587
2588```js
2589tls.getSignatureAlgorithms((err, data) => {
2590  if (err) {
2591    console.log("getSignatureAlgorithms callback error = " + err);
2592  } else {
2593    console.log("getSignatureAlgorithms callback = " + data);
2594  }
2595});
2596```
2597
2598### getSignatureAlgorithms<sup>9+</sup>
2599
2600getSignatureAlgorithms(): Promise\<Array\<string\>\>
2601
2602Obtains the signing algorithm negotiated by both communication parties after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses a promise to return the result.
2603
2604**System capability**: SystemCapability.Communication.NetStack
2605
2606**Return value**
2607
2608| Type                   | Description                 |
2609| ---------------------- | -------------------- |
2610| Promise\<Array\<string\>\> | Promise used to return the result.|
2611
2612**Error codes**
2613
2614| ID| Error Message                       |
2615| ------- | ------------------------------ |
2616| 2303501 | SSL is null.                   |
2617| 2300002 | System internal error.         |
2618
2619**Example**
2620
2621```js
2622tls.getSignatureAlgorithms().then(data => {
2623  console.log("getSignatureAlgorithms success" + data);
2624}).catch(err => {
2625  console.error(err);
2626});
2627```
2628
2629### send<sup>9+</sup>
2630
2631send(data: string, callback: AsyncCallback\<void\>): void
2632
2633Sends a message to the server after a TLSSocket connection is established. This API uses an asynchronous callback to return the result.
2634
2635**System capability**: SystemCapability.Communication.NetStack
2636
2637**Parameters**
2638
2639| Name   | Type                         | Mandatory| Description           |
2640| -------- | -----------------------------| ---- | ---------------|
2641|   data   | string                       | Yes  | Data content of the message to send.  |
2642| callback | AsyncCallback\<void\>         | Yes  | Callback used to return the result. If the operation fails, an error message is returned.|
2643
2644**Error codes**
2645
2646| ID| Error Message                                     |
2647| ------- | -------------------------------------------- |
2648| 401     | Parameter error.                             |
2649| 2303501 | SSL is null.                                 |
2650| 2303503 | Error in tls writing                         |
2651| 2303505 | Error occurred in the tls system call.       |
2652| 2303506 | Error clearing tls connection.               |
2653| 2300002 | System internal error.                       |
2654
2655**Example**
2656
2657```js
2658tls.send("xxxx", (err) => {
2659  if (err) {
2660    console.log("send callback error = " + err);
2661  } else {
2662    console.log("send success");
2663  }
2664});
2665```
2666
2667### send<sup>9+</sup>
2668
2669send(data: string): Promise\<void\>
2670
2671Sends a message to the server after a TLSSocket connection is established. This API uses a promise to return the result.
2672
2673**System capability**: SystemCapability.Communication.NetStack
2674
2675**Parameters**
2676
2677| Name   | Type                         | Mandatory| Description           |
2678| -------- | -----------------------------| ---- | ---------------|
2679|   data   | string                       | Yes  | Data content of the message to send.  |
2680
2681**Error codes**
2682
2683| ID| Error Message                                     |
2684| ------- | -------------------------------------------- |
2685| 401     | Parameter error.                             |
2686| 2303501 | SSL is null.                                 |
2687| 2303503 | Error in tls writing                         |
2688| 2303505 | Error occurred in the tls system call.       |
2689| 2303506 | Error clearing tls connection.               |
2690| 2300002 | System internal error.                       |
2691
2692**Return value**
2693
2694| Type          | Description                 |
2695| -------------- | -------------------- |
2696| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.|
2697
2698**Example**
2699
2700```js
2701tls.send("xxxx").then(() => {
2702  console.log("send success");
2703}).catch(err => {
2704  console.error(err);
2705});
2706```
2707
2708### close<sup>9+</sup>
2709
2710close(callback: AsyncCallback\<void\>): void
2711
2712Closes a TLSSocket connection. This API uses an asynchronous callback to return the result.
2713
2714**System capability**: SystemCapability.Communication.NetStack
2715
2716**Parameters**
2717
2718| Name   | Type                         | Mandatory| Description           |
2719| -------- | -----------------------------| ---- | ---------------|
2720| callback | AsyncCallback\<void\>         | Yes  | Callback used to return the result. If the operation fails, an error message is returned.|
2721
2722**Error codes**
2723
2724| ID| Error Message                                     |
2725| ------- | -------------------------------------------- |
2726| 2303501 | SSL is null.                                 |
2727| 2303505 | Error occurred in the tls system call.       |
2728| 2303506 | Error clearing tls connection.               |
2729| 2300002 | System internal error.                       |
2730
2731**Example**
2732
2733```js
2734tls.close((err) => {
2735  if (err) {
2736    console.log("close callback error = " + err);
2737  } else {
2738    console.log("close success");
2739  }
2740});
2741```
2742
2743### close<sup>9+</sup>
2744
2745close(): Promise\<void\>
2746
2747Closes a TLSSocket connection. This API uses a promise to return the result.
2748
2749**System capability**: SystemCapability.Communication.NetStack
2750
2751**Return value**
2752
2753| Type          | Description                 |
2754| -------------- | -------------------- |
2755| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.|
2756
2757**Error codes**
2758
2759| ID| Error Message                                     |
2760| ------- | -------------------------------------------- |
2761| 2303501 | SSL is null.                                 |
2762| 2303505 | Error occurred in the tls system call.       |
2763| 2303506 | Error clearing tls connection.               |
2764| 2300002 | System internal error.                       |
2765
2766**Example**
2767
2768```js
2769tls.close().then(() => {
2770  console.log("close success");
2771}).catch(err => {
2772  console.error(err);
2773});
2774```
2775
2776## TLSConnectOptions<sup>9+</sup>
2777
2778Defines TLS connection options.
2779
2780**System capability**: SystemCapability.Communication.NetStack
2781
2782| Name         | Type                                    | Mandatory| Description           |
2783| -------------- | ------------------------------------- | ---  |-------------- |
2784| address        | [NetAddress](#netaddress)             | Yes |  Gateway address.      |
2785| secureOptions  | [TLSSecureOptions](#tlssecureoptions9) | Yes| TLS security options.|
2786| ALPNProtocols  | Array\<string\>                         | No| ALPN protocol. The value range is ["spdy/1", "http/1.1"]. The default value is **[]**.     |
2787
2788## TLSSecureOptions<sup>9+</sup>
2789
2790Defines 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.
2791
2792**System capability**: SystemCapability.Communication.NetStack
2793
2794| Name                | Type                                                   | Mandatory| Description                               |
2795| --------------------- | ------------------------------------------------------ | --- |----------------------------------- |
2796| ca                    | string \| Array\<string\>                               | Yes| CA certificate of the server, which is used to authenticate the digital certificate of the server.|
2797| cert                  | string                                                  | No| Digital certificate of the local client.                |
2798| key                   | string                                                  | No| Private key of the local digital certificate.                  |
2799| password                | string                                                  | No| Password for reading the private key.                     |
2800| protocols             | [Protocol](#protocol9) \|Array\<[Protocol](#protocol9)\> | No| TLS protocol version. The default value is **TLSv1.2**.                 |
2801| useRemoteCipherPrefer | boolean                                                 | No| Whether to use the remote cipher suite preferentially.         |
2802| signatureAlgorithms   | string                                                 | No| Signing algorithm used during communication. The default value is **""**.              |
2803| cipherSuite           | string                                                 | No| Cipher suite used during communication. The default value is **""**.              |
2804
2805## Protocol<sup>9+</sup>
2806
2807Enumerates TLS protocol versions.
2808
2809**System capability**: SystemCapability.Communication.NetStack
2810
2811| Name     |    Value   | Description               |
2812| --------- | --------- |------------------ |
2813| TLSv12    | "TLSv1.2" | TLSv1.2.|
2814| TLSv13    | "TLSv1.3" | TLSv1.3.|
2815
2816## X509CertRawData<sup>9+</sup>
2817
2818Defines the certificate raw data.
2819
2820**System capability**: SystemCapability.Communication.NetStack
2821
2822| Type                                                                  | Description                  |
2823| --------------------------------------------------------------------- | --------------------- |
2824|[cert.EncodingBlob](js-apis-cert.md#datablob) | Data and encoding format of the certificate.|
2825