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> **NOTE** 8> 9> After an application is switched from the background to the foreground, it will attempt to resume network communication. If the attempt fails, an error is thrown and a new TCP/UDP connection object is created. 10 11## Basic Concepts 12 13- Socket: An abstraction of endpoints for bidirectional communication between application processes running on different hosts in a network. 14- TCP: Transmission Control Protocol, which is a byte stream–based transport layer communication protocol that is connection-oriented and reliable. 15- UDP: User Datagram Protocol, which is a simple datagram-oriented transport layer communication protocol. 16- Multicast: A UDP-based communication mode that implements broadcast communication between all devices in a group. 17- LocalSocket: An inter-process communication (IPC) mechanism that implements communication between processes on a device without using a network. 18- TLS: Transport Layer Security, which is a protocol that ensures the data confidentiality and integrity between communication programs. 19 20## When to Use 21 22Applications can transmit data over TCP, UDP, Multicast, or TLS socket connections. The main application scenarios include: 23 24- Implementing data transmission over TCP/UDP socket connections 25- Implementing data transmission over TCP socket server connections 26- Implementing data transmission over multicast socket connections 27- Implementing data transmission over local socket connections 28- Implementing data transmission over local socket server connections 29- Implementing encrypted data transmission over TLS socket connections 30- Implementing encrypted data transmission over TLS socket server connections 31 32## Available APIs 33 34For the complete list of APIs and example code, see [Socket Connection](../reference/apis-network-kit/js-apis-socket.md). 35 36Socket connection functions are mainly implemented by the **socket** module. The following table describes the related APIs. 37 38| API | Description | 39| ---------------------------------- | ------------------------------------------------------------------------------ | 40| constructUDPSocketInstance() | Creates a **UDPSocket** object. | 41| constructTCPSocketInstance() | Creates a **TCPSocket** object. | 42| constructTCPSocketServerInstance() | Creates a **TCPSocketServer** object. | 43| constructMulticastSocketInstance() | Creates a **MulticastSocket** object. | 44| constructLocalSocketInstance() | Creates a **LocalSocket** object. | 45| constructLocalSocketServerInstance() | Creates a **LocalSocketServer** object. | 46| listen() | Subscribes to **connect** events from the client. This API is supported only for TCP and local socket connections. | 47| bind() | Binds the IP address and port, or binds the local socket path. | 48| send() | Sends data. | 49| close() | Closes a socket connection. | 50| getState() | Obtains the status of a socket connection. | 51| connect() | Connects to the specified IP address and port, or connects to the local socket. (This API is supported only for TCP and local socket connections.) | 52| 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. | 53| setExtraOptions() | Sets other properties of the socket connection. | 54| getExtraOptions() | Obtains other properties of a socket connection. This API is supported only for local socket connections. | 55| addMembership() | Adds a member to the specified multicast group. This API is supported only for multicast socket connections. | 56| dropMembership() | Drops a member from the specified multicast group. This API is supported only for multicast socket connections. | 57| setMulticastTTL() | Sets the time to live (TTL) for multicast packets. This API is supported only for multicast socket connections. | 58| getMulticastTTL() | Obtains the TTL for multicast packets. This API is supported only for multicast socket connections. | 59| setLoopbackMode() | Sets the loopback mode flag for multicast communication. This API is supported only for multicast socket connections. | 60| getLoopbackMode() | Obtains the loopback mode flag for multicast communication. This API is supported only for multicast socket connections. | 61| on(type: 'message') | Subscribes to **message** events of a socket connection. | 62| off(type: 'message') | Unsubscribes from **message** events of a socket connection. | 63| on(type: 'close') | Subscribes to **close** events of a socket connection. | 64| off(type: 'close') | Unsubscribes from **close** events of a socket connection. | 65| on(type: 'error') | Subscribes to **error** events of a socket connection. | 66| off(type: 'error') | Unsubscribes from **error** events of a socket connection. | 67| on(type: 'listening') | Subscribes to **listening** events of a socket connection. This API is supported only for UDP socket connections. | 68| off(type: 'listening') | Unsubscribes from **listening** events of a socket connection. This API is supported only for UDP socket connections. | 69| on(type: 'connect') | Subscribes to **message** events of a socket connection. This API is supported only for TCP and local socket connections. | 70| off(type: 'connect') | Unsubscribes from **message** events of a socket connection. This API is supported only for TCP and local socket connections. | 71 72TLS socket connection functions are mainly provided by the **socket** module. The following table describes the related APIs. 73 74| API | Description | 75| ---------------------------- | ---------------------------------------------------------- | 76| constructTLSSocketInstance() | Creates a **TLSSocket** object. | 77| bind() | Binds the IP address and port number. | 78| close(type: 'error') | Closes a socket connection. | 79| connect() | Sets up a connection to the specified IP address and port number. | 80| getCertificate() | Obtains an object representing the local certificate. | 81| getCipherSuite() | Obtains a list containing information about the negotiated cipher suite. | 82| getProtocol() | Obtains a string containing the SSL/TLS protocol version negotiated for the current connection. | 83| getRemoteAddress() | Obtains the peer address of the TLS socket connection. | 84| getRemoteCertificate() | Obtains an object representing a peer certificate. | 85| getSignatureAlgorithms() | Obtains a list containing signature algorithms shared between the server and client, in descending order of priority.| 86| getState() | Obtains the status of a TLS socket connection. | 87| off(type: 'close') | Unsubscribes from **close** events of a TLS socket connection. | 88| off(type: 'error') | Unsubscribes from **error** events of a TLS socket connection. | 89| off(type: 'message') | Unsubscribes from **message** events of a TLS socket connection. | 90| on(type: 'close') | Subscribes to **close** events of a TLS socket connection. | 91| on(type: 'error') | Subscribes to **error** events of a TLS socket connection. | 92| on(type: 'message') | Subscribes to **message** events of a TLS socket connection. | 93| send() | Sends data. | 94| setExtraOptions() | Sets other properties of the TLS socket connection. | 95 96## Transmitting Data over TCP Socket or UDP Socket Connections 97 98The implementation is similar for UDP socket and TCP socket connections. The following uses data transmission over a TCP socket connection as an example. 99 1001. Import the required socket module. 101 1022. Create a TCP socket connection. A **TCPSocket** object is returned. 103 1043. (Optional) Subscribe to TCP socket connection events. 105 1064. Bind the IP address and port number. The port number can be specified or randomly allocated by the system. 107 1085. Set up a connection to the specified IP address and port number. 109 1106. Send data over the connection. 111 1127. Enable the TCP socket connection to be automatically closed after use. 113 114```ts 115import { socket } from '@kit.NetworkKit'; 116import { BusinessError } from '@kit.BasicServicesKit'; 117 118class SocketInfo { 119 message: ArrayBuffer = new ArrayBuffer(1); 120 remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 121} 122// Create a TCP socket connection. A TCPSocket object is returned. 123let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 124tcp.on('message', (value: SocketInfo) => { 125 console.log("on message"); 126 let buffer = value.message; 127 let dataView = new DataView(buffer); 128 let str = ""; 129 for (let i = 0; i < dataView.byteLength; ++i) { 130 str += String.fromCharCode(dataView.getUint8(i)); 131 } 132 console.log("on connect received:" + str); 133}); 134tcp.on('connect', () => { 135 console.log("on connect"); 136}); 137tcp.on('close', () => { 138 console.log("on close"); 139}); 140 141// Bind the local IP address and port number. 142let ipAddress : socket.NetAddress = {} as socket.NetAddress; 143ipAddress.address = "192.168.xxx.xxx"; 144ipAddress.port = 1234; 145tcp.bind(ipAddress, (err: BusinessError) => { 146 if (err) { 147 console.log('bind fail'); 148 return; 149 } 150 console.log('bind success'); 151 152 // Set up a connection to the specified IP address and port number. 153 ipAddress.address = "192.168.xxx.xxx"; 154 ipAddress.port = 5678; 155 156 let tcpConnect : socket.TCPConnectOptions = {} as socket.TCPConnectOptions; 157 tcpConnect.address = ipAddress; 158 tcpConnect.timeout = 6000; 159 160 tcp.connect(tcpConnect).then(() => { 161 console.log('connect success'); 162 let tcpSendOptions: socket.TCPSendOptions = { 163 data: 'Hello, server!' 164 } 165 tcp.send(tcpSendOptions).then(() => { 166 console.log('send success'); 167 }).catch((err: BusinessError) => { 168 console.log('send fail'); 169 }); 170 }).catch((err: BusinessError) => { 171 console.log('connect fail'); 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().then(() => { 178 console.log('close success'); 179 }).catch((err: BusinessError) => { 180 console.log('close fail'); 181 }); 182 tcp.off('message'); 183 tcp.off('connect'); 184 tcp.off('close'); 185}, 30 * 1000); 186``` 187 188## Transmitting Data over TCP Socket Server Connections 189 190The TCP socket connection process on the server is 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 '@kit.NetworkKit'; 203import { BusinessError } from '@kit.BasicServicesKit'; 204 205// Create a TCP socket server connection. A TCPSocketServer object is returned. 206let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 207// Bind the local IP address and port number for listening. 208 209let ipAddress : socket.NetAddress = {} as socket.NetAddress; 210ipAddress.address = "192.168.xxx.xxx"; 211ipAddress.port = 4651; 212tcpServer.listen(ipAddress).then(() => { 213 console.log('listen success'); 214}).catch((err: BusinessError) => { 215 console.log('listen fail'); 216}); 217 218class SocketInfo { 219 message: ArrayBuffer = new ArrayBuffer(1); 220 remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 221} 222// Subscribe to connect events of the TCPSocketServer object. 223tcpServer.on("connect", (client: socket.TCPSocketConnection) => { 224 // Subscribe to events of the TCPSocketConnection object. 225 client.on("close", () => { 226 console.log("on close success"); 227 }); 228 client.on("message", (value: SocketInfo) => { 229 let buffer = value.message; 230 let dataView = new DataView(buffer); 231 let str = ""; 232 for (let i = 0; i < dataView.byteLength; ++i) { 233 str += String.fromCharCode(dataView.getUint8(i)); 234 } 235 console.log("received message--:" + str); 236 console.log("received address--:" + value.remoteInfo.address); 237 console.log("received family--:" + value.remoteInfo.family); 238 console.log("received port--:" + value.remoteInfo.port); 239 console.log("received size--:" + value.remoteInfo.size); 240 }); 241 242 // Send data to the client. 243 let tcpSendOptions : socket.TCPSendOptions = {} as socket.TCPSendOptions; 244 tcpSendOptions.data = 'Hello, client!'; 245 client.send(tcpSendOptions).then(() => { 246 console.log('send success'); 247 }).catch((err: Object) => { 248 console.error('send fail: ' + JSON.stringify(err)); 249 }); 250 251 // Close the connection between the client and the server. 252 client.close().then(() => { 253 console.log('close success'); 254 }).catch((err: BusinessError) => { 255 console.log('close fail'); 256 }); 257 258 // Unsubscribe from events of the TCPSocketConnection object. 259 setTimeout(() => { 260 client.off("message"); 261 client.off("close"); 262 }, 10 * 1000); 263}); 264 265// Unsubscribe from events of the TCPSocketServer object. 266setTimeout(() => { 267 tcpServer.off("connect"); 268}, 30 * 1000); 269``` 270 271## Transmitting Data over Multicast Socket Connections 272 2731. Import the required socket module. 274 2752. Create a **MulticastSocket** object. 276 2773. Specify a **MulticastSocket** object by the IP address and port number, and add it to the multicast group. 278 2794. Subscribe to **message** events. 280 2815. 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. 282 2836. Unsubscribe from **message** events. 284 2857. Drop the **MulticastSocket** object from the multicast group. 286 287```ts 288import { socket } from '@kit.NetworkKit'; 289 290// Create a MulticastSocket object. 291let multicast: socket.MulticastSocket = socket.constructMulticastSocketInstance(); 292 293let addr : socket.NetAddress = { 294 address: '239.255.0.1', 295 port: 32123, 296 family: 1 297} 298 299// Add the MulticastSocket object to a multicast group. 300multicast.addMembership(addr).then(() => { 301 console.log('addMembership success'); 302}).catch((err: Object) => { 303 console.log('addMembership fail'); 304}); 305 306// Subscribe to message events and convert the received data of the ArrayBuffer type to strings. 307class SocketInfo { 308 message: ArrayBuffer = new ArrayBuffer(1); 309 remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 310} 311multicast.on('message', (data: SocketInfo) => { 312 console.info ('Received data:' + JSON.stringify (data)) 313 const uintArray = new Uint8Array(data.message) 314 let str = '' 315 for (let i = 0; i < uintArray.length; ++i) { 316 str += String.fromCharCode(uintArray[i]) 317 } 318 console.info(str) 319}) 320 321// Send data over the connection. 322multicast.send({ data:'Hello12345', address: addr }).then(() => { 323 console.log('send success'); 324}).catch((err: Object) => { 325 console.log('send fail, ' + JSON.stringify(err)); 326}); 327 328// Unsubscribe from message events. 329multicast.off('message') 330 331// Drop the MulticastSocket object from the multicast group. 332multicast.dropMembership(addr).then(() => { 333 console.log('drop membership success'); 334}).catch((err: Object) => { 335 console.log('drop membership fail'); 336}); 337``` 338 339## Transmitting Data over Local Socket Connections 340 3411. Import the required socket module. 342 3432. Call **constructLocalSocketInstance** to create a **LocalSocket** object. 344 3453. Subscribe to **message** events of the **LocalSocket** object and other events (optional). 346 3474. Connect to server based on the specified address of the local socket file. 348 3495. Send data over the connection. 350 3516. If the socket connection is no longer needed, unsubscribe from message events and close the connection. 352 353>**NOTE** 354> 355>In the sample code provided in this topic, **this.context** is used to obtain the UIAbilityContext, where **this** indicates a UIAbility instance inherited from **UIAbility**. To use **UIAbilityContext** APIs on pages, see [Obtaining the Context of UIAbility](../application-models/uiability-usage.md#obtaining-the-context-of-uiability). 356 357```ts 358import { socket } from '@kit.NetworkKit'; 359import { common } from '@kit.AbilityKit'; 360 361// Create a local socket connection. A LocalSocket object is returned. 362let client: socket.LocalSocket = socket.constructLocalSocketInstance(); 363client.on('message', (value: socket.LocalSocketMessageInfo) => { 364 const uintArray = new Uint8Array(value.message) 365 let messageView = ''; 366 for (let i = 0; i < uintArray.length; i++) { 367 messageView += String.fromCharCode(uintArray[i]); 368 } 369 console.log('total receive: ' + JSON.stringify(value)); 370 console.log('message information: ' + messageView); 371}); 372client.on('connect', () => { 373 console.log("on connect"); 374}); 375client.on('close', () => { 376 console.log("on close"); 377}); 378 379// Specify the address of local socket file to connect to the server. 380let context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext; 381let sandboxPath: string = context.filesDir + '/testSocket'; 382let localAddress : socket.LocalAddress = { 383 address: sandboxPath 384} 385let connectOpt: socket.LocalConnectOptions = { 386 address: localAddress, 387 timeout: 6000 388} 389let sendOpt: socket.LocalSendOptions = { 390 data: 'Hello world!' 391} 392client.connect(connectOpt).then(() => { 393 console.log('connect success') 394 client.send(sendOpt).then(() => { 395 console.log('send success') 396 }).catch((err: Object) => { 397 console.log('send failed: ' + JSON.stringify(err)) 398 }) 399}).catch((err: Object) => { 400 console.log('connect fail: ' + JSON.stringify(err)); 401}); 402 403// If the socket connection is no longer needed, unsubscribe from message events and close the connection. 404client.off('message'); 405client.off('connect'); 406client.off('close'); 407client.close().then(() => { 408 console.log('close client success') 409}).catch((err: Object) => { 410 console.log('close client err: ' + JSON.stringify(err)) 411}) 412``` 413 414## Transmitting Data over Local Socket Server Connections 415 416The local socket connection process on the server is as follows: 417 4181. Import the required socket module. 419 4202. Call **constructLocalSocketServerInstance** to create a **LocalSocketServer** object. 421 4223. Bind the address of the local socket file. 423 4244. Subscribe to **connect** events of the local socket client and other events (optional). 425 4265. When the local socket client is connected, obtain the **LocalSocketConnection** object through the callback of the **connect** event. 427 4286. Subscribe to **message** events of the **LocalSocketConnection** object and other events (optional). 429 4307. Send messages to the local socket client through the **LocalSocketConnection** object. 431 4328. When the communication ends, close the local socket connection. 433 4349. Unsubscribe from events of the **LocalSocketConnection** and **LocalSocketServer** objects. 435 436>**NOTE** 437> 438>In the sample code provided in this topic, **this.context** is used to obtain the UIAbilityContext, where **this** indicates a UIAbility instance inherited from **UIAbility**. To use **UIAbilityContext** APIs on pages, see [Obtaining the Context of UIAbility](../application-models/uiability-usage.md#obtaining-the-context-of-uiability). 439 440```ts 441import { socket } from '@kit.NetworkKit'; 442import { common } from '@kit.AbilityKit'; 443 444// Create a local socket server connection. A LocalSocketServer object is returned. 445let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance(); 446// Create and bind the local socket file testSocket for listening. 447let context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext; 448let sandboxPath: string = context.filesDir + '/testSocket'; 449let listenAddr: socket.LocalAddress = { 450 address: sandboxPath 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: Object) => { 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: Object) => { 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 507The TLS socket connection process on the client is as follows: 508 5091. Import the required socket module. 510 5112. Bind the server IP address and port number. 512 5133. For two-way authentication, upload the client CA certificate and digital certificate. For one-way authentication, upload the client CA certificate. 514 5154. Create a TLS socket connection. A **TLSsocket** object is returned. 516 5175. (Optional) Subscribe to TLS socket connection events. 518 5196. Send data over the connection. 520 5217. Enable the TLS socket connection to be automatically closed after use. 522 523```ts 524import { socket } from '@kit.NetworkKit'; 525import { BusinessError } from '@kit.BasicServicesKit'; 526 527class SocketInfo { 528 message: ArrayBuffer = new ArrayBuffer(1); 529 remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 530} 531// Create a TLS socket connection (for two-way authentication). A TLSSocketConnection object is returned. 532let tlsTwoWay: socket.TLSSocket = socket.constructTLSSocketInstance(); 533// Subscribe to events of the TLSSocketConnection object. 534tlsTwoWay.on('message', (value: SocketInfo) => { 535 console.log("on message"); 536 let buffer = value.message; 537 let dataView = new DataView(buffer); 538 let str = ""; 539 for (let i = 0; i < dataView.byteLength; ++i) { 540 str += String.fromCharCode(dataView.getUint8(i)); 541 } 542 console.log("on connect received:" + str); 543}); 544tlsTwoWay.on('connect', () => { 545 console.log("on connect"); 546}); 547tlsTwoWay.on('close', () => { 548 console.log("on close"); 549}); 550 551// Bind the local IP address and port number. 552let ipAddress : socket.NetAddress = {} as socket.NetAddress; 553ipAddress.address = "192.168.xxx.xxx"; 554ipAddress.port = 4512; 555tlsTwoWay.bind(ipAddress, (err: BusinessError) => { 556 if (err) { 557 console.log('bind fail'); 558 return; 559 } 560 console.log('bind success'); 561}); 562 563ipAddress.address = "192.168.xxx.xxx"; 564ipAddress.port = 1234; 565 566let tlsSecureOption : socket.TLSSecureOptions = {} as socket.TLSSecureOptions; 567tlsSecureOption.key = "xxxx"; 568tlsSecureOption.cert = "xxxx"; 569tlsSecureOption.ca = ["xxxx"]; 570tlsSecureOption.password = "xxxx"; 571tlsSecureOption.protocols = [socket.Protocol.TLSv12]; 572tlsSecureOption.useRemoteCipherPrefer = true; 573tlsSecureOption.signatureAlgorithms = "rsa_pss_rsae_sha256:ECDSA+SHA256"; 574tlsSecureOption.cipherSuite = "AES256-SHA256"; 575 576let tlsTwoWayConnectOption : socket.TLSConnectOptions = {} as socket.TLSConnectOptions; 577tlsSecureOption.key = "xxxx"; 578tlsTwoWayConnectOption.address = ipAddress; 579tlsTwoWayConnectOption.secureOptions = tlsSecureOption; 580tlsTwoWayConnectOption.ALPNProtocols = ["spdy/1", "http/1.1"]; 581 582// Set up a connection. 583tlsTwoWay.connect(tlsTwoWayConnectOption).then(() => { 584 console.log("connect successfully"); 585}).catch((err: BusinessError) => { 586 console.log("connect failed " + JSON.stringify(err)); 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.TLSSocket = 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).then(() => { 645 console.log("connect successfully"); 646}).catch((err: BusinessError) => { 647 console.log("connect failed " + JSON.stringify(err)); 648}); 649 650// Enable the socket connection to be automatically closed after use. Then, unsubscribe from events of the connection. 651tlsTwoWay.close((err: BusinessError) => { 652 if (err) { 653 console.log("close callback error = " + err); 654 } else { 655 console.log("close success"); 656 } 657 tlsTwoWay.off('message'); 658 tlsTwoWay.off('connect'); 659 tlsTwoWay.off('close'); 660}); 661``` 662 663## Implementing Encrypted Data Transmission by Upgrading a TCP Socket Connection to a TLS Socket Connection 664 665The process of upgrading a TCP socket connection to a TLS socket connection is as follows: 666 6671. Import the required socket module. 668 6692. Create a TCP socket connection. For details, see [Transmitting Data over TCP Socket or UDP Socket Connections](#transmitting-data-over-tcp-socket-or-udp-socket-connections). 670 6713. After the TCP socket connection is established, use the **TCPSocket** object to create a TLS socket connection. A **TLSSocket** object is returned. 672 6734. For two-way authentication, upload the client CA certificate and digital certificate. For one-way authentication, upload the client CA certificate. 674 6755. (Optional) Subscribe to TLS socket connection events. 676 6776. Send data over the connection. 678 6797. Enable the TLS socket connection to be automatically closed after use. 680 681```ts 682import { socket } from '@kit.NetworkKit'; 683import { BusinessError } from '@kit.BasicServicesKit'; 684 685class SocketInfo { 686 message: ArrayBuffer = new ArrayBuffer(1); 687 remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 688} 689 690// Create a TCP socket connection. A TCPSocket object is returned. 691let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 692tcp.on('message', (value: SocketInfo) => { 693 console.log("on message"); 694 let buffer = value.message; 695 let dataView = new DataView(buffer); 696 let str = ""; 697 for (let i = 0; i < dataView.byteLength; ++i) { 698 str += String.fromCharCode(dataView.getUint8(i)); 699 } 700 console.log("on connect received:" + str); 701}); 702tcp.on('connect', () => { 703 console.log("on connect"); 704}); 705 706// Bind the local IP address and port number. 707let ipAddress: socket.NetAddress = {} as socket.NetAddress; 708ipAddress.address = "192.168.xxx.xxx"; 709ipAddress.port = 1234; 710tcp.bind(ipAddress, (err: BusinessError) => { 711 if (err) { 712 console.log('bind fail'); 713 return; 714 } 715 console.log('bind success'); 716 717 // Set up a connection to the specified IP address and port number. 718 ipAddress.address = "192.168.xxx.xxx"; 719 ipAddress.port = 443; 720 721 let tcpConnect: socket.TCPConnectOptions = {} as socket.TCPConnectOptions; 722 tcpConnect.address = ipAddress; 723 tcpConnect.timeout = 6000; 724 725 tcp.connect(tcpConnect, (err: BusinessError) => { 726 if (err) { 727 console.log('connect fail'); 728 return; 729 } 730 console.log('connect success'); 731 732 // After TCP socket connection is established, upgrade it to a TLS socket connection. 733 let tlsTwoWay: socket.TLSSocket = socket.constructTLSSocketInstance(tcp); 734 // Subscribe to events of the TLSSocket object. 735 tlsTwoWay.on('message', (value: SocketInfo) => { 736 console.log("tls on message"); 737 let buffer = value.message; 738 let dataView = new DataView(buffer); 739 let str = ""; 740 for (let i = 0; i < dataView.byteLength; ++i) { 741 str += String.fromCharCode(dataView.getUint8(i)); 742 } 743 console.log("tls on connect received:" + str); 744 }); 745 tlsTwoWay.on('connect', () => { 746 console.log("tls on connect"); 747 }); 748 tlsTwoWay.on('close', () => { 749 console.log("tls on close"); 750 }); 751 752 // Configure the destination address and certificate of the TLSSocket object. 753 ipAddress.address = "192.168.xxx.xxx"; 754 ipAddress.port = 1234; 755 756 let tlsSecureOption: socket.TLSSecureOptions = {} as socket.TLSSecureOptions; 757 tlsSecureOption.key = "xxxx"; 758 tlsSecureOption.cert = "xxxx"; 759 tlsSecureOption.ca = ["xxxx"]; 760 tlsSecureOption.password = "xxxx"; 761 tlsSecureOption.protocols = [socket.Protocol.TLSv12]; 762 tlsSecureOption.useRemoteCipherPrefer = true; 763 tlsSecureOption.signatureAlgorithms = "rsa_pss_rsae_sha256:ECDSA+SHA256"; 764 tlsSecureOption.cipherSuite = "AES256-SHA256"; 765 766 let tlsTwoWayConnectOption: socket.TLSConnectOptions = {} as socket.TLSConnectOptions; 767 tlsSecureOption.key = "xxxx"; 768 tlsTwoWayConnectOption.address = ipAddress; 769 tlsTwoWayConnectOption.secureOptions = tlsSecureOption; 770 tlsTwoWayConnectOption.ALPNProtocols = ["spdy/1", "http/1.1"]; 771 772 // Establish a TLS socket connection. 773 tlsTwoWay.connect(tlsTwoWayConnectOption, () => { 774 console.log("tls connect success"); 775 776 // Enable the socket connection to be automatically closed after use. Then, unsubscribe from events of the connection. 777 tlsTwoWay.close((err: BusinessError) => { 778 if (err) { 779 console.log("tls close callback error = " + err); 780 } else { 781 console.log("tls close success"); 782 } 783 tlsTwoWay.off('message'); 784 tlsTwoWay.off('connect'); 785 tlsTwoWay.off('close'); 786 }); 787 }); 788 }); 789}); 790``` 791 792## Implementing Encrypted Data Transmission over TLS Socket Server Connections 793 794The TLS socket connection process on the server is as follows: 795 7961. Import the required socket module. 797 7982. 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. 799 8003. Subscribes to **TLSSocketServer** connection events. 801 8024. Obtain a **TLSSocketConnection** object through the callback when the client initiates a TLS socket connection. 803 8045. Subscribe to events of the **TLSSocketConnection** object. 805 8066. Send data over the connection. 807 8087. Close the TLS socket connection if it is no longer needed. 809 8108. Unsubscribe from events of the **TLSSocketConnection** and **TLSSocketServer** objects. 811 812```ts 813import { socket } from '@kit.NetworkKit'; 814import { BusinessError } from '@kit.BasicServicesKit'; 815 816let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 817 818let netAddress: socket.NetAddress = { 819 address: '192.168.xx.xxx', 820 port: 8080 821} 822 823let tlsSecureOptions: socket.TLSSecureOptions = { 824 key: "xxxx", 825 cert: "xxxx", 826 ca: ["xxxx"], 827 password: "xxxx", 828 protocols: socket.Protocol.TLSv12, 829 useRemoteCipherPrefer: true, 830 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 831 cipherSuite: "AES256-SHA256" 832} 833 834let tlsConnectOptions: socket.TLSConnectOptions = { 835 address: netAddress, 836 secureOptions: tlsSecureOptions, 837 ALPNProtocols: ["spdy/1", "http/1.1"] 838} 839 840tlsServer.listen(tlsConnectOptions).then(() => { 841 console.log("listen callback success"); 842}).catch((err: BusinessError) => { 843 console.log("failed" + err); 844}); 845 846class SocketInfo { 847 message: ArrayBuffer = new ArrayBuffer(1); 848 remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 849} 850let callback = (value: SocketInfo) => { 851 let messageView = ''; 852 for (let i: number = 0; i < value.message.byteLength; i++) { 853 let uint8Array = new Uint8Array(value.message) 854 let messages = uint8Array[i] 855 let message = String.fromCharCode(messages); 856 messageView += message; 857 } 858 console.log('on message message: ' + JSON.stringify(messageView)); 859 console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo)); 860} 861tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 862 client.on('message', callback); 863 864 // Send data over the connection. 865 client.send('Hello, client!').then(() => { 866 console.log('send success'); 867 }).catch((err: BusinessError) => { 868 console.log('send fail'); 869 }); 870 871 // Close the connection. 872 client.close().then(() => { 873 console.log('close success'); 874 }).catch((err: BusinessError) => { 875 console.log('close fail'); 876 }); 877 878 // 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. 879 client.off('message', callback); 880 client.off('message'); 881}); 882 883// Unsubscribe from events of the TLSSocketServer object. 884tlsServer.off('connect'); 885``` 886