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 transmit data over TCP, UDP, Multicast, or TLS socket connections. The main application scenarios are as follows: 23 24- Implementing data transmission over TCP socket or 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 an IP address to a port, or binds the address of a local socket. | 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 a 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 **tls_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 **TCPSocketConnction** object is returned. 103 1043. (Optional) Subscribe to events of the **TCPSocketConnction** object. 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 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 '@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```ts 354import { socket } from '@kit.NetworkKit'; 355 356// Create a local socket connection. A LocalSocket object is returned. 357let client: socket.LocalSocket = socket.constructLocalSocketInstance(); 358client.on('message', (value: socket.LocalSocketMessageInfo) => { 359 const uintArray = new Uint8Array(value.message) 360 let messageView = ''; 361 for (let i = 0; i < uintArray.length; i++) { 362 messageView += String.fromCharCode(uintArray[i]); 363 } 364 console.log('total receive: ' + JSON.stringify(value)); 365 console.log('message information: ' + messageView); 366}); 367client.on('connect', () => { 368 console.log("on connect"); 369}); 370client.on('close', () => { 371 console.log("on close"); 372}); 373 374// Specify the address of local socket file to connect to the server. 375let sandboxPath: string = getContext(this).filesDir + '/testSocket' 376let localAddress : socket.LocalAddress = { 377 address: sandboxPath 378} 379let connectOpt: socket.LocalConnectOptions = { 380 address: localAddress, 381 timeout: 6000 382} 383let sendOpt: socket.LocalSendOptions = { 384 data: 'Hello world!' 385} 386client.connect(connectOpt).then(() => { 387 console.log('connect success') 388 client.send(sendOpt).then(() => { 389 console.log('send success') 390 }).catch((err: Object) => { 391 console.log('send failed: ' + JSON.stringify(err)) 392 }) 393}).catch((err: Object) => { 394 console.log('connect fail: ' + JSON.stringify(err)); 395}); 396 397// If the socket connection is no longer needed, unsubscribe from message events and close the connection. 398client.off('message'); 399client.off('connect'); 400client.off('close'); 401client.close().then(() => { 402 console.log('close client success') 403}).catch((err: Object) => { 404 console.log('close client err: ' + JSON.stringify(err)) 405}) 406``` 407 408## Transmitting Data over Local Socket Server Connections 409 410The local socket connection process on the server is described as follows: 411 4121. Import the required **socket** module. 413 4142. Call **constructLocalSocketServerInstance** to create a **LocalSocketServer** object. 415 4163. Bind the address of the local socket file. 417 4184. Subscribe to **connect** events of the local socket client and other events (optional). 419 4205. When the local socket client is connected, obtain the **LocalSocketConnection** object through the callback of the **connect** event. 421 4226. Subscribe to **message** events of the **LocalSocketConnection** object and other events (optional). 423 4247. Send messages to the local socket client through the **LocalSocketConnection** object. 425 4268. When the communication ends, close the local socket connection. 427 4289. Unsubscribe from events of the **LocalSocketConnection** and **LocalSocketServer** objects. 429 430```ts 431import { socket } from '@kit.NetworkKit'; 432 433// Create a local socket server connection. A LocalSocketServer object is returned. 434let server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance(); 435// Create and bind the local socket file testSocket for listening. 436let sandboxPath: string = getContext(this).filesDir + '/testSocket' 437let listenAddr: socket.LocalAddress = { 438 address: sandboxPath 439} 440server.listen(listenAddr).then(() => { 441 console.log("listen success"); 442}).catch((err: Object) => { 443 console.log("listen fail: " + JSON.stringify(err)); 444}); 445 446// Subscribe to connect events of the LocalSocketServer object. 447server.on('connect', (connection: socket.LocalSocketConnection) => { 448 // Subscribe to events of the LocalSocketConnection object. 449 connection.on('error', (err: Object) => { 450 console.log("on error success"); 451 }); 452 connection.on('message', (value: socket.LocalSocketMessageInfo) => { 453 const uintArray = new Uint8Array(value.message); 454 let messageView = ''; 455 for (let i = 0; i < uintArray.length; i++) { 456 messageView += String.fromCharCode(uintArray[i]); 457 } 458 console.log('total: ' + JSON.stringify(value)); 459 console.log('message information: ' + messageView); 460 }); 461 462 connection.on('error', (err: Object) => { 463 console.log("err:" + JSON.stringify(err)); 464 }) 465 466 // Send data to the client. 467 let sendOpt : socket.LocalSendOptions = { 468 data: 'Hello world!' 469 }; 470 connection.send(sendOpt).then(() => { 471 console.log('send success'); 472 }).catch((err: Object) => { 473 console.log('send failed: ' + JSON.stringify(err)); 474 }) 475 476 // Close the connection between the client and the server. 477 connection.close().then(() => { 478 console.log('close success'); 479 }).catch((err: Object) => { 480 console.log('close failed: ' + JSON.stringify(err)); 481 }); 482 483 // Unsubscribe from events of the LocalSocketConnection object. 484 connection.off('message'); 485 connection.off('error'); 486}); 487 488// Unsubscribe from events of the LocalSocketServer object. 489server.off('connect'); 490server.off('error'); 491``` 492 493## Implementing Encrypted Data Transmission over TLS Socket Connections 494 495The TLS socket connection process on the client is described as follows: 496 4971. Import the required **socket** module. 498 4992. Bind the IP address and port number of the server. 500 5013. For two-way authentication, upload the client CA certificate and digital certificate. For one-way authentication, upload the client CA certificate. 502 5034. Create a TLS socket connection. A **TLSSocketConnection** object is returned. 504 5055. (Optional) Subscribe to events of the **TLSSocketConnection** object. 506 5076. Send data over the connection. 508 5097. Enable the TLS socket connection to be automatically closed after use. 510 511```ts 512import { socket } from '@kit.NetworkKit'; 513import { BusinessError } from '@kit.BasicServicesKit'; 514 515class SocketInfo { 516 message: ArrayBuffer = new ArrayBuffer(1); 517 remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 518} 519// Create a TLS socket connection (for two-way authentication). A TLSSocketConnection object is returned. 520let tlsTwoWay: socket.TLSSocket = socket.constructTLSSocketInstance(); 521// Subscribe to events of the TLSSocketConnection object. 522tlsTwoWay.on('message', (value: SocketInfo) => { 523 console.log("on message"); 524 let buffer = value.message; 525 let dataView = new DataView(buffer); 526 let str = ""; 527 for (let i = 0; i < dataView.byteLength; ++i) { 528 str += String.fromCharCode(dataView.getUint8(i)); 529 } 530 console.log("on connect received:" + str); 531}); 532tlsTwoWay.on('connect', () => { 533 console.log("on connect"); 534}); 535tlsTwoWay.on('close', () => { 536 console.log("on close"); 537}); 538 539// Bind the local IP address and port number. 540let ipAddress : socket.NetAddress = {} as socket.NetAddress; 541ipAddress.address = "192.168.xxx.xxx"; 542ipAddress.port = 4512; 543tlsTwoWay.bind(ipAddress, (err: BusinessError) => { 544 if (err) { 545 console.log('bind fail'); 546 return; 547 } 548 console.log('bind success'); 549}); 550 551ipAddress.address = "192.168.xxx.xxx"; 552ipAddress.port = 1234; 553 554let tlsSecureOption : socket.TLSSecureOptions = {} as socket.TLSSecureOptions; 555tlsSecureOption.key = "xxxx"; 556tlsSecureOption.cert = "xxxx"; 557tlsSecureOption.ca = ["xxxx"]; 558tlsSecureOption.password = "xxxx"; 559tlsSecureOption.protocols = [socket.Protocol.TLSv12]; 560tlsSecureOption.useRemoteCipherPrefer = true; 561tlsSecureOption.signatureAlgorithms = "rsa_pss_rsae_sha256:ECDSA+SHA256"; 562tlsSecureOption.cipherSuite = "AES256-SHA256"; 563 564let tlsTwoWayConnectOption : socket.TLSConnectOptions = {} as socket.TLSConnectOptions; 565tlsSecureOption.key = "xxxx"; 566tlsTwoWayConnectOption.address = ipAddress; 567tlsTwoWayConnectOption.secureOptions = tlsSecureOption; 568tlsTwoWayConnectOption.ALPNProtocols = ["spdy/1", "http/1.1"]; 569 570// Set up a connection. 571tlsTwoWay.connect(tlsTwoWayConnectOption).then(() => { 572 console.log("connect successfully"); 573}).catch((err: BusinessError) => { 574 console.log("connect failed " + JSON.stringify(err)); 575}); 576 577// Enable the socket connection to be automatically closed after use. Then, unsubscribe from events of the connection. 578tlsTwoWay.close((err: BusinessError) => { 579 if (err) { 580 console.log("close callback error = " + err); 581 } else { 582 console.log("close success"); 583 } 584 tlsTwoWay.off('message'); 585 tlsTwoWay.off('connect'); 586 tlsTwoWay.off('close'); 587}); 588 589// Create a TLS socket connection (for one-way authentication). A TLSSocketConnection object is returned. 590let tlsOneWay: socket.TLSSocket = socket.constructTLSSocketInstance(); // One way authentication 591 592// Subscribe to events of the TLSSocketConnection object. 593tlsTwoWay.on('message', (value: SocketInfo) => { 594 console.log("on message"); 595 let buffer = value.message; 596 let dataView = new DataView(buffer); 597 let str = ""; 598 for (let i = 0; i < dataView.byteLength; ++i) { 599 str += String.fromCharCode(dataView.getUint8(i)); 600 } 601 console.log("on connect received:" + str); 602}); 603tlsTwoWay.on('connect', () => { 604 console.log("on connect"); 605}); 606tlsTwoWay.on('close', () => { 607 console.log("on close"); 608}); 609 610// Bind the local IP address and port number. 611ipAddress.address = "192.168.xxx.xxx"; 612ipAddress.port = 5445; 613tlsOneWay.bind(ipAddress, (err:BusinessError) => { 614 if (err) { 615 console.log('bind fail'); 616 return; 617 } 618 console.log('bind success'); 619}); 620 621ipAddress.address = "192.168.xxx.xxx"; 622ipAddress.port = 8789; 623let tlsOneWaySecureOption : socket.TLSSecureOptions = {} as socket.TLSSecureOptions; 624tlsOneWaySecureOption.ca = ["xxxx", "xxxx"]; 625tlsOneWaySecureOption.cipherSuite = "AES256-SHA256"; 626 627let tlsOneWayConnectOptions: socket.TLSConnectOptions = {} as socket.TLSConnectOptions; 628tlsOneWayConnectOptions.address = ipAddress; 629tlsOneWayConnectOptions.secureOptions = tlsOneWaySecureOption; 630 631// Set up a connection. 632tlsOneWay.connect(tlsOneWayConnectOptions).then(() => { 633 console.log("connect successfully"); 634}).catch((err: BusinessError) => { 635 console.log("connect failed " + JSON.stringify(err)); 636}); 637 638// Enable the socket connection to be automatically closed after use. Then, unsubscribe from events of the connection. 639tlsTwoWay.close((err: BusinessError) => { 640 if (err) { 641 console.log("close callback error = " + err); 642 } else { 643 console.log("close success"); 644 } 645 tlsTwoWay.off('message'); 646 tlsTwoWay.off('connect'); 647 tlsTwoWay.off('close'); 648}); 649``` 650 651## Implementing Encrypted Data Transmission by Upgrading a TCP Socket Connection to a TLS Socket Connection 652 653The process of upgrading a TCP socket connection to a TLS socket connection is as follows: 654 6551. Import the required **socket** module. 656 6572. 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). 658 6593. After the TCP socket connection is established, use the **TCPSocket** object to create a TLS socket connection. A **TLSSocket** object is returned. 660 6614. For two-way authentication, upload the client CA certificate and digital certificate. For one-way authentication, upload the client CA certificate. 662 6635. (Optional) Subscribe to events of the **TLSSocketConnection** object. 664 6656. Send data over the connection. 666 6677. Enable the TLS socket connection to be automatically closed after use. 668 669```ts 670import { socket } from '@kit.NetworkKit'; 671import { BusinessError } from '@kit.BasicServicesKit'; 672 673class SocketInfo { 674 message: ArrayBuffer = new ArrayBuffer(1); 675 remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 676} 677 678// Create a TCP socket connection. A TCPSocket object is returned. 679let tcp: socket.TCPSocket = socket.constructTCPSocketInstance(); 680tcp.on('message', (value: SocketInfo) => { 681 console.log("on message"); 682 let buffer = value.message; 683 let dataView = new DataView(buffer); 684 let str = ""; 685 for (let i = 0; i < dataView.byteLength; ++i) { 686 str += String.fromCharCode(dataView.getUint8(i)); 687 } 688 console.log("on connect received:" + str); 689}); 690tcp.on('connect', () => { 691 console.log("on connect"); 692}); 693 694// Bind the local IP address and port number. 695let ipAddress: socket.NetAddress = {} as socket.NetAddress; 696ipAddress.address = "192.168.xxx.xxx"; 697ipAddress.port = 1234; 698tcp.bind(ipAddress, (err: BusinessError) => { 699 if (err) { 700 console.log('bind fail'); 701 return; 702 } 703 console.log('bind success'); 704 705 // Set up a connection to the specified IP address and port number. 706 ipAddress.address = "192.168.xxx.xxx"; 707 ipAddress.port = 443; 708 709 let tcpConnect: socket.TCPConnectOptions = {} as socket.TCPConnectOptions; 710 tcpConnect.address = ipAddress; 711 tcpConnect.timeout = 6000; 712 713 tcp.connect(tcpConnect, (err: BusinessError) => { 714 if (err) { 715 console.log('connect fail'); 716 return; 717 } 718 console.log('connect success'); 719 720 // After TCP socket connection is established, upgrade it to a TLS socket connection. 721 let tlsTwoWay: socket.TLSSocket = socket.constructTLSSocketInstance(tcp); 722 // Subscribe to events of the TLSSocket object. 723 tlsTwoWay.on('message', (value: SocketInfo) => { 724 console.log("tls on message"); 725 let buffer = value.message; 726 let dataView = new DataView(buffer); 727 let str = ""; 728 for (let i = 0; i < dataView.byteLength; ++i) { 729 str += String.fromCharCode(dataView.getUint8(i)); 730 } 731 console.log("tls on connect received:" + str); 732 }); 733 tlsTwoWay.on('connect', () => { 734 console.log("tls on connect"); 735 }); 736 tlsTwoWay.on('close', () => { 737 console.log("tls on close"); 738 }); 739 740 // Configure the destination address and certificate of the TLSSocket object. 741 ipAddress.address = "192.168.xxx.xxx"; 742 ipAddress.port = 1234; 743 744 let tlsSecureOption: socket.TLSSecureOptions = {} as socket.TLSSecureOptions; 745 tlsSecureOption.key = "xxxx"; 746 tlsSecureOption.cert = "xxxx"; 747 tlsSecureOption.ca = ["xxxx"]; 748 tlsSecureOption.password = "xxxx"; 749 tlsSecureOption.protocols = [socket.Protocol.TLSv12]; 750 tlsSecureOption.useRemoteCipherPrefer = true; 751 tlsSecureOption.signatureAlgorithms = "rsa_pss_rsae_sha256:ECDSA+SHA256"; 752 tlsSecureOption.cipherSuite = "AES256-SHA256"; 753 754 let tlsTwoWayConnectOption: socket.TLSConnectOptions = {} as socket.TLSConnectOptions; 755 tlsSecureOption.key = "xxxx"; 756 tlsTwoWayConnectOption.address = ipAddress; 757 tlsTwoWayConnectOption.secureOptions = tlsSecureOption; 758 tlsTwoWayConnectOption.ALPNProtocols = ["spdy/1", "http/1.1"]; 759 760 // Establish a TLS socket connection. 761 tlsTwoWay.connect(tlsTwoWayConnectOption, () => { 762 console.log("tls connect success"); 763 764 // Enable the socket connection to be automatically closed after use. Then, unsubscribe from events of the connection. 765 tlsTwoWay.close((err: BusinessError) => { 766 if (err) { 767 console.log("tls close callback error = " + err); 768 } else { 769 console.log("tls close success"); 770 } 771 tlsTwoWay.off('message'); 772 tlsTwoWay.off('connect'); 773 tlsTwoWay.off('close'); 774 }); 775 }); 776 }); 777}); 778``` 779 780## Implementing Encrypted Data Transmission over TLS Socket Server Connections 781 782The TLS socket connection process on the server is described as follows: 783 7841. Import the required **socket** module. 785 7862. 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. 787 7883. Subscribe to **connect** events of the **TLSSocketServer** object. 789 7904. Obtain a **TLSSocketConnection** object through the callback when the client initiates a TLS socket connection. 791 7925. Subscribe to events of the **TLSSocketConnection** object. 793 7946. Send data over the connection. 795 7967. Close the TLS socket connection if it is no longer needed. 797 7988. Unsubscribe from events of the **TLSSocketConnection** and **TLSSocketServer** objects. 799 800```ts 801import { socket } from '@kit.NetworkKit'; 802import { BusinessError } from '@kit.BasicServicesKit'; 803 804let tlsServer: socket.TLSSocketServer = socket.constructTLSSocketServerInstance(); 805 806let netAddress: socket.NetAddress = { 807 address: '192.168.xx.xxx', 808 port: 8080 809} 810 811let tlsSecureOptions: socket.TLSSecureOptions = { 812 key: "xxxx", 813 cert: "xxxx", 814 ca: ["xxxx"], 815 password: "xxxx", 816 protocols: socket.Protocol.TLSv12, 817 useRemoteCipherPrefer: true, 818 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", 819 cipherSuite: "AES256-SHA256" 820} 821 822let tlsConnectOptions: socket.TLSConnectOptions = { 823 address: netAddress, 824 secureOptions: tlsSecureOptions, 825 ALPNProtocols: ["spdy/1", "http/1.1"] 826} 827 828tlsServer.listen(tlsConnectOptions).then(() => { 829 console.log("listen callback success"); 830}).catch((err: BusinessError) => { 831 console.log("failed" + err); 832}); 833 834class SocketInfo { 835 message: ArrayBuffer = new ArrayBuffer(1); 836 remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 837} 838let callback = (value: SocketInfo) => { 839 let messageView = ''; 840 for (let i: number = 0; i < value.message.byteLength; i++) { 841 let uint8Array = new Uint8Array(value.message) 842 let messages = uint8Array[i] 843 let message = String.fromCharCode(messages); 844 messageView += message; 845 } 846 console.log('on message message: ' + JSON.stringify(messageView)); 847 console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo)); 848} 849tlsServer.on('connect', (client: socket.TLSSocketConnection) => { 850 client.on('message', callback); 851 852 // Send data over the connection. 853 client.send('Hello, client!').then(() => { 854 console.log('send success'); 855 }).catch((err: BusinessError) => { 856 console.log('send fail'); 857 }); 858 859 // Close the connection. 860 client.close().then(() => { 861 console.log('close success'); 862 }).catch((err: BusinessError) => { 863 console.log('close fail'); 864 }); 865 866 // 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. 867 client.off('message', callback); 868 client.off('message'); 869}); 870 871// Unsubscribe from events of the TLSSocketServer object. 872tlsServer.off('connect'); 873``` 874