• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Socket Connection
2
3## Overview
4
5The Socket Connection module allows an application to transmit data over a socket connection through the TCP, UDP, Multicast, or TLS protocol.
6
7## Basic Concepts
8
9- Socket: An abstraction of endpoints for bidirectional communication between application processes running on different hosts in a network.
10- TCP: Transmission Control Protocol, which is a byte stream–based transport layer communication protocol that is connection-oriented and reliable.
11- UDP: User Datagram Protocol, which is a simple datagram-oriented transport layer communication protocol.
12- Multicast: A UDP-based communication mode that implements broadcast communication between all devices in a group.
13- LocalSocket: An inter-process communication (IPC) mechanism that implements communication between processes on a device without using a network.
14- TLS: Transport Layer Security, which is a protocol that ensures the data confidentiality and integrity between communication programs.
15
16## When to Use
17
18Applications transmit data over TCP, UDP, Multicast, or TLS socket connections. The main application scenarios are as follows:
19
20- Implementing data transmission over TCP socket or UDP socket connections
21- Implementing data transmission over TCP socket server connections
22- Implementing data transmission over multicast socket connections
23- Implementing data transmission over local socket connections
24- Implementing data transmission over local socket server connections
25- Implementing encrypted data transmission over TLS socket connections
26- Implementing encrypted data transmission over TLS socket server connections
27
28## Available APIs
29
30For the complete list of APIs and example code, see [Socket Connection](../reference/apis/js-apis-socket.md).
31
32Socket connection functions are mainly implemented by the **socket** module. The following table describes the related APIs.
33
34| API                            | Description                                                                         |
35| ---------------------------------- | ------------------------------------------------------------------------------ |
36| constructUDPSocketInstance()       | Creates a **UDPSocket** object.                                                     |
37| constructTCPSocketInstance()       | Creates a **TCPSocket** object.                                                     |
38| constructTCPSocketServerInstance() | Creates a **TCPSocketServer** object.                                               |
39| constructMulticastSocketInstance() | Creates a **MulticastSocket** object.                                               |
40| constructLocalSocketInstance()       | Creates a **LocalSocket** object.                                                 |
41| constructLocalSocketServerInstance() | Creates a **LocalSocketServer** object.                                           |
42| listen()                           | Subscribes to **connect** events from the client. This API is supported only for TCP and local socket connections.            |
43| bind()                             | Binds an IP address to a port, or binds the address of a local socket.                                       |
44| send()                             | Sends data.                                                                    |
45| close()                            | Closes a socket connection.                                                                    |
46| getState()                         | Obtains the status of a socket connection.                                                            |
47| connect()                          | Connects to the specified IP address and port, or connects to a local socket. This API is supported only for TCP and local socket connections.         |
48| getRemoteAddress()                 | Obtains the peer address of the socket connection. This function is supported only for TCP. The **connect** API must have been called before you use this API.                  |
49| setExtraOptions()                  | Sets other properties of the socket connection.                                                  |
50| getExtraOptions()                  | Obtains other properties of a socket connection. This API is supported only for local socket connections.                           |
51| addMembership()                    | Adds a member to the specified multicast group. This API is supported only for multicast socket connections.                                |
52| dropMembership()                   | Drops a member from the specified multicast group. This API is supported only for multicast socket connections.                                |
53| setMulticastTTL()                  | Sets the time to live (TTL) for multicast packets. This API is supported only for multicast socket connections.                                   |
54| getMulticastTTL()                  | Obtains the TTL for multicast packets. This API is supported only for multicast socket connections.                                   |
55| setLoopbackMode()                  | Sets the loopback mode flag for multicast communication. This API is supported only for multicast socket connections.      |
56| getLoopbackMode()                  | Obtains the loopback mode flag for multicast communication. This API is supported only for multicast socket connections.                              |
57| on(type: 'message')           | Subscribes to **message** events of a socket connection.                                              |
58| off(type: 'message')          | Unsubscribes from **message** events of a socket connection.                                          |
59| on(type: 'close')             | Subscribes to **close** events of a socket connection.                                                  |
60| off(type: 'close')            | Unsubscribes from **close** events of a socket connection.                                              |
61| on(type: 'error')             | Subscribes to **error** events of a socket connection.                                               |
62| off(type: 'error')            | Unsubscribes from **error** events of a socket connection.                                           |
63| on(type: 'listening')         | Subscribes to **listening** events of a socket connection. This API is supported only for UDP socket connections.                          |
64| off(type: 'listening')        | Unsubscribes from **listening** events of a socket connection. This API is supported only for UDP socket connections.                      |
65| on(type: 'connect')           | Subscribes to **message** events of a socket connection. This API is supported only for TCP and local socket connections.                           |
66| off(type: 'connect')          | Unsubscribes from **message** events of a socket connection. This API is supported only for TCP and local socket connections.                        |
67
68TLS socket connection functions are mainly provided by the **tls_socket** module. The following table describes the related APIs.
69
70| API                      | Description                                                  |
71| ---------------------------- | ---------------------------------------------------------- |
72| constructTLSSocketInstance() | Creates a **TLSSocket** object.                                 |
73| bind()                       | Binds the IP address and port number.                                    |
74| close(type: 'error')    | Closes a socket connection.                                                |
75| connect()                    | Sets up a connection to the specified IP address and port number.                              |
76| getCertificate()             | Obtains an object representing the local certificate.                                  |
77| getCipherSuite()             | Obtains a list containing information about the negotiated cipher suite.                        |
78| getProtocol()                | Obtains a string containing the SSL/TLS protocol version negotiated for the current connection.         |
79| getRemoteAddress()           | Obtains the peer address of the TLS socket connection.                           |
80| getRemoteCertificate()       | Obtains an object representing a peer certificate.                                  |
81| getSignatureAlgorithms()     | Obtains a list containing signature algorithms shared between the server and client, in descending order of priority.|
82| getState()                   | Obtains the status of a TLS socket connection.                               |
83| off(type: 'close')      | Unsubscribes from **close** events of a TLS socket connection.                       |
84| off(type: 'error')      | Unsubscribes from **error** events of a TLS socket connection.                    |
85| off(type: 'message')    | Unsubscribes from **message** events of a TLS socket connection.                   |
86| on(type: 'close')       | Subscribes to **close** events of a TLS socket connection.                           |
87| on(type: 'error')       | Subscribes to **error** events of a TLS socket connection.                        |
88| on(type: 'message')     | Subscribes to **message** events of a TLS socket connection.                       |
89| send()                       | Sends data.                                                |
90| setExtraOptions()            | Sets other properties of the TLS socket connection.                           |
91
92## Transmitting Data over TCP Socket or UDP Socket Connections
93
94The implementation is similar for UDP socket and TCP socket connections. The following uses data transmission over a TCP socket connection as an example.
95
961. Import the required **socket** module.
97
982. Create a TCP socket connection. A **TCPSocketConnction** object is returned.
99
1003. (Optional) Subscribe to events of the **TCPSocketConnction** object.
101
1024. Bind the IP address and port number. The port number can be specified or randomly allocated by the system.
103
1045. Set up a connection to the specified IP address and port number.
105
1066. Send data over the connection.
107
1087. Enable the TCP socket connection to be automatically closed after use.
109
110```ts
111import socket from '@ohos.net.socket';
112import { BusinessError } from '@ohos.base';
113
114class SocketInfo {
115  message: ArrayBuffer = new ArrayBuffer(1);
116  remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo;
117}
118// Create a TCP socket connection. A TCPSocket object is returned.
119let tcp = socket.constructTCPSocketInstance();
120tcp.on('message', (value: SocketInfo) => {
121  console.log("on message");
122  let buffer = value.message;
123  let dataView = new DataView(buffer);
124  let str = "";
125  for (let i = 0; i < dataView.byteLength; ++i) {
126    str += String.fromCharCode(dataView.getUint8(i));
127  }
128  console.log("on connect received:" + str);
129});
130tcp.on('connect', () => {
131  console.log("on connect");
132});
133tcp.on('close', () => {
134  console.log("on close");
135});
136
137// Bind the local IP address and port number.
138let ipAddress : socket.NetAddress = {} as socket.NetAddress;
139ipAddress.address = "192.168.xxx.xxx";
140ipAddress.port = 1234;
141tcp.bind(ipAddress, (err: BusinessError) => {
142  if (err) {
143    console.log('bind fail');
144    return;
145  }
146  console.log('bind success');
147
148  // Set up a connection to the specified IP address and port number.
149  ipAddress.address = "192.168.xxx.xxx";
150  ipAddress.port = 5678;
151
152  let tcpConnect : socket.TCPConnectOptions = {} as socket.TCPConnectOptions;
153  tcpConnect.address = ipAddress;
154  tcpConnect.timeout = 6000;
155
156  tcp.connect(tcpConnect, (err: BusinessError) => {
157    if (err) {
158      console.log('connect fail');
159      return;
160    }
161    console.log('connect success');
162    // Send data over the connection.
163    let tcpSendOptions : socket.TCPSendOptions = {} as socket.TCPSendOptions;
164    tcpSendOptions.data = 'Hello, server!';
165    tcp.send(tcpSendOptions, (err: BusinessError) => {
166      if (err) {
167        console.log('send fail');
168        return;
169      }
170      console.log('send success');
171    })
172  });
173});
174
175// Enable the socket connection to be automatically closed after use. Then, unsubscribe from events of the connection.
176setTimeout(() => {
177  tcp.close((err: BusinessError) => {
178    console.log('close socket.');
179  });
180  tcp.off('message');
181  tcp.off('connect');
182  tcp.off('close');
183}, 30 * 1000);
184```
185
186## Transmitting Data over TCP Socket Server Connections
187
188### How to Develop
189
190The TCP socket server connection process is described as follows:
191
1921. Import the required **socket** module.
1932. Create a TCP socket server connection. A **TCPSocketServer** object is returned.
1943. Bind the local IP address and port, and listen for and accept TCP socket connections established over the socket.
1954. Subscribe to **connect** events of the **TCPSocketServer** object to listen for client connection status changes.
1965. Set up a connection between the client and the server. A **TCPSocketConnection** object is returned.
1976. Subscribe to events of the **TCPSocketConnection** object, and send data to the client through the **TCPSocketConnection** object.
1987. Close the connection between the client and the server.
1998. Unsubscribe from events of the **TCPSocketConnection** and **TCPSocketServer** objects.
200
201```ts
202import socket from '@ohos.net.socket';
203import { BusinessError } from '@ohos.base';
204// Create a TCP socket server connection. A TCPSocketServer object is returned.
205let tcpServer = socket.constructTCPSocketServerInstance();
206// Bind the local IP address and port number for listening.
207
208let ipAddress : socket.NetAddress = {} as socket.NetAddress;
209ipAddress.address = "192.168.xxx.xxx";
210ipAddress.port = 4651;
211tcpServer.listen(ipAddress, (err: BusinessError) => {
212  if (err) {
213    console.log("listen fail");
214    return;
215  }
216  console.log("listen success");
217});
218
219class SocketInfo {
220  message: ArrayBuffer = new ArrayBuffer(1);
221  remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo;
222}
223// Subscribe to connect events of the TCPSocketServer object.
224tcpServer.on("connect", (client: socket.TCPSocketConnection) => {
225  // Subscribe to events of the TCPSocketConnection object.
226  client.on("close", () => {
227    console.log("on close success");
228  });
229  client.on("message", (value: SocketInfo) => {
230    let buffer = value.message;
231    let dataView = new DataView(buffer);
232    let str = "";
233    for (let i = 0; i < dataView.byteLength; ++i) {
234      str += String.fromCharCode(dataView.getUint8(i));
235    }
236    console.log("received message--:" + str);
237    console.log("received address--:" + value.remoteInfo.address);
238    console.log("received family--:" + value.remoteInfo.family);
239    console.log("received port--:" + value.remoteInfo.port);
240    console.log("received size--:" + value.remoteInfo.size);
241  });
242
243  // Send data to the client.
244  let tcpSendOptions : socket.TCPSendOptions = {} as socket.TCPSendOptions;
245  tcpSendOptions.data = 'Hello, client!';
246  client.send(tcpSendOptions, (err: BusinessError) => {
247    if (err) {
248      console.log("send fail");
249      return;
250    }
251    console.log("send success");
252  });
253
254  // Close the connection between the client and the server.
255  client.close((err: BusinessError) => {
256    if (err) {
257      console.log("close fail");
258      return;
259    }
260    console.log("close success");
261  });
262
263  // Unsubscribe from events of the TCPSocketConnection object.
264  setTimeout(() => {
265    client.off("message");
266    client.off("close");
267  }, 10 * 1000);
268});
269
270// Unsubscribe from events of the TCPSocketServer object.
271setTimeout(() => {
272  tcpServer.off("connect");
273}, 30 * 1000);
274```
275
276## Transmitting Data over Multicast Socket Connections
277
278### How to Develop
279
2801. Import the required **socket** module.
281
2822. Create a **MulticastSocket** object.
283
2843. Specify a **MulticastSocket** object by the IP address and port number, and add it to the multicast group.
285
2864. Subscribe to **message** events.
287
2885. Send data in broadcast mode. All **MulticastSocket** objects in the same multicast group for which **message** event listening has been enabled will receive the data.
289
2906. Unsubscribe from **message** events.
291
2927. Drop the **MulticastSocket** object from the multicast group.
293
294```ts
295import socket from '@ohos.net.socket'
296// Create a MulticastSocket object.
297let multicast = socket.constructMulticastSocketInstance();
298
299let addr : socket.NetAddress = {
300  address: '239.255.0.1',
301  port: 32123,
302  family: 1
303}
304
305// Add the MulticastSocket object to a multicast group.
306multicast.addMembership(addr, (err: Object) => {
307  if (err) {
308    console.info('add err: ' + JSON.stringify(err));
309    return;
310  }
311  console.info('add ok');
312})
313
314// Subscribe to message events and convert the received data of the ArrayBuffer type to strings.
315class SocketInfo {
316  message: ArrayBuffer = new ArrayBuffer(1);
317  remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo;
318}
319multicast.on('message', (data: SocketInfo) => {
320  console.info ('Received data:' + JSON.stringify (data))
321  const uintArray = new Uint8Array(data.message)
322  let str = ''
323  for (let i = 0; i < uintArray.length; ++i) {
324    str += String.fromCharCode(uintArray[i])
325  }
326  console.info(str)
327})
328
329// Send data over the connection.
330multicast.send({ data:'Hello12345', address: addr }, (err: Object) => {
331  if (err) {
332    console.info ('Sending failed:' + JSON.stringify (err));
333    return;
334  }
335  console.info('Sending success');
336})
337
338// Unsubscribe from message events.
339multicast.off('message')
340
341// Drop the MulticastSocket object from the multicast group.
342multicast.dropMembership(addr, (err: Object) => {
343  if (err) {
344    console.info('drop err ' + JSON.stringify(err));
345    return;
346  }
347  console.info('drop ok');
348})
349```
350
351## Transmitting Data over Local Socket Connections
352
353### How to Develop
354
3551. Import the required **socket** module.
356
3572. Call **constructLocalSocketInstance** to create a **LocalSocket** object.
358
3593. Subscribe to **message** events of the **LocalSocket** object and other events (optional).
360
3614. Connect to server based on the specified address of the local socket file.
362
3635. Send data over the connection.
364
3656. If the socket connection is no longer needed, unsubscribe from message events and close the connection.
366
367```ts
368import socket from '@ohos.net.socket';
369
370// Create a local socket connection. A LocalSocket object is returned.
371let client = socket.constructLocalSocketInstance();
372client.on('message', (value: socket.LocalSocketMessageInfo) => {
373  const uintArray = new Uint8Array(value.message)
374  let messageView = '';
375  for (let i = 0; i < uintArray.length; i++) {
376    messageView = String.fromCharCode(uintArray[i]);
377  }
378  console.log('total receive: ' + JSON.stringify(value));
379  console.log('message information: ' + messageView);
380});
381client.on('connect', () => {
382  console.log("on connect");
383});
384client.on('close', () => {
385  console.log("on close");
386});
387
388// Specify the address of local socket file to connect to the server.
389let connectOpt: socket.LocalConnectOptions = {
390  address: {
391    address: '/tmp/testSocket'
392  },
393  timeout: 6000
394}
395let sendOpt: socket.LocalSendOptions = {
396  data: 'Hello world!'
397}
398client.connect(connectOpt).then(() => {
399  console.log('connect success')
400  client.send(sendOpt).then(() => {
401  console.log('send success')
402  }).catch((err: Object) => {
403    console.log('send failed: ' + JSON.stringify(err))
404  })
405}).catch((err: Object) => {
406  console.log('connect fail: ' + JSON.stringify(err));
407});
408
409// If the socket connection is no longer needed, unsubscribe from message events and close the connection.
410client.off('message');
411client.off('connect');
412client.off('close');
413client.close().then(() => {
414  console.log('close client success')
415}).catch((err: Object) => {
416  console.log('close client err: ' + JSON.stringify(err))
417})
418```
419
420## Transmitting Data over Local Socket Server Connections
421
422### How to Develop
423
424The local socket connection process on the server is described as follows:
425
4261. Import the required **socket** module.
427
4282. Call **constructLocalSocketServerInstance** to create a **LocalSocketServer** object.
429
4303. Bind the address of the local socket file.
431
4324. Subscribe to **connect** events of the local socket client and other events (optional).
433
4345. When the local socket client is connected, obtain the **LocalSocketConnection** object through the callback of the **connect** event.
435
4366. Subscribe to **message** events of the **LocalSocketConnection** object and other events (optional).
437
4387. Send messages to the local socket client through the **LocalSocketConnection** object.
439
4408. When the communication ends, close the local socket connection.
441
4429. Unsubscribe from events of the **LocalSocketConnection** and **LocalSocketServer** objects.
443
444```ts
445import socket from '@ohos.net.socket';
446// Create a local socket server connection. A LocalSocketServer object is returned.
447let server = socket.constructLocalSocketServerInstance();
448// Bind the local IP address and port number for listening.
449let listenAddr: socket.LocalAddress = {
450  address: '/tmp/testSocket'
451}
452server.listen(listenAddr).then(() => {
453  console.log("listen success");
454}).catch((err: Object) => {
455  console.log("listen fail: " + JSON.stringify(err));
456});
457
458// Subscribe to connect events of the LocalSocketServer object.
459server.on("connect", (connection: socket.LocalSocketConnection) => {
460  // Subscribe to events of the LocalSocketConnection object.
461  connection.on("error", (err) => {
462    console.log("on error success");
463  });
464  connection.on('message', (value: socket.LocalSocketMessageInfo) => {
465    const uintArray = new Uint8Array(value.message);
466    let messageView = '';
467    for (let i = 0; i < uintArray.length; i++) {
468      messageView = String.fromCharCode(uintArray[i]);
469    }
470    console.log('total: ' + JSON.stringify(value));
471    console.log('message information: ' + messageView);
472  });
473
474  connection.on('error', (err) => {
475    console.log("err:" + JSON.stringify(err));
476  })
477
478  // Send data to the client.
479  let sendOpt : socket.LocalSendOptions = {
480    data: 'Hello world!'
481  };
482  connection.send(sendOpt).then(() => {
483    console.log('send success');
484  }).catch((err: Object) => {
485    console.log('send failed: ' + JSON.stringify(err));
486  })
487
488  // Close the connection between the client and the server.
489  connection.close().then(() => {
490    console.log('close success');
491  }).catch((err: Object) => {
492    console.log('close failed: ' + JSON.stringify(err));
493  });
494
495  // Unsubscribe from events of the LocalSocketConnection object.
496  connection.off('message');
497  connection.off('error');
498});
499
500// Unsubscribe from events of the LocalSocketServer object.
501server.off('connect');
502server.off('error');
503```
504
505## Implementing Encrypted Data Transmission over TLS Socket Connections
506
507### How to Develop
508
509The TLS socket connection process on the client is described as follows:
510
5111. Import the required **socket** module.
512
5132. Bind the IP address and port number of the server.
514
5153. For two-way authentication, upload the client CA certificate and digital certificate. For one-way authentication, upload the client CA certificate.
516
5174. Create a TLS socket connection. A **TLSSocketConnection** object is returned.
518
5195. (Optional) Subscribe to events of the **TLSSocketConnection** object.
520
5216. Send data over the connection.
522
5237. Enable the TLS socket connection to be automatically closed after use.
524
525```ts
526import socket from '@ohos.net.socket';
527import { BusinessError } from '@ohos.base';
528
529class SocketInfo {
530  message: ArrayBuffer = new ArrayBuffer(1);
531  remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo;
532}
533// Create a TLS socket connection (for two-way authentication). A TLSSocketConnection object is returned.
534let tlsTwoWay = socket.constructTLSSocketInstance();
535// Subscribe to events of the TLSSocketConnection object.
536tlsTwoWay.on('message', (value: SocketInfo) => {
537  console.log("on message");
538  let buffer = value.message;
539  let dataView = new DataView(buffer);
540  let str = "";
541  for (let i = 0; i < dataView.byteLength; ++i) {
542    str += String.fromCharCode(dataView.getUint8(i));
543  }
544  console.log("on connect received:" + str);
545});
546tlsTwoWay.on('connect', () => {
547  console.log("on connect");
548});
549tlsTwoWay.on('close', () => {
550  console.log("on close");
551});
552
553// Bind the local IP address and port number.
554let ipAddress : socket.NetAddress = {} as socket.NetAddress;
555ipAddress.address = "192.168.xxx.xxx";
556ipAddress.port = 4512;
557tlsTwoWay.bind(ipAddress, (err: BusinessError) => {
558  if (err) {
559    console.log('bind fail');
560    return;
561  }
562  console.log('bind success');
563});
564
565ipAddress.address = "192.168.xxx.xxx";
566ipAddress.port = 1234;
567
568let tlsSecureOption : socket.TLSSecureOptions = {} as socket.TLSSecureOptions;
569tlsSecureOption.key = "xxxx";
570tlsSecureOption.cert = "xxxx";
571tlsSecureOption.ca = ["xxxx"];
572tlsSecureOption.password = "xxxx";
573tlsSecureOption.protocols = [socket.Protocol.TLSv12];
574tlsSecureOption.useRemoteCipherPrefer = true;
575tlsSecureOption.signatureAlgorithms = "rsa_pss_rsae_sha256:ECDSA+SHA256";
576tlsSecureOption.cipherSuite = "AES256-SHA256";
577
578let tlsTwoWayConnectOption : socket.TLSConnectOptions = {} as socket.TLSConnectOptions;
579tlsSecureOption.key = "xxxx";
580tlsTwoWayConnectOption.address = ipAddress;
581tlsTwoWayConnectOption.secureOptions = tlsSecureOption;
582tlsTwoWayConnectOption.ALPNProtocols = ["spdy/1", "http/1.1"];
583
584// Set up a connection.
585tlsTwoWay.connect(tlsTwoWayConnectOption, () => {
586  console.error("connect function");
587});
588
589// Enable the socket connection to be automatically closed after use. Then, unsubscribe from events of the connection.
590tlsTwoWay.close((err: BusinessError) => {
591  if (err) {
592    console.log("close callback error = " + err);
593  } else {
594    console.log("close success");
595  }
596  tlsTwoWay.off('message');
597  tlsTwoWay.off('connect');
598  tlsTwoWay.off('close');
599});
600
601// Create a TLS socket connection (for one-way authentication). A TLSSocketConnection object is returned.
602let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
603
604// Subscribe to events of the TLSSocketConnection object.
605tlsTwoWay.on('message', (value: SocketInfo) => {
606  console.log("on message");
607  let buffer = value.message;
608  let dataView = new DataView(buffer);
609  let str = "";
610  for (let i = 0; i < dataView.byteLength; ++i) {
611    str += String.fromCharCode(dataView.getUint8(i));
612  }
613  console.log("on connect received:" + str);
614});
615tlsTwoWay.on('connect', () => {
616  console.log("on connect");
617});
618tlsTwoWay.on('close', () => {
619  console.log("on close");
620});
621
622// Bind the local IP address and port number.
623ipAddress.address = "192.168.xxx.xxx";
624ipAddress.port = 5445;
625tlsOneWay.bind(ipAddress, (err:BusinessError) => {
626  if (err) {
627    console.log('bind fail');
628    return;
629  }
630  console.log('bind success');
631});
632
633ipAddress.address = "192.168.xxx.xxx";
634ipAddress.port = 8789;
635let tlsOneWaySecureOption : socket.TLSSecureOptions = {} as socket.TLSSecureOptions;
636tlsOneWaySecureOption.ca = ["xxxx", "xxxx"];
637tlsOneWaySecureOption.cipherSuite = "AES256-SHA256";
638
639let tlsOneWayConnectOptions: socket.TLSConnectOptions = {} as socket.TLSConnectOptions;
640tlsOneWayConnectOptions.address = ipAddress;
641tlsOneWayConnectOptions.secureOptions = tlsOneWaySecureOption;
642
643// Set up a connection.
644tlsOneWay.connect(tlsOneWayConnectOptions, () => {
645  console.error("connect function");
646});
647
648// Enable the socket connection to be automatically closed after use. Then, unsubscribe from events of the connection.
649tlsTwoWay.close((err: BusinessError) => {
650  if (err) {
651    console.log("close callback error = " + err);
652  } else {
653    console.log("close success");
654  }
655  tlsTwoWay.off('message');
656  tlsTwoWay.off('connect');
657  tlsTwoWay.off('close');
658});
659```
660
661## Implementing Encrypted Data Transmission over TLS Socket Server Connections
662
663### How to Develop
664
665The TLS socket connection process on the server is described as follows:
666
6671. Import the required **socket** module.
668
6692. Start the service and bind the IP address and port number to set up a TLS socket connection. Then, create and initialize a TLS session, and load and verify the certificate key.
670
6713. Subscribe to **connect** events of the **TLSSocketServer** object.
672
6734. Obtain a **TLSSocketConnection** object through the callback when the client initiates a TLS socket connection.
674
6755. Subscribe to events of the **TLSSocketConnection** object.
676
6776. Send data over the connection.
678
6797. Close the TLS socket connection if it is no longer needed.
680
6818. Unsubscribe from events of the **TLSSocketConnection** and **TLSSocketServer** objects.
682
683```ts
684import socket from "@ohos.net.socket";
685import { BusinessError } from '@ohos.base';
686let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance();
687let tlsConnectOptions: socket.TLSConnectOptions = {
688  address: {
689    address: '192.168.xx.xxx',
690    port: 8080
691  },
692  secureOptions: {
693    key: "xxxx",
694    cert: "xxxx",
695    ca: ["xxxx"],
696    password: "xxxx",
697    protocols: socket.Protocol.TLSv12,
698    useRemoteCipherPrefer: true,
699    signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
700    cipherSuite: "AES256-SHA256"
701  },
702  ALPNProtocols: ["spdy/1", "http/1.1"]
703}
704tlsServer.listen(tlsConnectOptions).then(() => {
705  console.log("listen callback success");
706}).catch((err: BusinessError) => {
707  console.log("failed" + err);
708});
709
710class SocketInfo {
711  message: ArrayBuffer = new ArrayBuffer(1);
712  remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo;
713}
714let callback = (value: SocketInfo) => {
715  let messageView = '';
716  for (let i: number = 0; i < value.message.byteLength; i++) {
717    let uint8Array = new Uint8Array(value.message)
718    let messages = uint8Array[i]
719    let message = String.fromCharCode(messages);
720    messageView += message;
721  }
722  console.log('on message message: ' + JSON.stringify(messageView));
723  console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo));
724}
725tlsServer.on('connect', (client: socket.TLSSocketConnection) => {
726  client.on('message', callback);
727
728  // Send data over the connection.
729  client.send('Hello, client!').then(() => {
730    console.log('send success');
731  }).catch((err: BusinessError) => {
732    console.log('send fail');
733  });
734
735  // Close the connection.
736  client.close().then(() => {
737    console.log('close success');
738  }).catch((err: BusinessError) => {
739    console.log('close fail');
740  });
741
742  // You can pass the callback of the on function if you want to unsubscribe from a certain type of events. If you do not pass the callback, you will unsubscribe from all events.
743  client.off('message', callback);
744  client.off('message');
745});
746
747// Unsubscribe from events of the TLSSocketServer object.
748tlsServer.off('connect');
749```
750