1# Socket Connection 2 3## Introduction 4 5The Socket Connection module allows an application to transmit data over a socket connection through the TCP, UDP, 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- TLS: Transport Layer Security, which is a protocol that ensures the data confidentiality and integrity between communication programs. 13 14## When to Use 15 16Applications transmit data over TCP, UDP, or TLS socket connections. The main application scenarios are as follows: 17 18- Implementing data transmission over TCP socket or UDP socket connections 19- Implementing data transmission over TCP socket server connections 20- Implementing encrypted data transmission over TLS socket connections 21 22## Available APIs 23 24For the complete list of APIs and example code, see [Socket Connection](../reference/apis/js-apis-socket.md). 25 26Socket connection functions are mainly implemented by the **socket** module. The following table describes the related APIs. 27 28| API | Description | 29| ---------------------------------- | ------------------------------------------------------------------------------ | 30| constructUDPSocketInstance() | Creates a **UDPSocket** object. | 31| constructTCPSocketInstance() | Creates a **TCPSocket** object. | 32| constructTCPSocketServerInstance() | Creates a **TCPSocketServer** object. | 33| listen() | Listens for and accepts TCP socket connections established over the socket. (This API is applicable only to TCP.)| 34| bind() | Binds the IP address and port number. | 35| send() | Sends data. | 36| close() | Closes a socket connection. | 37| getState() | Obtains the socket connection status. | 38| connect() | Connects to the specified IP address and port. This function is supported only for TCP. | 39| 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. | 40| setExtraOptions() | Sets other properties of the socket connection. | 41| on(type: 'message') | Subscribes to **message** events of the socket connection. | 42| off(type: 'message') | Unsubscribes from **message** events of the socket connection. | 43| on(type: 'close') | Subscribes to **close** events of the socket connection. | 44| off(type: 'close') | Unsubscribes from **close** events of the socket connection. | 45| on(type: 'error') | Subscribes to **error** events of the socket connection. | 46| off(type: 'error') | Unsubscribes from **error** events of the socket connection. | 47| on(type: 'listening') | Subscribes to **listening** events of the UDP socket connection. | 48| off(type: 'listening') | Unsubscribes from **listening** events of the UDP socket connection. | 49| on(type: 'connect') | Subscribes to **connect** events of the TCP socket connection. | 50| off(type: 'connect') | Unsubscribes from **connect** events of the TCP socket connection. | 51 52TLS socket connection functions are mainly provided by the **tls_socket** module. The following table describes the related APIs. 53 54| API | Description | 55| ---------------------------- | ---------------------------------------------------------- | 56| constructTLSSocketInstance() | Creates a **TLSSocket** object. | 57| bind() | Binds the IP address and port number. | 58| close(type: 'error') | Closes a socket connection. | 59| connect() | Sets up a connection to the specified IP address and port number. | 60| getCertificate() | Obtains an object representing the local certificate. | 61| getCipherSuite() | Obtains a list containing information about the negotiated cipher suite. | 62| getProtocol() | Obtains a string containing the SSL/TLS protocol version negotiated for the current connection. | 63| getRemoteAddress() | Obtains the peer address of the TLS socket connection. | 64| getRemoteCertificate() | Obtains an object representing a peer certificate. | 65| getSignatureAlgorithms() | Obtains a list containing signature algorithms shared between the server and client, in descending order of priority.| 66| getState() | Obtains the TLS socket connection status. | 67| off(type: 'close') | Unsubscribes from **close** events of the TLS socket connection. | 68| off(type: 'error') | Unsubscribes from **error** events of the TLS socket connection. | 69| off(type: 'message') | Unsubscribes from **message** events of the TLS socket connection. | 70| on(type: 'close') | Subscribes to **close** events of the TLS socket connection. | 71| on(type: 'error') | Subscribes to **error** events of the TLS socket connection. | 72| on(type: 'message') | Subscribes to **message** events of the TLS socket connection. | 73| send() | Sends data. | 74| setExtraOptions() | Sets other properties of the TLS socket connection. | 75 76## Transmitting Data over TCP Socket or UDP Socket Connections 77 78The implementation is similar for UDP socket and TCP socket connections. The following uses data transmission over a TCP socket connection as an example. 79 801. Import the required **socket** module. 81 822. Create a TCP socket connection. A **TCPSocket** object is returned. 83 843. (Optional) Subscribe to TCP socket connection events. 85 864. Bind the IP address and port number. The port number can be specified or randomly allocated by the system. 87 885. Sets up a connection to the specified IP address and port number. 89 906. Send data over the connection. 91 927. Enable the TCP socket connection to be automatically closed after use. 93 94```js 95import socket from "@ohos.net.socket"; 96import { BusinessError } from "@ohos.base"; 97 98class SocketInfo { 99 message: ArrayBuffer = new ArrayBuffer(1); 100 remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 101} 102// Create a TCP socket connection. A TCPSocket object is returned. 103let tcp = socket.constructTCPSocketInstance(); 104tcp.on('message', (value: SocketInfo) => { 105 console.log("on message") 106 let buffer = value.message 107 let dataView = new DataView(buffer) 108 let str = "" 109 for (let i = 0; i < dataView.byteLength; ++i) { 110 str += String.fromCharCode(dataView.getUint8(i)) 111 } 112 console.log("on connect received:" + str) 113}); 114tcp.on('connect', () => { 115 console.log("on connect") 116}); 117tcp.on('close', () => { 118 console.log("on close") 119}); 120 121// Bind the local IP address and port number. 122let ipAddress : socket.NetAddress = {} as socket.NetAddress 123ipAddress.address = "192.168.xxx.xxx" 124ipAddress.port = 1234 125tcp.bind(ipAddress, (err: BusinessError) => { 126 if (err) { 127 console.log('bind fail'); 128 return; 129 } 130 console.log('bind success'); 131 132 // Set up a connection to the specified IP address and port number. 133 ipAddress.address = "192.168.xxx.xxx" 134 ipAddress.port = 5678 135 136 let tcpConnect : socket.TCPConnectOptions = {} as socket.TCPConnectOptions 137 tcpConnect.address = ipAddress 138 tcpConnect.timeout = 6000 139 140 tcp.connect(tcpConnect, (err: BusinessError) => { 141 if (err) { 142 console.log('connect fail'); 143 return; 144 } 145 console.log('connect success'); 146 // Send data over the connection. 147 let tcpSendOptions : socket.TCPSendOptions = {} as socket.TCPSendOptions 148 tcpSendOptions.data = 'Hello, server!' 149 tcp.send(tcpSendOptions, (err: BusinessError) => { 150 if (err) { 151 console.log('send fail'); 152 return; 153 } 154 console.log('send success'); 155 }) 156 }); 157}); 158 159// Enable the socket connection to be automatically closed after use. Then, unsubscribe from events of the connection. 160setTimeout(() => { 161 tcp.close((err: BusinessError) => { 162 console.log('close socket.') 163 }); 164 tcp.off('message'); 165 tcp.off('connect'); 166 tcp.off('close'); 167}, 30 * 1000); 168``` 169 170## Transmitting Data over TCP Socket Server Connections 171 172### How to Develop 173 174The TCP socket server connection process is described as follows: 175 1761. Import the required **socket** module. 1772. Create a TCP socket server connection. A **TCPSocketServer** object is returned. 1783. Bind the local IP address and port, and listen for and accept TCP socket connections established over the socket. 1794. Subscribe to **connect** events of the **TCPSocketServer** object to listen for client connection status changes. 1805. Set up a connection between the client and the server. A **TCPSocketConnection** object is returned. 1816. Subscribe to events of the **TCPSocketConnection** object, and send data to the client through the **TCPSocketConnection** object. 1827. Close the connection between the client and the server. 1838. Unsubscribe from events of the **TCPSocketConnection** and **TCPSocketServer** objects. 184 185```js 186import socket from "@ohos.net.socket"; 187import { BusinessError } from "@ohos.base"; 188// Create a TCP socket server connection. A TCPSocketServer object is returned. 189let tcpServer = socket.constructTCPSocketServerInstance(); 190// Bind the local IP address and port number for listening. 191 192let ipAddress : socket.NetAddress = {} as socket.NetAddress 193ipAddress.address = "192.168.xxx.xxx" 194ipAddress.port = 4651 195tcpServer.listen(ipAddress, (err: BusinessError) => { 196 if (err) { 197 console.log("listen fail"); 198 return; 199 } 200 console.log("listen success"); 201}); 202 203class SocketInfo { 204 message: ArrayBuffer = new ArrayBuffer(1); 205 remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 206} 207// Subscribe to connect events of the TCPSocketServer object. 208tcpServer.on("connect", (client: socket.TCPSocketConnection) => { 209 // Subscribe to events of the TCPSocketConnection object. 210 client.on("close", () => { 211 console.log("on close success"); 212 }); 213 client.on("message", (value: SocketInfo) => { 214 let buffer = value.message; 215 let dataView = new DataView(buffer); 216 let str = ""; 217 for (let i = 0; i < dataView.byteLength; ++i) { 218 str += String.fromCharCode(dataView.getUint8(i)); 219 } 220 console.log("received message--:" + str); 221 console.log("received address--:" + value.remoteInfo.address); 222 console.log("received family--:" + value.remoteInfo.family); 223 console.log("received port--:" + value.remoteInfo.port); 224 console.log("received size--:" + value.remoteInfo.size); 225 }); 226 227 // Send data to the client. 228 let tcpSendOptions : socket.TCPSendOptions = {} as socket.TCPSendOptions 229 tcpSendOptions.data = 'Hello, client!' 230 client.send(tcpSendOptions, (err: BusinessError) => { 231 if (err) { 232 console.log("send fail"); 233 return; 234 } 235 console.log("send success"); 236 }); 237 238 // Close the connection between the client and the server. 239 client.close((err: BusinessError) => { 240 if (err) { 241 console.log("close fail"); 242 return; 243 } 244 console.log("close success"); 245 }); 246 247 // Unsubscribe from events of the TCPSocketConnection object. 248 setTimeout(() => { 249 client.off("message"); 250 client.off("close"); 251 }, 10 * 1000); 252}); 253 254// Unsubscribe from events of the TCPSocketServer object. 255setTimeout(() => { 256 tcpServer.off("connect"); 257}, 30 * 1000); 258``` 259 260## Implementing Encrypted Data Transmission over TLS Socket Connections 261 262### How to Develop 263 264The TLS socket connection process on the client is described as follows: 265 2661. Import the required **socket** module. 267 2682. Bind the IP address and port number of the server. 269 2703. For two-way authentication, upload the client CA certificate and digital certificate. For one-way authentication, upload the client CA certificate. 271 2724. Create a TLS socket connection. A **TLSsocket** object is returned. 273 2745. (Optional) Subscribe to TLS socket connection events. 275 2766. Send data over the connection. 277 2787. Enable the TLS socket connection to be automatically closed after use. 279 280```js 281import socket from "@ohos.net.socket"; 282import { BusinessError } from "@ohos.base"; 283 284class SocketInfo { 285 message: ArrayBuffer = new ArrayBuffer(1); 286 remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 287} 288// Create a TLS socket connection (for two-way authentication). A TLSSocket object is returned. 289let tlsTwoWay = socket.constructTLSSocketInstance(); 290// Subscribe to TLS socket connection events. 291tlsTwoWay.on('message', (value: SocketInfo) => { 292 console.log("on message") 293 let buffer = value.message 294 let dataView = new DataView(buffer) 295 let str = "" 296 for (let i = 0; i < dataView.byteLength; ++i) { 297 str += String.fromCharCode(dataView.getUint8(i)) 298 } 299 console.log("on connect received:" + str) 300}); 301tlsTwoWay.on('connect', () => { 302 console.log("on connect") 303}); 304tlsTwoWay.on('close', () => { 305 console.log("on close") 306}); 307 308// Bind the local IP address and port number. 309let ipAddress : socket.NetAddress = {} as socket.NetAddress; 310ipAddress.address = "192.168.xxx.xxx" 311ipAddress.port = 4512 312tlsTwoWay.bind(ipAddress, (err: BusinessError) => { 313 if (err) { 314 console.log('bind fail'); 315 return; 316 } 317 console.log('bind success'); 318}); 319 320ipAddress.address = "192.168.xxx.xxx" 321ipAddress.port = 1234 322 323let tlsSecureOption : socket.TLSSecureOptions = {} as socket.TLSSecureOptions; 324tlsSecureOption.key = "xxxx" 325tlsSecureOption.cert = "xxxx" 326tlsSecureOption.ca = ["xxxx"] 327tlsSecureOption.password = "xxxx" 328tlsSecureOption.protocols = [socket.Protocol.TLSv12] 329tlsSecureOption.useRemoteCipherPrefer = true 330tlsSecureOption.signatureAlgorithms = "rsa_pss_rsae_sha256:ECDSA+SHA256" 331tlsSecureOption.cipherSuite = "AES256-SHA256" 332 333let tlsTwoWayConnectOption : socket.TLSConnectOptions = {} as socket.TLSConnectOptions; 334tlsSecureOption.key = "xxxx" 335tlsTwoWayConnectOption.address = ipAddress 336tlsTwoWayConnectOption.secureOptions = tlsSecureOption 337tlsTwoWayConnectOption.ALPNProtocols = ["spdy/1", "http/1.1"] 338 339// Set up a connection. 340tlsTwoWay.connect(tlsTwoWayConnectOption, () => { 341 console.error("connect function"); 342}); 343 344// Enable the socket connection to be automatically closed after use. Then, unsubscribe from events of the connection. 345tlsTwoWay.close((err: BusinessError) => { 346 if (err) { 347 console.log("close callback error = " + err); 348 } else { 349 console.log("close success"); 350 } 351 tlsTwoWay.off('message'); 352 tlsTwoWay.off('connect'); 353 tlsTwoWay.off('close'); 354}); 355 356// Create a TLS socket connection (for one-way authentication). A TLSsocket object is returned. 357let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication 358 359// Subscribe to TLS socket connection events. 360tlsTwoWay.on('message', (value: SocketInfo) => { 361 console.log("on message") 362 let buffer = value.message 363 let dataView = new DataView(buffer) 364 let str = "" 365 for (let i = 0; i < dataView.byteLength; ++i) { 366 str += String.fromCharCode(dataView.getUint8(i)) 367 } 368 console.log("on connect received:" + str) 369}); 370tlsTwoWay.on('connect', () => { 371 console.log("on connect") 372}); 373tlsTwoWay.on('close', () => { 374 console.log("on close") 375}); 376 377// Bind the local IP address and port number. 378ipAddress.address = "192.168.xxx.xxx" 379ipAddress.port = 5445 380tlsOneWay.bind(ipAddress, (err:BusinessError) => { 381 if (err) { 382 console.log('bind fail'); 383 return; 384 } 385 console.log('bind success'); 386}); 387 388ipAddress.address = "192.168.xxx.xxx" 389ipAddress.port = 8789 390let tlsOneWaySecureOption : socket.TLSSecureOptions = {} as socket.TLSSecureOptions 391tlsOneWaySecureOption.ca = ["xxxx", "xxxx"] 392tlsOneWaySecureOption.cipherSuite = "AES256-SHA256" 393 394let tlsOneWayConnectOptions: socket.TLSConnectOptions = {} as socket.TLSConnectOptions 395tlsOneWayConnectOptions.address = ipAddress 396tlsOneWayConnectOptions.secureOptions = tlsOneWaySecureOption 397 398// Set up a connection. 399tlsOneWay.connect(tlsOneWayConnectOptions, () => { 400 console.error("connect function"); 401}); 402 403// Enable the socket connection to be automatically closed after use. Then, unsubscribe from events of the connection. 404tlsTwoWay.close((err: BusinessError) => { 405 if (err) { 406 console.log("close callback error = " + err); 407 } else { 408 console.log("close success"); 409 } 410 tlsTwoWay.off('message'); 411 tlsTwoWay.off('connect'); 412 tlsTwoWay.off('close'); 413}); 414``` 415