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