• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Socket Connection
2
3> **NOTE**<br>
4> 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.
5
6## Modules to Import
7
8```
9import socket from '@ohos.net.socket';
10```
11
12## socket.constructUDPSocketInstance
13
14constructUDPSocketInstance\(\): UDPSocket
15
16Creates a **UDPSocket** object.
17
18**System capability**: SystemCapability.Communication.NetStack
19
20**Return Value**
21
22| Type                              | Description                   |
23| :--------------------------------- | :---------------------- |
24| [UDPSocket](#udpsocket) | **UDPSocket** object.|
25
26
27**Example**
28
29```
30let udp = socket.constructUDPSocketInstance();
31```
32
33
34## UDPSocket
35
36Defines a **UDPSocket** connection. Before invoking UDPSocket APIs, you need to call [socket.constructUDPSocketInstance](#socketconstructudpsocketinstance) to create a **UDPSocket** object.
37
38### bind
39
40bind\(address: NetAddress, callback: AsyncCallback<void\>\): void
41
42Binds 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.
43
44**Required permission**: ohos.permission.INTERNET
45
46**System capability**: SystemCapability.Communication.NetStack
47
48**Parameters**
49
50| Name  | Type                              | Mandatory| Description                                                  |
51| -------- | ---------------------------------- | ---- | ------------------------------------------------------ |
52| address  | [NetAddress](#netaddress) | Yes  | Destination address. For details, see [NetAddress](#netaddress).|
53| callback | AsyncCallback\<void\>              | Yes  | Callback used to return the result.                                            |
54
55**Example**
56
57```
58let udp = socket.constructUDPSocketInstance();
59udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
60  if (err) {
61	console.log('bind fail');
62	return;
63  }
64  console.log('bind success');
65})
66```
67
68
69### bind
70
71bind\(address: NetAddress\): Promise<void\>
72
73Binds 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.
74
75**Required permission**: ohos.permission.INTERNET
76
77**System capability**: SystemCapability.Communication.NetStack
78
79**Parameters**
80
81| Name | Type                              | Mandatory| Description                                                  |
82| ------- | ---------------------------------- | ---- | ------------------------------------------------------ |
83| address | [NetAddress](#netaddress) | Yes  | Destination address. For details, see [NetAddress](#netaddress).|
84
85
86**Return Value**
87
88| Type           | Description                                      |
89| :-------------- | :----------------------------------------- |
90| Promise\<void\> | Promise used to return the result.|
91
92**Example**
93
94```
95let udp = socket.constructUDPSocketInstance();
96let promise = udp.bind({address: '192.168.xx.xxx', port: 8080, family: 1});
97promise .then(() => {
98  console.log('bind success');
99}).catch(err => {
100  console.log('bind fail');
101});
102```
103
104
105### send
106
107send\(options: UDPSendOptions, callback: AsyncCallback<void\>\): void
108
109Sends data over a UDPSocket connection. This API uses an asynchronous callback to return the result.
110
111Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and port.
112
113**Required permission**: ohos.permission.INTERNET
114
115**System capability**: SystemCapability.Communication.NetStack
116
117**Parameters**
118
119| Name  | Type                                    | Mandatory| Description                                                        |
120| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
121| options  | [UDPSendOptions](#udpsendoptions) | Yes  | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).|
122| callback | AsyncCallback\<void\>                    | Yes  | Callback used to return the result.                                                  |
123
124**Example**
125
126```
127let udp = socket.constructUDPSocketInstance();
128udp.send({
129  data:'Hello, server!',
130  address: {
131	address:'192.168.xx.xxx',
132	port:xxxx,
133	family:1
134  }
135}, err=> {
136	if (err) {
137	  console.log('send fail');
138	  return;
139	}
140	console.log('send success');
141})
142```
143
144
145### send
146
147send\(options: UDPSendOptions\): Promise<void\>
148
149Sends data over a UDPSocket connection. This API uses a promise to return the result.
150
151Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and port.
152
153**Required permission**: ohos.permission.INTERNET
154
155**System capability**: SystemCapability.Communication.NetStack
156
157**Parameters**
158
159| Name | Type                                    | Mandatory| Description                                                        |
160| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
161| options | [UDPSendOptions](#udpsendoptions) | Yes  | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).|
162
163**Return Value**
164
165| Type           | Description                                          |
166| :-------------- | :--------------------------------------------- |
167| Promise\<void\> | Promise used to return the result.|
168
169**Example**
170
171```
172let udp = socket.constructUDPSocketInstance();
173let promise = udp.send({
174  data:'Hello, server!',
175  address: {
176	address:'192.168.xx.xxx',
177	port:xxxx,
178	family:1
179  }
180});
181promise.then(() => {
182  console.log('send success');
183}).catch(err => {
184  console.log('send fail');
185});
186```
187
188
189### close
190
191close\(callback: AsyncCallback<void\>\): void
192
193Closes a UDPSocket connection. This API uses an asynchronous callback to return the result.
194
195**Required permission**: ohos.permission.INTERNET
196
197**System capability**: SystemCapability.Communication.NetStack
198
199**Parameters**
200
201| Name  | Type                 | Mandatory| Description      |
202| -------- | --------------------- | ---- | ---------- |
203| callback | AsyncCallback\<void\> | Yes  | Callback used to return the result.|
204
205**Example**
206
207```
208let udp = socket.constructUDPSocketInstance();
209udp.close(err => {
210  if (err) {
211	console.log('close fail');
212	return;
213  }
214  console.log('close success');
215})
216```
217
218
219### close
220
221close\(\): Promise<void\>
222
223Closes a UDPSocket connection. This API uses a promise to return the result.
224
225**Required permission**: ohos.permission.INTERNET
226
227**System capability**: SystemCapability.Communication.NetStack
228
229**Return Value**
230
231| Type           | Description                                      |
232| :-------------- | :----------------------------------------- |
233| Promise\<void\> | Promise used to return the result.|
234
235**Example**
236
237```
238let udp = socket.constructUDPSocketInstance();
239let promise = udp.close();
240promise.then(() => {
241  console.log('close success');
242}).catch(err => {
243  console.log('close fail');
244});
245```
246
247
248### getState
249
250getState\(callback: AsyncCallback<SocketStateBase\>\): void
251
252Obtains the status of the UDPSocket connection. This API uses an asynchronous callback to return the result.
253
254>![](public_sys-resources/icon-note.gif) **NOTE:**
255>This API can be called only after [bind](#bind) is successfully called.
256
257**Required permission**: ohos.permission.INTERNET
258
259**System capability**: SystemCapability.Communication.NetStack
260
261**Parameters**
262
263| Name  | Type                                                  | Mandatory| Description      |
264| -------- | ------------------------------------------------------ | ---- | ---------- |
265| callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | Yes  | Callback used to return the result.|
266
267**Example**
268
269```
270let udp = socket.constructUDPSocketInstance();
271udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
272  if (err) {
273	console.log('bind fail');
274	return;
275  }
276  console.log('bind success');
277  udp.getState((err, data) => {
278	if (err) {
279	  console.log('getState fail');
280	  return;
281	}
282	console.log('getState success:' + JSON.stringify(data));
283  })
284})
285```
286
287
288### getState
289
290getState\(\): Promise<SocketStateBase\>
291
292Obtains the status of the UDPSocket connection. This API uses a promise to return the result.
293
294>![](public_sys-resources/icon-note.gif) **NOTE:**
295>This API can be called only after [bind](#bind) is successfully called.
296
297**Required permission**: ohos.permission.INTERNET
298
299**System capability**: SystemCapability.Communication.NetStack
300
301**Return Value**
302
303| Type                                            | Description                                      |
304| :----------------------------------------------- | :----------------------------------------- |
305| Promise<[SocketStateBase](#socketstatebase)> | Promise used to return the result.|
306
307**Example**
308
309```
310let udp = socket.constructUDPSocketInstance();
311udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
312  if (err) {
313	console.log('bind fail');
314	return;
315  }
316  console.log('bind success');
317  let promise = udp.getState({});
318  promise.then(data => {
319	console.log('getState success:' + JSON.stringify(data));
320  }).catch(err => {
321	console.log('getState fail');
322  });
323})
324```
325
326
327### setExtraOptions
328
329setExtraOptions\(options: UDPExtraOptions, callback: AsyncCallback<void\>\): void
330
331Sets other properties of the UDPSocket connection. This API uses an asynchronous callback to return the result.
332
333>![](public_sys-resources/icon-note.gif) **NOTE:**
334>This API can be called only after [bind](#bind) is successfully called.
335
336**Required permission**: ohos.permission.INTERNET
337
338**System capability**: SystemCapability.Communication.NetStack
339
340**Parameters**
341
342| Name  | Type                                    | Mandatory| Description                                                        |
343| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
344| options  | [UDPExtraOptions](#udpextraoptions) | Yes  | Other properties of the UDPSocket connection. For details, see [UDPExtraOptions](#udpextraoptions).|
345| callback | AsyncCallback\<void\>                    | Yes  | Callback used to return the result.                                                  |
346
347
348**Example**
349
350```
351let udp = socket.constructUDPSocketInstance();
352udp.bind({address:'192.168.xx.xxx', port:xxxx, family:1}, err=> {
353  if (err) {
354	console.log('bind fail');
355	return;
356  }
357  console.log('bind success');
358  udp.setExtraOptions({
359	receiveBufferSize:1000,
360	sendBufferSize:1000,
361	reuseAddress:false,
362	socketTimeout:6000,
363	broadcast:true
364  }, err=> {
365	if (err) {
366	  console.log('setExtraOptions fail');
367	  return;
368	}
369	console.log('setExtraOptions success');
370  })
371})
372```
373
374
375### setExtraOptions
376
377setExtraOptions\(options: UDPExtraOptions\): Promise<void\>
378
379Sets other properties of the UDPSocket connection. This API uses a promise to return the result.
380
381>![](public_sys-resources/icon-note.gif) **NOTE:**
382>This API can be called only after [bind](#bind) is successfully called.
383
384**Required permission**: ohos.permission.INTERNET
385
386**System capability**: SystemCapability.Communication.NetStack
387
388**Parameters**
389
390| Name | Type                                    | Mandatory| Description                                                        |
391| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
392| options | [UDPExtraOptions](#udpextraoptions) | Yes  | Other properties of the UDPSocket connection. For details, see [UDPExtraOptions](#udpextraoptions).|
393
394**Return Value**
395
396| Type           | Description                                                |
397| :-------------- | :--------------------------------------------------- |
398| Promise\<void\> | Promise used to return the result.|
399
400**Example**
401
402```
403let udp = socket.constructUDPSocketInstance();
404let promise = udp.bind({address:'192.168.xx.xxx', port:xxxx, family:1});
405promise.then(() => {
406  console.log('bind success');
407  let promise1 = udp.setExtraOptions({
408	receiveBufferSize:1000,
409	sendBufferSize:1000,
410	reuseAddress:false,
411	socketTimeout:6000,
412	broadcast:true
413  });
414  promise1.then(() => {
415	console.log('setExtraOptions success');
416  }).catch(err => {
417	console.log('setExtraOptions fail');
418  });
419}).catch(err => {
420  console.log('bind fail');
421});
422```
423
424
425### on\('message'\)
426
427on\(type: 'message', callback: Callback<\{message: ArrayBuffer, remoteInfo: SocketRemoteInfo\}\>\): void
428
429Enables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
430
431**System capability**: SystemCapability.Communication.NetStack
432
433**Parameters**
434
435| Name  | Type                                                        | Mandatory| Description                                     |
436| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
437| type     | string                                                       | Yes  | Event type. <br />**message**: message receiving event|
438| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | Yes  | Callback used to return the result.                               |
439
440**Example**
441
442```
443let udp = socket.constructUDPSocketInstance();
444udp.on('message', value => {
445	console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
446});
447```
448
449
450### off\('message'\)
451
452off\(type: 'message', callback?: Callback<\{message: ArrayBuffer, remoteInfo: SocketRemoteInfo\}\>\): void
453
454Disables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
455
456>![](public_sys-resources/icon-note.gif) **NOTE:**
457>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.
458
459**System capability**: SystemCapability.Communication.NetStack
460
461**Parameters**
462
463| Name  | Type                                                        | Mandatory| Description                                     |
464| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
465| type     | string                                                       | Yes  | Event type. <br />**message**: message receiving event|
466| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No  | Callback used to return the result.                               |
467
468**Example**
469
470```
471let udp = socket.constructUDPSocketInstance();
472let callback = value =>{
473	console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
474}
475udp.on('message', callback);
476// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
477udp.off('message', callback);
478udp.off('message');
479```
480
481
482### on\('listening' | 'close'\)
483
484on\(type: 'listening' | 'close', callback: Callback<void\>\): void
485
486Enables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
487
488**System capability**: SystemCapability.Communication.NetStack
489
490**Parameters**
491
492| Name  | Type            | Mandatory| Description                                                        |
493| -------- | ---------------- | ---- | ------------------------------------------------------------ |
494| type     | string           | Yes  | Event type.<br>- **listening**: data packet message event<br>- **close**: close event|
495| callback | Callback\<void\> | Yes  | Callback used to return the result.                                                  |
496
497**Example**
498
499```
500let udp = socket.constructUDPSocketInstance();
501udp.on('listening', () => {
502	console.log("on listening success");
503});
504udp.on('close', () => {
505	console.log("on close success" );
506});
507```
508
509
510### off\('listening' | 'close'\)
511
512off\(type: 'listening' | 'close', callback?: Callback<void\>\): void
513
514Disables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
515
516>![](public_sys-resources/icon-note.gif) **NOTE:**
517>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.
518
519**System capability**: SystemCapability.Communication.NetStack
520
521**Parameters**
522
523| Name  | Type            | Mandatory| Description                                                        |
524| -------- | ---------------- | ---- | ------------------------------------------------------------ |
525| type     | string           | Yes  | Event type.<br>- **listening**: data packet message event<br>- **close**: close event|
526| callback | Callback\<void\> | No  | Callback used to return the result.                                                  |
527
528**Example**
529
530```
531let udp = socket.constructUDPSocketInstance();
532let callback1 = () =>{
533	console.log("on listening, success");
534}
535udp.on('listening', callback1);
536// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
537udp.off('listening', callback1);
538udp.off('listening');
539let callback2 = () =>{
540	console.log("on close, success");
541}
542udp.on('close', callback2);
543// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
544udp.off('close', callback2);
545udp.off('close');
546```
547
548
549### on\('error'\)
550
551on\(type: 'error', callback: ErrorCallback\): void
552
553Enables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
554
555**System capability**: SystemCapability.Communication.NetStack
556
557**Parameters**
558
559| Name  | Type         | Mandatory| Description                                |
560| -------- | ------------- | ---- | ------------------------------------ |
561| type     | string        | Yes  | Event type. <br />**error**: error event|
562| callback | ErrorCallback | Yes  | Callback used to return the result.                          |
563
564
565**Example**
566
567```
568let udp = socket.constructUDPSocketInstance();
569udp.on('error', err => {
570	console.log("on error, err:" + JSON.stringify(err))
571});
572```
573
574
575### off\('error'\)
576
577off\(type: 'error', callback?: ErrorCallback\): void
578
579Disables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
580
581>![](public_sys-resources/icon-note.gif) **NOTE:**
582>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.
583
584**System capability**: SystemCapability.Communication.NetStack
585
586**Parameters**
587
588| Name  | Type         | Mandatory| Description                                |
589| -------- | ------------- | ---- | ------------------------------------ |
590| type     | string        | Yes  | Event type. <br />**error**: error event|
591| callback | ErrorCallback | No  | Callback used to return the result.                          |
592
593**Example**
594
595```
596let udp = socket.constructUDPSocketInstance();
597let callback = err =>{
598	console.log("on error, err:" + JSON.stringify(err));
599}
600udp.on('error', callback);
601// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
602udp.off('error', callback);
603udp.off('error');
604```
605
606
607## NetAddress
608
609Defines the destination address.
610
611**System capability**: SystemCapability.Communication.NetStack
612
613| Name | Type  | Mandatory| Description                                                        |
614| ------- | ------ | ---- | ------------------------------------------------------------ |
615| address | string | Yes  | Bound IP address.                                          |
616| port    | number | No  | Port number. The value ranges from **0** to **65535**. If this parameter is not specified, the system randomly allocates a port.          |
617| family  | number | No  | Network protocol type.<br>- **1**: IPv4<br>- **2**: IPv6<br>The default value is **1**.|
618
619## UDPSendOptions
620
621Defines the parameters for sending data over the UDPSocket connection.
622
623**System capability**: SystemCapability.Communication.NetStack
624
625| Name | Type                              | Mandatory| Description          |
626| ------- | ---------------------------------- | ---- | -------------- |
627| data    | string                             | Yes  | Data to send.  |
628| address | [NetAddress](#netaddress) | Yes  | Destination address.|
629
630## UDPExtraOptions
631
632Defines other properties of the UDPSocket connection.
633
634**System capability**: SystemCapability.Communication.NetStack
635
636| Name           | Type   | Mandatory| Description                            |
637| ----------------- | ------- | ---- | -------------------------------- |
638| broadcast         | boolean | No  | Whether to send broadcast messages. The default value is **false**. |
639| receiveBufferSize | number  | No  | Size of the receive buffer, in bytes.  |
640| sendBufferSize    | number  | No  | Size of the send buffer, in bytes.  |
641| reuseAddress      | boolean | No  | Whether to reuse addresses. The default value is **false**.     |
642| socketTimeout     | number  | No  | Timeout duration of the UDPSocket connection, in ms.|
643
644## SocketStateBase
645
646Defines the status of the UDPSocket connection.
647
648**System capability**: SystemCapability.Communication.NetStack
649
650| Name     | Type   | Mandatory| Description      |
651| ----------- | ------- | ---- | ---------- |
652| isBound     | boolean | Yes  | Whether the connection is in the bound state.|
653| isClose     | boolean | Yes  | Whether the connection is in the closed state.|
654| isConnected | boolean | Yes  | Whether the connection is in the connected state.|
655
656## SocketRemoteInfo
657
658Defines information about the UDPSocket connection.
659
660**System capability**: SystemCapability.Communication.NetStack
661
662| Name | Type  | Mandatory| Description                                                        |
663| ------- | ------ | ---- | ------------------------------------------------------------ |
664| address | string | Yes  | Bound IP address.                                          |
665| family  | string | Yes  | Network protocol type.<br>- IPv4<br>- IPv6<br>The default value is **IPv4**.|
666| port    | number | Yes  | Port number. The value ranges from **0** to **65535**.                                       |
667| size    | number | Yes  | Length of the server response message, in bytes.                                  |
668
669## socket.constructTCPSocketInstance
670
671constructTCPSocketInstance\(\): TCPSocket
672
673Creates a **TCPSocket** object.
674
675**System capability**: SystemCapability.Communication.NetStack
676
677**Return Value**
678
679  | Type                              | Description                   |
680  | :--------------------------------- | :---------------------- |
681  | [TCPSocket](#tcpsocket) | **TCPSocket** object.|
682
683**Example**
684
685```
686let tcp = socket.constructTCPSocketInstance();
687```
688
689
690## TCPSocket
691
692Defines a TCPSocket connection. Before invoking TCPSocket APIs, you need to call [socket.constructTCPSocketInstance](#socketconstructtcpsocketinstance) to create a **TCPSocket** object.
693
694### bind
695
696bind\(address: NetAddress, callback: AsyncCallback<void\>\): void
697
698Binds 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.
699
700**Required permission**: ohos.permission.INTERNET
701
702**System capability**: SystemCapability.Communication.NetStack
703
704**Parameters**
705
706| Name  | Type                              | Mandatory| Description                                                  |
707| -------- | ---------------------------------- | ---- | ------------------------------------------------------ |
708| address  | [NetAddress](#netaddress) | Yes  | Destination address. For details, see [NetAddress](#netaddress).|
709| callback | AsyncCallback\<void\>              | Yes  | Callback used to return the result.                                            |
710
711
712**Example**
713
714```
715let tcp = socket.constructTCPSocketInstance();
716tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
717  if (err) {
718	console.log('bind fail');
719	return;
720  }
721  console.log('bind success');
722})
723```
724
725
726### bind
727
728bind\(address: NetAddress\): Promise<void\>
729
730Binds 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.
731
732**Required permission**: ohos.permission.INTERNET
733
734**System capability**: SystemCapability.Communication.NetStack
735
736**Parameters**
737
738| Name | Type                              | Mandatory| Description                                                  |
739| ------- | ---------------------------------- | ---- | ------------------------------------------------------ |
740| address | [NetAddress](#netaddress) | Yes  | Destination address. For details, see [NetAddress](#netaddress).|
741
742**Return Value**
743
744| Type           | Description                                                    |
745| :-------------- | :------------------------------------------------------- |
746| Promise\<void\> | Promise used to return the result.|
747
748**Example**
749
750```
751let tcp = socket.constructTCPSocketInstance();
752let promise = tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1});
753promise.then(() => {
754  console.log('bind success');
755}).catch(err => {
756  console.log('bind fail');
757});
758```
759
760
761### connect
762
763connect\(options: TCPConnectOptions, callback: AsyncCallback<void\>\): void
764
765Sets up a connection to the specified IP address and port number. This API uses an asynchronous callback to return the result.
766
767**Required permission**: ohos.permission.INTERNET
768
769**System capability**: SystemCapability.Communication.NetStack
770
771**Parameters**
772
773| Name  | Type                                    | Mandatory| Description                                                        |
774| -------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
775| options  | [TCPConnectOptions](#tcpconnectoptions) | Yes  | TCPSocket connection parameters. For details, see [TCPConnectOptions](#tcpconnectoptions).|
776| callback | AsyncCallback\<void\>                    | Yes  | Callback used to return the result.                                                  |
777
778**Example**
779
780```
781let tcp = socket.constructTCPSocketInstance();
782tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}, err => {
783  if (err) {
784	console.log('connect fail');
785	return;
786  }
787  console.log('connect success');
788})
789```
790
791
792### connect
793
794connect\(options: TCPConnectOptions\): Promise<void\>
795
796Sets up a connection to the specified IP address and port number. This API uses a promise to return the result.
797
798**Required permission**: ohos.permission.INTERNET
799
800**System capability**: SystemCapability.Communication.NetStack
801
802**Parameters**
803
804| Name | Type                                    | Mandatory| Description                                                        |
805| ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
806| options | [TCPConnectOptions](#tcpconnectoptions) | Yes  | TCPSocket connection parameters. For details, see [TCPConnectOptions](#tcpconnectoptions).|
807
808**Return Value**
809
810| Type           | Description                                                      |
811| :-------------- | :--------------------------------------------------------- |
812| Promise\<void\> | Promise used to return the result.|
813
814**Example**
815
816```
817let tcp = socket.constructTCPSocketInstance();
818let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000});
819promise.then(() => {
820  console.log('connect success')
821}).catch(err => {
822  console.log('connect fail');
823});
824```
825
826
827### send
828
829send\(options: TCPSendOptions, callback: AsyncCallback<void\>\): void
830
831Sends data over a TCPSocket connection. This API uses an asynchronous callback to return the result.
832
833>![](public_sys-resources/icon-note.gif) **NOTE:**
834>This API can be called only after [connect](#connect) is successfully called.
835
836**Required permission**: ohos.permission.INTERNET
837
838**System capability**: SystemCapability.Communication.NetStack
839
840**Parameters**
841
842| Name  | Type                                   | Mandatory| Description                                                        |
843| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
844| options  | [TCPSendOptions](#tcpsendoptions) | Yes  | Parameters for sending data over the TCPSocket connection. For details, see [TCPSendOptions](#tcpsendoptions).|
845| callback | AsyncCallback\<void\>                   | Yes  | Callback used to return the result.                                                  |
846
847**Example**
848
849```
850let tcp = socket.constructTCPSocketInstance();
851let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000});
852promise.then(() => {
853  console.log('connect success');
854  tcp.send({
855	data:'Hello, server!'
856  },err => {
857	if (err) {
858	  console.log('send fail');
859	  return;
860	}
861	console.log('send success');
862  })
863}).catch(err => {
864  console.log('connect fail');
865});
866```
867
868
869### send
870
871send\(options: TCPSendOptions\): Promise<void\>
872
873Sends data over a TCPSocket connection. This API uses a promise to return the result.
874
875>![](public_sys-resources/icon-note.gif) **NOTE:**
876>This API can be called only after [connect](#connect) is successfully called.
877
878**Required permission**: ohos.permission.INTERNET
879
880**System capability**: SystemCapability.Communication.NetStack
881
882**Parameters**
883
884| Name | Type                                   | Mandatory| Description                                                        |
885| ------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
886| options | [TCPSendOptions](#tcpsendoptions) | Yes  | Parameters for sending data over the TCPSocket connection. For details, see [TCPSendOptions](#tcpsendoptions).|
887
888**Return Value**
889
890| Type           | Description                                              |
891| :-------------- | :------------------------------------------------- |
892| Promise\<void\> | Promise used to return the result.|
893
894**Example**
895
896```
897let tcp = socket.constructTCPSocketInstance();
898let promise1 = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000});
899promise1.then(() => {
900  console.log('connect success');
901  let promise2 = tcp.send({
902	data:'Hello, server!'
903  });
904  promise2.then(() => {
905	console.log('send success');
906  }).catch(err => {
907	console.log('send fail');
908  });
909}).catch(err => {
910  console.log('connect fail');
911});
912```
913
914
915### close
916
917close\(callback: AsyncCallback<void\>\): void
918
919Closes a TCPSocket connection. This API uses an asynchronous callback to return the result.
920
921**Required permission**: ohos.permission.INTERNET
922
923**System capability**: SystemCapability.Communication.NetStack
924
925**Parameters**
926
927| Name  | Type                 | Mandatory| Description      |
928| -------- | --------------------- | ---- | ---------- |
929| callback | AsyncCallback\<void\> | Yes  | Callback used to return the result.|
930
931
932**Example**
933
934```
935let tcp = socket.constructTCPSocketInstance();
936tcp.close(err => {
937  if (err) {
938	console.log('close fail');
939	return;
940  }
941  console.log('close success');
942})
943```
944
945
946### close
947
948close\(\): Promise<void\>
949
950Closes a TCPSocket connection. This API uses a promise to return the result.
951
952**Required permission**: ohos.permission.INTERNET
953
954**System capability**: SystemCapability.Communication.NetStack
955
956**Return Value**
957
958| Type           | Description                                      |
959| :-------------- | :----------------------------------------- |
960| Promise\<void\> | Promise used to return the result.|
961
962**Example**
963
964```
965let tcp = socket.constructTCPSocketInstance();
966let promise = tcp.close();
967promise.then(() => {
968  console.log('close success');
969}).catch(err => {
970  console.log('close fail');
971});
972```
973
974
975### getRemoteAddress
976
977getRemoteAddress\(callback: AsyncCallback<NetAddress\>\): void
978
979Obtains the remote address of a TCPSocket connection. This API uses an asynchronous callback to return the result.
980
981>![](public_sys-resources/icon-note.gif) **NOTE:**
982>This API can be called only after [connect](#connect) is successfully called.
983
984**Required permission**: ohos.permission.INTERNET
985
986**System capability**: SystemCapability.Communication.NetStack
987
988**Parameters**
989
990| Name  | Type                                             | Mandatory| Description      |
991| -------- | ------------------------------------------------- | ---- | ---------- |
992| callback | AsyncCallback<[NetAddress](#netaddress)> | Yes  | Callback used to return the result.|
993
994**Example**
995
996```
997let tcp = socket.constructTCPSocketInstance();
998let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000});
999promise.then(() => {
1000  console.log('connect success');
1001  tcp.getRemoteAddress((err, data) => {
1002	if (err) {
1003	  console.log('getRemoteAddressfail');
1004	  return;
1005	}
1006	console.log('getRemoteAddresssuccess:' + JSON.stringify(data));
1007  })
1008}).catch(err => {
1009  console.log('connect fail');
1010});
1011```
1012
1013
1014### getRemoteAddress
1015
1016getRemoteAddress\(\): Promise<NetAddress\>
1017
1018Obtains the remote address of a TCPSocket connection. This API uses a promise to return the result.
1019
1020>![](public_sys-resources/icon-note.gif) **NOTE:**
1021>This API can be called only after [connect](#connect) is successfully called.
1022
1023**Required permission**: ohos.permission.INTERNET
1024
1025**System capability**: SystemCapability.Communication.NetStack
1026
1027**Return Value**
1028
1029| Type                                       | Description                                       |
1030| :------------------------------------------ | :------------------------------------------ |
1031| Promise<[NetAddress](#netaddress)> | Promise used to return the result.|
1032
1033**Example**
1034
1035```
1036let tcp = socket.constructTCPSocketInstance();
1037let promise1 = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000});
1038promise1.then(() => {
1039  console.log('connect success');
1040  let promise2 = tcp.getRemoteAddress();
1041  promise2.then(() => {
1042	console.log('getRemoteAddress success:' + JSON.stringify(data));
1043  }).catch(err => {
1044	console.log('getRemoteAddressfail');
1045  });
1046}).catch(err => {
1047  console.log('connect fail');
1048});
1049```
1050
1051
1052### getState
1053
1054getState\(callback: AsyncCallback<SocketStateBase\>\): void
1055
1056Obtains the status of the TCPSocket connection. This API uses an asynchronous callback to return the result.
1057
1058>![](public_sys-resources/icon-note.gif) **NOTE:**
1059>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called.
1060
1061**Required permission**: ohos.permission.INTERNET
1062
1063**System capability**: SystemCapability.Communication.NetStack
1064
1065**Parameters**
1066
1067| Name  | Type                                                  | Mandatory| Description      |
1068| -------- | ------------------------------------------------------ | ---- | ---------- |
1069| callback | AsyncCallback<[SocketStateBase](#socketstatebase)> | Yes  | Callback used to return the result.|
1070
1071
1072**Example**
1073
1074```
1075let tcp = socket.constructTCPSocketInstance();
1076let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000});
1077promise.then(() => {
1078  console.log('connect success');
1079  tcp.getState((err, data) => {
1080	if (err) {
1081	  console.log('getState fail');
1082	  return;
1083	}
1084	console.log('getState success:' + JSON.stringify(data));
1085  });
1086}).catch(err => {
1087  console.log('connect fail');
1088});
1089```
1090
1091
1092### getState
1093
1094getState\(\): Promise<SocketStateBase\>
1095
1096Obtains the status of the TCPSocket connection. This API uses a promise to return the result.
1097
1098>![](public_sys-resources/icon-note.gif) **NOTE:**
1099>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called.
1100
1101**Required permission**: ohos.permission.INTERNET
1102
1103**System capability**: SystemCapability.Communication.NetStack
1104
1105**Return Value**
1106
1107| Type                                            | Description                                      |
1108| :----------------------------------------------- | :----------------------------------------- |
1109| Promise<[SocketStateBase](#socketstatebase)> | Promise used to return the result.|
1110
1111
1112**Example**
1113
1114```
1115let tcp = socket.constructTCPSocketInstance();
1116let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000});
1117promise.then(() => {
1118  console.log('connect success');
1119  let promise1 = tcp.getState();
1120  promise1.then(() => {
1121	console.log('getState success:' + JSON.stringify(data));
1122  }).catch(err => {
1123	console.log('getState fail');
1124  });
1125}).catch(err => {
1126  console.log('connect fail');
1127});
1128```
1129
1130
1131### setExtraOptions
1132
1133setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback<void\>\): void
1134
1135Sets other properties of the TCPSocket connection. This API uses an asynchronous callback to return the result.
1136
1137>![](public_sys-resources/icon-note.gif) **NOTE:**
1138>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called.
1139
1140**Required permission**: ohos.permission.INTERNET
1141
1142**System capability**: SystemCapability.Communication.NetStack
1143
1144**Parameters**
1145
1146| Name  | Type                                     | Mandatory| Description                                                        |
1147| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
1148| options  | [TCPExtraOptions](#tcpextraoptions) | Yes  | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).|
1149| callback | AsyncCallback\<void\>                     | Yes  | Callback used to return the result.                                                  |
1150
1151**Example**
1152
1153```
1154let tcp = socket.constructTCPSocketInstance();
1155let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000});
1156promise.then(() => {
1157  console.log('connect success');
1158  tcp.setExtraOptions({
1159	keepAlive: true,
1160	OOBInline: true,
1161	TCPNoDelay: true,
1162	socketLinger: { on:true, linger:10 },
1163	receiveBufferSize: 1000,
1164	sendBufferSize: 1000,
1165	reuseAddress: true,
1166	socketTimeout: 3000,
1167  },err => {
1168	if (err) {
1169	  console.log('setExtraOptions fail');
1170	  return;
1171	}
1172	console.log('setExtraOptions success');
1173  });
1174}).catch(err => {
1175  console.log('connect fail');
1176});
1177```
1178
1179
1180### setExtraOptions
1181
1182setExtraOptions\(options: TCPExtraOptions\): Promise<void\>
1183
1184Sets other properties of the TCPSocket connection. This API uses a promise to return the result.
1185
1186>![](public_sys-resources/icon-note.gif) **NOTE:**
1187>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called.
1188
1189**Required permission**: ohos.permission.INTERNET
1190
1191**System capability**: SystemCapability.Communication.NetStack
1192
1193**Parameters**
1194
1195| Name | Type                                     | Mandatory| Description                                                        |
1196| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
1197| options | [TCPExtraOptions](#tcpextraoptions) | Yes  | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).|
1198
1199**Return Value**
1200
1201| Type           | Description                                                |
1202| :-------------- | :--------------------------------------------------- |
1203| Promise\<void\> | Promise used to return the result.|
1204
1205
1206**Example**
1207
1208```
1209let tcp = socket.constructTCPSocketInstance();
1210let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000});
1211promise.then(() => {
1212  console.log('connect success');
1213  let promise1 = tcp.setExtraOptions({
1214	keepAlive: true,
1215	OOBInline: true,
1216	TCPNoDelay: true,
1217	socketLinger: { on:true, linger:10 },
1218	receiveBufferSize: 1000,
1219	sendBufferSize: 1000,
1220	reuseAddress: true,
1221	socketTimeout: 3000,
1222  });
1223  promise1.then(() => {
1224	console.log('setExtraOptions success');
1225  }).catch(err => {
1226	console.log('setExtraOptions fail');
1227  });
1228}).catch(err => {
1229  console.log('connect fail');
1230});
1231```
1232
1233
1234### on\('message'\)
1235
1236on\(type: 'message', callback: Callback<\{message: ArrayBuffer, remoteInfo: SocketRemoteInfo\}\>\): void
1237
1238Enables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
1239
1240**System capability**: SystemCapability.Communication.NetStack
1241
1242**Parameters**
1243
1244| Name  | Type                                                        | Mandatory| Description                                     |
1245| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
1246| type     | string                                                       | Yes  | Event type. <br />**message**: message receiving event|
1247| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | Yes  | Callback used to return the result.                               |
1248
1249**Example**
1250
1251```
1252let tcp = socket.constructTCPSocketInstance();
1253tcp.on('message', value => {
1254	console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo)
1255});
1256```
1257
1258
1259### off\('message'\)
1260
1261off\(type: 'message', callback?: Callback<\{message: ArrayBuffer, remoteInfo: SocketRemoteInfo\}\>\): void
1262
1263Disables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
1264
1265>![](public_sys-resources/icon-note.gif) **NOTE:**
1266>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.
1267
1268**System capability**: SystemCapability.Communication.NetStack
1269
1270**Parameters**
1271
1272| Name  | Type                                                        | Mandatory| Description                                     |
1273| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
1274| type     | string                                                       | Yes  | Event type. <br />**message**: message receiving event|
1275| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No  | Callback used to return the result.                               |
1276
1277**Example**
1278
1279```
1280let tcp = socket.constructTCPSocketInstance();
1281let callback = value =>{
1282	console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
1283}
1284tcp.on('message', callback);
1285// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
1286tcp.off('message', callback);
1287tcp.off('message');
1288```
1289
1290
1291### on\('connect' | 'close'\)
1292
1293on\(type: 'connect' | 'close', callback: Callback<void\>\): void
1294
1295Enables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
1296
1297**System capability**: SystemCapability.Communication.NetStack
1298
1299**Parameters**
1300
1301| Name  | Type            | Mandatory| Description                                                        |
1302| -------- | ---------------- | ---- | ------------------------------------------------------------ |
1303| type     | string           | Yes  | Event type.<br>- **connect**: connection event<br>- **close**: close event|
1304| callback | Callback\<void\> | Yes  | Callback used to return the result.                                                  |
1305
1306
1307**Example**
1308
1309```
1310let tcp = socket.constructTCPSocketInstance();
1311tcp.on('connect', () => {
1312	console.log("on connect success")
1313});
1314tcp.on('close', data => {
1315	console.log("on close success")
1316});
1317```
1318
1319
1320### off\('connect' | 'close'\)
1321
1322off\(type: 'connect' | 'close', callback?: Callback<void\>\): void
1323
1324Disables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
1325
1326>![](public_sys-resources/icon-note.gif) **NOTE:**
1327>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.
1328
1329**System capability**: SystemCapability.Communication.NetStack
1330
1331**Parameters**
1332
1333| Name  | Type            | Mandatory| Description                                                        |
1334| -------- | ---------------- | ---- | ------------------------------------------------------------ |
1335| type     | string           | Yes  | Event type.<br>- **connect**: connection event<br>- **close**: close event|
1336| callback | Callback\<void\> | No  | Callback used to return the result.                                                  |
1337
1338**Example**
1339
1340```
1341let tcp = socket.constructTCPSocketInstance();
1342let callback1 = () =>{
1343	console.log("on connect success");
1344}
1345tcp.on('connect', callback1);
1346// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
1347tcp.off('connect', callback1);
1348tcp.off('connect');
1349let callback2 = () =>{
1350	console.log("on close success");
1351}
1352tcp.on('close', callback2);
1353// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
1354tcp.off('close', callback2);
1355tcp.off('close');
1356```
1357
1358
1359### on\('error'\)
1360
1361on\(type: 'error', callback: ErrorCallback\): void
1362
1363Enables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
1364
1365**System capability**: SystemCapability.Communication.NetStack
1366
1367**Parameters**
1368
1369| Name  | Type         | Mandatory| Description                                |
1370| -------- | ------------- | ---- | ------------------------------------ |
1371| type     | string        | Yes  | Event type. <br />**error**: error event|
1372| callback | ErrorCallback | Yes  | Callback used to return the result.                          |
1373
1374**Example**
1375
1376```
1377let tcp = socket.constructTCPSocketInstance();
1378tcp.on('error', err => {
1379	console.log("on error, err:" + JSON.stringify(err))
1380});
1381```
1382
1383
1384### off\('error'\)
1385
1386off\(type: 'error', callback?: ErrorCallback\): void
1387
1388Disables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
1389
1390>![](public_sys-resources/icon-note.gif) **NOTE:**
1391>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.
1392
1393**System capability**: SystemCapability.Communication.NetStack
1394
1395**Parameters**
1396
1397| Name  | Type         | Mandatory| Description                                |
1398| -------- | ------------- | ---- | ------------------------------------ |
1399| type     | string        | Yes  | Event type. <br />**error**: error event|
1400| callback | ErrorCallback | No  | Callback used to return the result.                          |
1401
1402**Example**
1403
1404```
1405let tcp = socket.constructTCPSocketInstance();
1406let callback = err =>{
1407	console.log("on error, err:" + JSON.stringify(err));
1408}
1409tcp.on('error', callback);
1410// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
1411tcp.off('error', callback);
1412tcp.off('error');
1413```
1414
1415
1416## TCPConnectOptions
1417
1418Defines TCPSocket connection parameters.
1419
1420**System capability**: SystemCapability.Communication.NetStack
1421
1422| Name | Type                              | Mandatory| Description                      |
1423| ------- | ---------------------------------- | ---- | -------------------------- |
1424| address | [NetAddress](#netaddress) | Yes  | Bound IP address and port number.      |
1425| timeout | number                             | No  | Timeout duration of the TCPSocket connection, in ms.|
1426
1427## TCPSendOptions
1428
1429Defines the parameters for sending data over the TCPSocket connection.
1430
1431**System capability**: SystemCapability.Communication.NetStack
1432
1433| Name  | Type  | Mandatory| Description                                                        |
1434| -------- | ------ | ---- | ------------------------------------------------------------ |
1435| data     | string | Yes  | Data to send.                                                |
1436| 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**.|
1437
1438## TCPExtraOptions
1439
1440Defines other properties of the TCPSocket connection.
1441
1442**System capability**: SystemCapability.Communication.NetStack
1443
1444| Name           | Type   | Mandatory| Description                                                        |
1445| ----------------- | ------- | ---- | ------------------------------------------------------------ |
1446| keepAlive         | boolean | No  | Whether to keep the connection alive. The default value is **false**.                                 |
1447| OOBInline         | boolean | No  | Whether to enable OOBInline. The default value is **false**.                                |
1448| TCPNoDelay        | boolean | No  | Whether to enable no-delay on the TCPSocket connection. The default value is **false**.                      |
1449| 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**.|
1450| receiveBufferSize | number  | No  | Size of the receive buffer, in bytes.                              |
1451| sendBufferSize    | number  | No  | Size of the send buffer, in bytes.                              |
1452| reuseAddress      | boolean | No  | Whether to reuse addresses. The default value is **false**.                                 |
1453| socketTimeout     | number  | No  | Timeout duration of the TCPSocket connection, in ms.                            |
1454