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-network-kit/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 '@kit.NetworkKit'; 112import { BusinessError } from '@kit.BasicServicesKit'; 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.TCPSocket = 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).then(() => { 157 console.log('connect success'); 158 let tcpSendOptions: socket.TCPSendOptions = { 159 data: 'Hello, server!' 160 } 161 tcp.send(tcpSendOptions).then(() => { 162 console.log('send success'); 163 }).catch((err: BusinessError) => { 164 console.log('send fail'); 165 }); 166 }).catch((err: BusinessError) => { 167 console.log('connect fail'); 168 }); 169}); 170 171// Enable the socket connection to be automatically closed after use. Then, unsubscribe from events of the connection. 172setTimeout(() => { 173 tcp.close().then(() => { 174 console.log('close success'); 175 }).catch((err: BusinessError) => { 176 console.log('close fail'); 177 }); 178 tcp.off('message'); 179 tcp.off('connect'); 180 tcp.off('close'); 181}, 30 * 1000); 182``` 183 184## Transmitting Data over TCP Socket Server Connections 185 186The TCP socket server connection process is described as follows: 187 1881. Import the required **socket** module. 1892. Create a TCP socket server connection. A **TCPSocketServer** object is returned. 1903. Bind the local IP address and port, and listen for and accept TCP socket connections established over the socket. 1914. Subscribe to **connect** events of the **TCPSocketServer** object to listen for client connection status changes. 1925. Set up a connection between the client and the server. A **TCPSocketConnection** object is returned. 1936. Subscribe to events of the **TCPSocketConnection** object, and send data to the client through the **TCPSocketConnection** object. 1947. Close the connection between the client and the server. 1958. Unsubscribe from events of the **TCPSocketConnection** and **TCPSocketServer** objects. 196 197```ts 198import { socket } from '@kit.NetworkKit'; 199import { BusinessError } from '@kit.BasicServicesKit'; 200 201// Create a TCP socket server connection. A TCPSocketServer object is returned. 202let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance(); 203// Bind the local IP address and port number for listening. 204 205let ipAddress : socket.NetAddress = {} as socket.NetAddress; 206ipAddress.address = "192.168.xxx.xxx"; 207ipAddress.port = 4651; 208tcpServer.listen(ipAddress).then(() => { 209 console.log('listen success'); 210}).catch((err: BusinessError) => { 211 console.log('listen fail'); 212}); 213 214class SocketInfo { 215 message: ArrayBuffer = new ArrayBuffer(1); 216 remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 217} 218// Subscribe to connect events of the TCPSocketServer object. 219tcpServer.on("connect", (client: socket.TCPSocketConnection) => { 220 // Subscribe to events of the TCPSocketConnection object. 221 client.on("close", () => { 222 console.log("on close success"); 223 }); 224 client.on("message", (value: SocketInfo) => { 225 let buffer = value.message; 226 let dataView = new DataView(buffer); 227 let str = ""; 228 for (let i = 0; i < dataView.byteLength; ++i) { 229 str += String.fromCharCode(dataView.getUint8(i)); 230 } 231 console.log("received message--:" + str); 232 console.log("received address--:" + value.remoteInfo.address); 233 console.log("received family--:" + value.remoteInfo.family); 234 console.log("received port--:" + value.remoteInfo.port); 235 console.log("received size--:" + value.remoteInfo.size); 236 }); 237 238 // Send data to the client. 239 let tcpSendOptions : socket.TCPSendOptions = {} as socket.TCPSendOptions; 240 tcpSendOptions.data = 'Hello, client!'; 241 client.send(tcpSendOptions).then(() => { 242 console.log('send success'); 243 }).catch((err: Object) => { 244 console.error('send fail: ' + JSON.stringify(err)); 245 }); 246 247 // Close the connection between the client and the server. 248 client.close().then(() => { 249 console.log('close success'); 250 }).catch((err: BusinessError) => { 251 console.log('close fail'); 252 }); 253 254 // Unsubscribe from events of the TCPSocketConnection object. 255 setTimeout(() => { 256 client.off("message"); 257 client.off("close"); 258 }, 10 * 1000); 259}); 260 261// Unsubscribe from events of the TCPSocketServer object. 262setTimeout(() => { 263 tcpServer.off("connect"); 264}, 30 * 1000); 265``` 266 267## Transmitting Data over Multicast Socket Connections 268 2691. Import the required **socket** module. 270 2712. Create a **MulticastSocket** object. 272 2733. Specify a **MulticastSocket** object by the IP address and port number, and add it to the multicast group. 274 2754. Subscribe to **message** events. 276 2775. 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. 278 2796. Unsubscribe from **message** events. 280 2817. Drop the **MulticastSocket** object from the multicast group. 282 283```ts 284import { socket } from '@kit.NetworkKit'; 285 286// Create a MulticastSocket object. 287let multicast: socket.MulticastSocket = socket.constructMulticastSocketInstance(); 288 289let addr : socket.NetAddress = { 290 address: '239.255.0.1', 291 port: 32123, 292 family: 1 293} 294 295// Add the MulticastSocket object to a multicast group. 296multicast.addMembership(addr).then(() => { 297 console.log('addMembership success'); 298}).catch((err: Object) => { 299 console.log('addMembership fail'); 300}); 301 302// Subscribe to message events and convert the received data of the ArrayBuffer type to strings. 303class SocketInfo { 304 message: ArrayBuffer = new ArrayBuffer(1); 305 remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 306} 307multicast.on('message', (data: SocketInfo) => { 308 console.info ('Received data:' + JSON.stringify (data)) 309 const uintArray = new Uint8Array(data.message) 310 let str = '' 311 for (let i = 0; i < uintArray.length; ++i) { 312 str += String.fromCharCode(uintArray[i]) 313 } 314 console.info(str) 315}) 316 317// Send data over the connection. 318multicast.send({ data:'Hello12345', address: addr }).then(() => { 319 console.log('send success'); 320}).catch((err: Object) => { 321 console.log('send fail, ' + JSON.stringify(err)); 322}); 323 324// Unsubscribe from message events. 325multicast.off('message') 326 327// Drop the MulticastSocket object from the multicast group. 328multicast.dropMembership(addr).then(() => { 329 console.log('drop membership success'); 330}).catch((err: Object) => { 331 console.log('drop membership fail'); 332}); 333``` 334 335## Transmitting Data over Local Socket Connections 336 3371. Import the required **socket** module. 338 3392. Call **constructLocalSocketInstance** to create a **LocalSocket** object. 340 3413. Subscribe to **message** events of the **LocalSocket** object and other events (optional). 342 3434. Connect to server based on the specified address of the local socket file. 344 3455. Send data over the connection. 346 3476. If the socket connection is no longer needed, unsubscribe from message events and close the connection. 348 349```ts 350import { socket } from '@kit.NetworkKit'; 351 352// Create a local socket connection. A LocalSocket object is returned. 353let client: socket.LocalSocket = socket.constructLocalSocketInstance(); 354client.on('message', (value: socket.LocalSocketMessageInfo) => { 355 const uintArray = new Uint8Array(value.message) 356 let messageView = ''; 357 for (let i = 0; i < uintArray.length; i++) { 358 messageView += String.fromCharCode(uintArray[i]); 359 } 360 console.log('total receive: ' + JSON.stringify(value)); 361 console.log('message information: ' + messageView); 362}); 363client.on('connect', () => { 364 console.log("on connect"); 365}); 366client.on('close', () => { 367 console.log("on close"); 368}); 369 370// Specify the address of local socket file to connect to the server. 371let sandboxPath: string = getContext(this).filesDir + '/testSocket' 372let localAddress : socket.LocalAddress = { 373 address: sandboxPath 374} 375let connectOpt: socket.LocalConnectOptions = { 376 address: localAddress, 377 timeout: 6000 378} 379let sendOpt: socket.LocalSendOptions = { 380 data: 'Hello world!' 381} 382client.connect(connectOpt).then(() => { 383 console.log('connect success') 384 client.send(sendOpt).then(() => { 385 console.log('send success') 386 }).catch((err: Object) => { 387 console.log('send failed: ' + JSON.stringify(err)) 388 }) 389}).catch((err: Object) => { 390 console.log('connect fail: ' + JSON.stringify(err)); 391}); 392 393// If the socket connection is no longer needed, unsubscribe from message events and close the connection. 394client.off('message'); 395client.off('connect'); 396client.off('close'); 397client.close().then(() => { 398 console.log('close client success') 399}).catch((err: Object) => { 400 console.log('close client err: ' + JSON.stringify(err)) 401}) 402``` 403 404## Transmitting Data over Local Socket Server Connections 405 406The local socket connection process on the server is described as follows: 407 4081. Import the required **socket** module. 409 4102. Call **constructLocalSocketServerInstance** to create a **LocalSocketServer** object. 411 4123. Bind the address of the local socket file. 413 4144. Subscribe to **connect** events of the local socket client and other events (optional). 415 4165. When the local socket client is connected, obtain the **LocalSocketConnection** object through the callback of the **connect** event. 417 4186. Subscribe to **message** events of the **LocalSocketConnection** object and other events (optional). 419 4207. Send messages to the local socket client through the **LocalSocketConnection** object. 421 4228. When the communication ends, close the local socket connection. 423 4249. Unsubscribe from events of the **LocalSocketConnection** and **LocalSocketServer** objects. 425 426```ts 427import { socket } from '@kit.NetworkKit'; 428 429// Create a local socket server connection. A LocalSocketServer object is returned. 430let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance(); 431// Create and bind the local socket file testSocket for listening. 432let sandboxPath: string = getContext(this).filesDir + '/testSocket' 433let listenAddr: socket.LocalAddress = { 434 address: sandboxPath 435} 436server.listen(listenAddr).then(() => { 437 console.log("listen success"); 438}).catch((err: Object) => { 439 console.log("listen fail: " + JSON.stringify(err)); 440}); 441 442// Subscribe to connect events of the LocalSocketServer object. 443server.on('connect', (connection: socket.LocalSocketConnection) => { 444 // Subscribe to events of the LocalSocketConnection object. 445 connection.on('error', (err: Object) => { 446 console.log("on error success"); 447 }); 448 connection.on('message', (value: socket.LocalSocketMessageInfo) => { 449 const uintArray = new Uint8Array(value.message); 450 let messageView = ''; 451 for (let i = 0; i < uintArray.length; i++) { 452 messageView += String.fromCharCode(uintArray[i]); 453 } 454 console.log('total: ' + JSON.stringify(value)); 455 console.log('message information: ' + messageView); 456 }); 457 458 connection.on('error', (err: Object) => { 459 console.log("err:" + JSON.stringify(err)); 460 }) 461 462 // Send data to the client. 463 let sendOpt : socket.LocalSendOptions = { 464 data: 'Hello world!' 465 }; 466 connection.send(sendOpt).then(() => { 467 console.log('send success'); 468 }).catch((err: Object) => { 469 console.log('send failed: ' + JSON.stringify(err)); 470 }) 471 472 // Close the connection between the client and the server. 473 connection.close().then(() => { 474 console.log('close success'); 475 }).catch((err: Object) => { 476 console.log('close failed: ' + JSON.stringify(err)); 477 }); 478 479 // Unsubscribe from events of the LocalSocketConnection object. 480 connection.off('message'); 481 connection.off('error'); 482}); 483 484// Unsubscribe from events of the LocalSocketServer object. 485server.off('connect'); 486server.off('error'); 487``` 488 489## Implementing Encrypted Data Transmission over TLS Socket Connections 490 491The TLS socket connection process on the client is described as follows: 492 4931. Import the required **socket** module. 494 4952. Bind the IP address and port number of the server. 496 4973. For two-way authentication, upload the client CA certificate and digital certificate. For one-way authentication, upload the client CA certificate. 498 4994. Create a TLS socket connection. A **TLSSocketConnection** object is returned. 500 5015. (Optional) Subscribe to events of the **TLSSocketConnection** object. 502 5036. Send data over the connection. 504 5057. Enable the TLS socket connection to be automatically closed after use. 506 507```ts 508import { socket } from '@kit.NetworkKit'; 509import { BusinessError } from '@kit.BasicServicesKit'; 510 511class SocketInfo { 512 message: ArrayBuffer = new ArrayBuffer(1); 513 remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 514} 515// Create a TLS socket connection (for two-way authentication). A TLSSocketConnection object is returned. 516let tlsTwoWay: socket.TLSSocket = socket.constructTLSSocketInstance(); 517// Subscribe to events of the TLSSocketConnection object. 518tlsTwoWay.on('message', (value: SocketInfo) => { 519 console.log("on message"); 520 let buffer = value.message; 521 let dataView = new DataView(buffer); 522 let str = ""; 523 for (let i = 0; i < dataView.byteLength; ++i) { 524 str += String.fromCharCode(dataView.getUint8(i)); 525 } 526 console.log("on connect received:" + str); 527}); 528tlsTwoWay.on('connect', () => { 529 console.log("on connect"); 530}); 531tlsTwoWay.on('close', () => { 532 console.log("on close"); 533}); 534 535// Bind the local IP address and port number. 536let ipAddress : socket.NetAddress = {} as socket.NetAddress; 537ipAddress.address = "192.168.xxx.xxx"; 538ipAddress.port = 4512; 539tlsTwoWay.bind(ipAddress, (err: BusinessError) => { 540 if (err) { 541 console.log('bind fail'); 542 return; 543 } 544 console.log('bind success'); 545}); 546 547ipAddress.address = "192.168.xxx.xxx"; 548ipAddress.port = 1234; 549 550let tlsSecureOption : socket.TLSSecureOptions = {} as socket.TLSSecureOptions; 551tlsSecureOption.key = "xxxx"; 552tlsSecureOption.cert = "xxxx"; 553tlsSecureOption.ca = ["xxxx"]; 554tlsSecureOption.password = "xxxx"; 555tlsSecureOption.protocols = [socket.Protocol.TLSv12]; 556tlsSecureOption.useRemoteCipherPrefer = true; 557tlsSecureOption.signatureAlgorithms = "rsa_pss_rsae_sha256:ECDSA+SHA256"; 558tlsSecureOption.cipherSuite = "AES256-SHA256"; 559 560let tlsTwoWayConnectOption : socket.TLSConnectOptions = {} as socket.TLSConnectOptions; 561tlsSecureOption.key = "xxxx"; 562tlsTwoWayConnectOption.address = ipAddress; 563tlsTwoWayConnectOption.secureOptions = tlsSecureOption; 564tlsTwoWayConnectOption.ALPNProtocols = ["spdy/1", "http/1.1"]; 565 566// Set up a connection. 567tlsTwoWay.connect(tlsTwoWayConnectOption).then(() => { 568 console.log("connect successfully"); 569}).catch((err: BusinessError) => { 570 console.log("connect failed " + JSON.stringify(err)); 571}); 572 573// Enable the socket connection to be automatically closed after use. Then, unsubscribe from events of the connection. 574tlsTwoWay.close((err: BusinessError) => { 575 if (err) { 576 console.log("close callback error = " + err); 577 } else { 578 console.log("close success"); 579 } 580 tlsTwoWay.off('message'); 581 tlsTwoWay.off('connect'); 582 tlsTwoWay.off('close'); 583}); 584 585// Create a TLS socket connection (for one-way authentication). A TLSSocketConnection object is returned. 586let tlsOneWay: socket.TLSSocket = socket.constructTLSSocketInstance(); // One way authentication 587 588// Subscribe to events of the TLSSocketConnection object. 589tlsTwoWay.on('message', (value: SocketInfo) => { 590 console.log("on message"); 591 let buffer = value.message; 592 let dataView = new DataView(buffer); 593 let str = ""; 594 for (let i = 0; i < dataView.byteLength; ++i) { 595 str += String.fromCharCode(dataView.getUint8(i)); 596 } 597 console.log("on connect received:" + str); 598}); 599tlsTwoWay.on('connect', () => { 600 console.log("on connect"); 601}); 602tlsTwoWay.on('close', () => { 603 console.log("on close"); 604}); 605 606// Bind the local IP address and port number. 607ipAddress.address = "192.168.xxx.xxx"; 608ipAddress.port = 5445; 609tlsOneWay.bind(ipAddress, (err:BusinessError) => { 610 if (err) { 611 console.log('bind fail'); 612 return; 613 } 614 console.log('bind success'); 615}); 616 617ipAddress.address = "192.168.xxx.xxx"; 618ipAddress.port = 8789; 619let tlsOneWaySecureOption : socket.TLSSecureOptions = {} as socket.TLSSecureOptions; 620tlsOneWaySecureOption.ca = ["xxxx", "xxxx"]; 621tlsOneWaySecureOption.cipherSuite = "AES256-SHA256"; 622 623let tlsOneWayConnectOptions: socket.TLSConnectOptions = {} as socket.TLSConnectOptions; 624tlsOneWayConnectOptions.address = ipAddress; 625tlsOneWayConnectOptions.secureOptions = tlsOneWaySecureOption; 626 627// Set up a connection. 628tlsOneWay.connect(tlsOneWayConnectOptions).then(() => { 629 console.log("connect successfully"); 630}).catch((err: BusinessError) => { 631 console.log("connect failed " + JSON.stringify(err)); 632}); 633 634// Enable the socket connection to be automatically closed after use. Then, unsubscribe from events of the connection. 635tlsTwoWay.close((err: BusinessError) => { 636 if (err) { 637 console.log("close callback error = " + err); 638 } else { 639 console.log("close success"); 640 } 641 tlsTwoWay.off('message'); 642 tlsTwoWay.off('connect'); 643 tlsTwoWay.off('close'); 644}); 645``` 646 647## Implementing Encrypted Data Transmission by Upgrading a TCP Socket Connection to a TLS Socket Connection 648 649The process of upgrading a TCP socket connection to a TLS socket connection is as follows: 650 6511. Import the required **socket** module. 652 6532. 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). 654 6553. After the TCP socket connection is established, use the **TCPSocket** object to create a TLS socket connection. A **TLSSocket** object is returned. 656 6574. For two-way authentication, upload the client CA certificate and digital certificate. For one-way authentication, upload the client CA certificate. 658 6595. (Optional) Subscribe to events of the **TLSSocketConnection** object. 660 6616. Send data over the connection. 662 6637. Enable the TLS socket connection to be automatically closed after use. 664 665```ts 666import { socket } from '@kit.NetworkKit'; 667import { BusinessError } from '@kit.BasicServicesKit'; 668 669class SocketInfo { 670 message: ArrayBuffer = new ArrayBuffer(1); 671 remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 672} 673 674// Create a TCP socket connection. A TCPSocket object is returned. 675let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 676tcp.on('message', (value: SocketInfo) => { 677 console.log("on message"); 678 let buffer = value.message; 679 let dataView = new DataView(buffer); 680 let str = ""; 681 for (let i = 0; i < dataView.byteLength; ++i) { 682 str += String.fromCharCode(dataView.getUint8(i)); 683 } 684 console.log("on connect received:" + str); 685}); 686tcp.on('connect', () => { 687 console.log("on connect"); 688}); 689 690// Bind the local IP address and port number. 691let ipAddress: socket.NetAddress = {} as socket.NetAddress; 692ipAddress.address = "192.168.xxx.xxx"; 693ipAddress.port = 1234; 694tcp.bind(ipAddress, (err: BusinessError) => { 695 if (err) { 696 console.log('bind fail'); 697 return; 698 } 699 console.log('bind success'); 700 701 // Set up a connection to the specified IP address and port number. 702 ipAddress.address = "192.168.xxx.xxx"; 703 ipAddress.port = 443; 704 705 let tcpConnect: socket.TCPConnectOptions = {} as socket.TCPConnectOptions; 706 tcpConnect.address = ipAddress; 707 tcpConnect.timeout = 6000; 708 709 tcp.connect(tcpConnect, (err: BusinessError) => { 710 if (err) { 711 console.log('connect fail'); 712 return; 713 } 714 console.log('connect success'); 715 716 // After TCP socket connection is established, upgrade it to a TLS socket connection. 717 let tlsTwoWay: socket.TLSSocket = socket.constructTLSSocketInstance(tcp); 718 // Subscribe to events of the TLSSocket object. 719 tlsTwoWay.on('message', (value: SocketInfo) => { 720 console.log("tls on message"); 721 let buffer = value.message; 722 let dataView = new DataView(buffer); 723 let str = ""; 724 for (let i = 0; i < dataView.byteLength; ++i) { 725 str += String.fromCharCode(dataView.getUint8(i)); 726 } 727 console.log("tls on connect received:" + str); 728 }); 729 tlsTwoWay.on('connect', () => { 730 console.log("tls on connect"); 731 }); 732 tlsTwoWay.on('close', () => { 733 console.log("tls on close"); 734 }); 735 736 // Configure the destination address and certificate of the TLSSocket object. 737 ipAddress.address = "192.168.xxx.xxx"; 738 ipAddress.port = 1234; 739 740 let tlsSecureOption: socket.TLSSecureOptions = {} as socket.TLSSecureOptions; 741 tlsSecureOption.key = "xxxx"; 742 tlsSecureOption.cert = "xxxx"; 743 tlsSecureOption.ca = ["xxxx"]; 744 tlsSecureOption.password = "xxxx"; 745 tlsSecureOption.protocols = [socket.Protocol.TLSv12]; 746 tlsSecureOption.useRemoteCipherPrefer = true; 747 tlsSecureOption.signatureAlgorithms = "rsa_pss_rsae_sha256:ECDSA+SHA256"; 748 tlsSecureOption.cipherSuite = "AES256-SHA256"; 749 750 let tlsTwoWayConnectOption: socket.TLSConnectOptions = {} as socket.TLSConnectOptions; 751 tlsSecureOption.key = "xxxx"; 752 tlsTwoWayConnectOption.address = ipAddress; 753 tlsTwoWayConnectOption.secureOptions = tlsSecureOption; 754 tlsTwoWayConnectOption.ALPNProtocols = ["spdy/1", "http/1.1"]; 755 756 // Establish a TLS socket connection. 757 tlsTwoWay.connect(tlsTwoWayConnectOption, () => { 758 console.log("tls connect success"); 759 760 // Enable the socket connection to be automatically closed after use. Then, unsubscribe from events of the connection. 761 tlsTwoWay.close((err: BusinessError) => { 762 if (err) { 763 console.log("tls close callback error = " + err); 764 } else { 765 console.log("tls close success"); 766 } 767 tlsTwoWay.off('message'); 768 tlsTwoWay.off('connect'); 769 tlsTwoWay.off('close'); 770 }); 771 }); 772 }); 773}); 774``` 775 776## Implementing Encrypted Data Transmission over TLS Socket Server Connections 777 778The TLS socket connection process on the server is described as follows: 779 7801. Import the required **socket** module. 781 7822. 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. 783 7843. Subscribe to **connect** events of the **TLSSocketServer** object. 785 7864. Obtain a **TLSSocketConnection** object through the callback when the client initiates a TLS socket connection. 787 7885. Subscribe to events of the **TLSSocketConnection** object. 789 7906. Send data over the connection. 791 7927. Close the TLS socket connection if it is no longer needed. 793 7948. Unsubscribe from events of the **TLSSocketConnection** and **TLSSocketServer** objects. 795 796```ts 797import { socket } from '@kit.NetworkKit'; 798import { BusinessError } from '@kit.BasicServicesKit'; 799 800let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 801 802let netAddress: socket.NetAddress = { 803 address: '192.168.xx.xxx', 804 port: 8080 805} 806 807let tlsSecureOptions: socket.TLSSecureOptions = { 808 key: "xxxx", 809 cert: "xxxx", 810 ca: ["xxxx"], 811 password: "xxxx", 812 protocols: socket.Protocol.TLSv12, 813 useRemoteCipherPrefer: true, 814 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 815 cipherSuite: "AES256-SHA256" 816} 817 818let tlsConnectOptions: socket.TLSConnectOptions = { 819 address: netAddress, 820 secureOptions: tlsSecureOptions, 821 ALPNProtocols: ["spdy/1", "http/1.1"] 822} 823 824tlsServer.listen(tlsConnectOptions).then(() => { 825 console.log("listen callback success"); 826}).catch((err: BusinessError) => { 827 console.log("failed" + err); 828}); 829 830class SocketInfo { 831 message: ArrayBuffer = new ArrayBuffer(1); 832 remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 833} 834let callback = (value: SocketInfo) => { 835 let messageView = ''; 836 for (let i: number = 0; i < value.message.byteLength; i++) { 837 let uint8Array = new Uint8Array(value.message) 838 let messages = uint8Array[i] 839 let message = String.fromCharCode(messages); 840 messageView += message; 841 } 842 console.log('on message message: ' + JSON.stringify(messageView)); 843 console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo)); 844} 845tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 846 client.on('message', callback); 847 848 // Send data over the connection. 849 client.send('Hello, client!').then(() => { 850 console.log('send success'); 851 }).catch((err: BusinessError) => { 852 console.log('send fail'); 853 }); 854 855 // Close the connection. 856 client.close().then(() => { 857 console.log('close success'); 858 }).catch((err: BusinessError) => { 859 console.log('close fail'); 860 }); 861 862 // 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. 863 client.off('message', callback); 864 client.off('message'); 865}); 866 867// Unsubscribe from events of the TLSSocketServer object. 868tlsServer.off('connect'); 869``` 870 871