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 TLSSocket connections. The main application scenarios are as follows: 17 18- Implementing data transmission over TCP/UDPSocket connections 19- Implementing encrypted data transmission over TLSSocket connections 20 21## Available APIs 22 23For the complete list of APIs and example code, see [Socket Connection](../reference/apis/js-apis-socket.md). 24 25Socket connection functions are mainly implemented by the **socket** module. The following table describes the related APIs. 26 27| API| Description| 28| -------- | -------- | 29| constructUDPSocketInstance() | Creates a **UDPSocket** object.| 30| constructTCPSocketInstance() | Creates a **TCPSocket** object.| 31| bind() | Binds the IP address and port number.| 32| send() | Sends data.| 33| close() | Closes a Socket connection.| 34| getState() | Obtains the Socket connection status.| 35| connect() | Connects to the specified IP address and port. This function is supported only for TCP.| 36| 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.| 37| on(type: 'message') | Subscribes to **message** events of the Socket connection.| 38| off(type: 'message') | Unsubscribes from **message** events of the Socket connection.| 39| on(type: 'close') | Subscribes to **close** events of the Socket connection.| 40| off(type: 'close') | Unsubscribes from **close** events of the Socket connection.| 41| on(type: 'error') | Subscribes to **error** events of the Socket connection.| 42| off(type: 'error') | Unsubscribes from **error** events of the Socket connection.| 43| on(type: 'listening') | Subscribes to **listening** events of the UDPSocket connection. | 44| off(type: 'listening') | Unsubscribes from **listening** events of the UDPSocket connection. | 45| on(type: 'connect') | Subscribes to **connect** events of the TCPSocket connection. | 46| off(type: 'connect') | Unsubscribes from **connect** events of the TCPSocket connection.| 47 48TLSSocket connection functions are mainly provided by the **tls_socket** module. The following table describes the related APIs. 49 50| API| Description| 51| -------- | -------- | 52| constructTLSSocketInstance() | Creates a **TLSSocket** object.| 53| bind() | Binds the IP address and port number.| 54| close(type: 'error') | Closes a Socket connection.| 55| connect() | Sets up a connection to the specified IP address and port number.| 56| getCertificate() | Obtains an object representing the local certificate.| 57| getCipherSuite() | Obtains a list containing information about the negotiated cipher suite.| 58| getProtocol() | Obtains a string containing the SSL/TLS protocol version negotiated for the current connection.| 59| getRemoteAddress() | Obtains the peer address of the TLSSocket connection.| 60| getRemoteCertificate() | Obtains an object representing a peer certificate.| 61| getSignatureAlgorithms() | Obtains a list containing signature algorithms shared between the server and client, in descending order of priority.| 62| getState() | Obtains the TLSSocket connection status.| 63| off(type: 'close') | Unsubscribes from **close** events of the TLSSocket connection.| 64| off(type: 'error') | Unsubscribes from **error** events of the TLSSocket connection.| 65| off(type: 'message') | Unsubscribes from **message** events of the TLSSocket connection.| 66| on(type: 'close') | Subscribes to **close** events of the TLSSocket connection.| 67| on(type: 'error') | Subscribes to **error** events of the TLSSocket connection.| 68| on(type: 'message') | Subscribes to **message** events of the TLSSocket connection.| 69| send() | Sends data.| 70| setExtraOptions() | Sets other properties of the TLSSocket connection.| 71 72## Transmitting Data over TCP/UDPSocket Connections 73 74The implementation is similar for UDPSocket and TCPSocket connections. The following uses data transmission over a TCPSocket connection as an example. 75 761. Import the required **socket** module. 77 782. Create a **TCPSocket** object. 79 803. (Optional) Subscribe to TCPSocket connection events. 81 824. Bind the IP address and port number. The port number can be specified or randomly allocated by the system. 83 845. Set up a connection to the specified IP address and port number. 85 866. Send data. 87 887. Enable the TCPSocket connection to be automatically closed after use. 89 90 ```js 91 import socket from '@ohos.net.socket' 92 93 // Create a TCPSocket object. 94 let tcp = socket.constructTCPSocketInstance(); 95 96 // Subscribe to TCPSocket connection events. 97 tcp.on('message', value => { 98 console.log("on message") 99 let buffer = value.message 100 let dataView = new DataView(buffer) 101 let str = "" 102 for (let i = 0;i < dataView.byteLength; ++i) { 103 str += String.fromCharCode(dataView.getUint8(i)) 104 } 105 console.log("on connect received:" + str) 106 }); 107 tcp.on('connect', () => { 108 console.log("on connect") 109 }); 110 tcp.on('close', () => { 111 console.log("on close") 112 }); 113 114 // Bind the local IP address and port number. 115 let bindAddress = { 116 address: '192.168.xx.xx', 117 port: 1234, // Bound port, for example, 1234. 118 family: 1 119 }; 120 tcp.bind(bindAddress, err => { 121 if (err) { 122 console.log('bind fail'); 123 return; 124 } 125 console.log('bind success'); 126 127 // Set up a connection to the specified IP address and port number. 128 let connectAddress = { 129 address: '192.168.xx.xx', 130 port: 5678, // Connection port, for example, 5678. 131 family: 1 132 }; 133 tcp.connect({ 134 address: connectAddress, timeout: 6000 135 }, err => { 136 if (err) { 137 console.log('connect fail'); 138 return; 139 } 140 console.log('connect success'); 141 142 // Send data. 143 tcp.send({ 144 data: 'Hello, server!' 145 }, err => { 146 if (err) { 147 console.log('send fail'); 148 return; 149 } 150 console.log('send success'); 151 }) 152 }); 153 }); 154 155 // Enable the TCPSocket connection to be automatically closed after use. Then, disable listening for TCPSocket connection events. 156 setTimeout(() => { 157 tcp.close((err) => { 158 console.log('close socket.') 159 }); 160 tcp.off('message'); 161 tcp.off('connect'); 162 tcp.off('close'); 163 }, 30 * 1000); 164 ``` 165 166## Implementing encrypted data transmission over TLSSocket connections 167 168### How to Develop 169 170TLSSocket connection process on the client: 171 1721. Import the required **socket** module. 173 1742. Bind the IP address and port number of the server. 175 1763. For two-way authentication, upload the client CA certificate and digital certificate. For one-way authentication, upload the client CA certificate. 177 1784. Create a **TLSSocket** object. 179 1805. (Optional) Subscribe to TLSSocket connection events. 181 1826. Send data. 183 1847. Enable the TLSSocket connection to be automatically closed after use. 185 186```js 187// Create a TLSSocket connection (for two-way authentication). 188let tlsTwoWay = socket.constructTLSSocketInstance(); 189 190// Subscribe to TLSSocket connection events. 191tlsTwoWay.on('message', value => { 192 console.log("on message") 193 let buffer = value.message 194 let dataView = new DataView(buffer) 195 let str = "" 196 for (let i = 0; i < dataView.byteLength; ++i) { 197 str += String.fromCharCode(dataView.getUint8(i)) 198 } 199 console.log("on connect received:" + str) 200}); 201tlsTwoWay.on('connect', () => { 202 console.log("on connect") 203}); 204tlsTwoWay.on('close', () => { 205 console.log("on close") 206}); 207 208// Bind the local IP address and port number. 209tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { 210 if (err) { 211 console.log('bind fail'); 212 return; 213 } 214 console.log('bind success'); 215}); 216 217// Set the communication parameters. 218let options = { 219 ALPNProtocols: ["spdy/1", "http/1.1"], 220 221 // Set up a connection to the specified IP address and port number. 222 address: { 223 address: "192.168.xx.xxx", 224 port: xxxx, // Port 225 family: 1, 226 }, 227 228 // Set the parameters used for authentication during communication. 229 secureOptions: { 230 key: "xxxx", // Key 231 cert: "xxxx", // Digital certificate 232 ca: ["xxxx"], // CA certificate 233 passwd: "xxxx", // Password for generating the key 234 protocols: [socket.Protocol.TLSv12], // Communication protocol 235 useRemoteCipherPrefer: true, // Whether to preferentially use the peer cipher suite 236 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", // Signature algorithm 237 cipherSuite: "AES256-SHA256", // Cipher suite 238 }, 239}; 240 241// Set up a connection. 242tlsTwoWay.connect(options, (err, data) => { 243 console.error(err); 244 console.log(data); 245}); 246 247// Enable the TCPSocket connection to be automatically closed after use. Then, disable listening for TCPSocket connection events. 248tlsTwoWay.close((err) => { 249 if (err) { 250 console.log("close callback error = " + err); 251 } else { 252 console.log("close success"); 253 } 254 tlsTwoWay.off('message'); 255 tlsTwoWay.off('connect'); 256 tlsTwoWay.off('close'); 257}); 258 259// Create a TLSSocket connection (for one-way authentication). 260let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication 261 262// Subscribe to TLSSocket connection events. 263tlsTwoWay.on('message', value => { 264 console.log("on message") 265 let buffer = value.message 266 let dataView = new DataView(buffer) 267 let str = "" 268 for (let i = 0; i < dataView.byteLength; ++i) { 269 str += String.fromCharCode(dataView.getUint8(i)) 270 } 271 console.log("on connect received:" + str) 272}); 273tlsTwoWay.on('connect', () => { 274 console.log("on connect") 275}); 276tlsTwoWay.on('close', () => { 277 console.log("on close") 278}); 279 280// Bind the local IP address and port number. 281tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { 282 if (err) { 283 console.log('bind fail'); 284 return; 285 } 286 console.log('bind success'); 287}); 288 289// Set the communication parameters. 290let oneWayOptions = { 291 address: { 292 address: "192.168.xxx.xxx", 293 port: xxxx, 294 family: 1, 295 }, 296 secureOptions: { 297 ca: ["xxxx","xxxx"], // CA certificate 298 cipherSuite: "AES256-SHA256", // Cipher suite 299 }, 300}; 301 302// Set up a connection. 303tlsOneWay.connect(oneWayOptions, (err, data) => { 304 console.error(err); 305 console.log(data); 306}); 307 308// Enable the TCPSocket connection to be automatically closed after use. Then, disable listening for TCPSocket connection events. 309tlsTwoWay.close((err) => { 310 if (err) { 311 console.log("close callback error = " + err); 312 } else { 313 console.log("close success"); 314 } 315 tlsTwoWay.off('message'); 316 tlsTwoWay.off('connect'); 317 tlsTwoWay.off('close'); 318}); 319``` 320