• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
91import socket from '@ohos.net.socket'
92
93// Create a TCPSocket object.
94let tcp = socket.constructTCPSocketInstance();
95
96// Subscribe to TCPSocket connection events.
97tcp.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});
107tcp.on('connect', () => {
108  console.log("on connect")
109});
110tcp.on('close', () => {
111  console.log("on close")
112});
113
114// Bind the local IP address and port number.
115let bindAddress = {
116  address: '192.168.xx.xx',
117  port: 1234, // Bound port, for example, 1234.
118  family: 1
119};
120tcp.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.
156setTimeout(() => {
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
187import socket from '@ohos.net.socket'
188
189// Create a TLSSocket connection (for two-way authentication).
190let tlsTwoWay = socket.constructTLSSocketInstance();
191
192// Subscribe to TLSSocket connection events.
193tlsTwoWay.on('message', value => {
194  console.log("on message")
195  let buffer = value.message
196  let dataView = new DataView(buffer)
197  let str = ""
198  for (let i = 0; i < dataView.byteLength; ++i) {
199    str += String.fromCharCode(dataView.getUint8(i))
200  }
201  console.log("on connect received:" + str)
202});
203tlsTwoWay.on('connect', () => {
204  console.log("on connect")
205});
206tlsTwoWay.on('close', () => {
207  console.log("on close")
208});
209
210// Bind the local IP address and port number.
211tlsTwoWay.bind({ address: '192.168.xxx.xxx', port: xxxx, family: 1 }, err => {
212  if (err) {
213    console.log('bind fail');
214    return;
215  }
216  console.log('bind success');
217});
218
219// Set the communication parameters.
220let options = {
221  ALPNProtocols: ["spdy/1", "http/1.1"],
222
223  // Set up a connection to the specified IP address and port number.
224  address: {
225    address: "192.168.xx.xxx",
226    port: xxxx, // Port
227    family: 1,
228  },
229
230  // Set the parameters used for authentication during communication.
231  secureOptions: {
232    key: "xxxx",                            // Key
233    cert: "xxxx",                           // Digital certificate
234    ca: ["xxxx"],                           // CA certificate
235    passwd: "xxxx",                         // Password for generating the key
236    protocols: [socket.Protocol.TLSv12],    // Communication protocol
237    useRemoteCipherPrefer: true,            // Whether to preferentially use the peer cipher suite
238    signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",    // Signature algorithm
239    cipherSuite: "AES256-SHA256",           // Cipher suite
240  },
241};
242
243// Set up a connection.
244tlsTwoWay.connect(options, (err, data) => {
245  console.error(err);
246  console.log(data);
247});
248
249// Enable the TCPSocket connection to be automatically closed after use. Then, disable listening for TCPSocket connection events.
250tlsTwoWay.close((err) => {
251  if (err) {
252    console.log("close callback error = " + err);
253  } else {
254    console.log("close success");
255  }
256  tlsTwoWay.off('message');
257  tlsTwoWay.off('connect');
258  tlsTwoWay.off('close');
259});
260
261// Create a TLSSocket connection (for one-way authentication).
262let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
263
264// Subscribe to TLSSocket connection events.
265tlsTwoWay.on('message', value => {
266  console.log("on message")
267  let buffer = value.message
268  let dataView = new DataView(buffer)
269  let str = ""
270  for (let i = 0; i < dataView.byteLength; ++i) {
271    str += String.fromCharCode(dataView.getUint8(i))
272  }
273  console.log("on connect received:" + str)
274});
275tlsTwoWay.on('connect', () => {
276  console.log("on connect")
277});
278tlsTwoWay.on('close', () => {
279  console.log("on close")
280});
281
282// Bind the local IP address and port number.
283tlsOneWay.bind({ address: '192.168.xxx.xxx', port: xxxx, family: 1 }, err => {
284  if (err) {
285    console.log('bind fail');
286    return;
287  }
288  console.log('bind success');
289});
290
291// Set the communication parameters.
292let oneWayOptions = {
293  address: {
294    address: "192.168.xxx.xxx",
295    port: xxxx,
296    family: 1,
297  },
298  secureOptions: {
299    ca: ["xxxx","xxxx"],            // CA certificate
300    cipherSuite: "AES256-SHA256",   // Cipher suite
301  },
302};
303
304// Set up a connection.
305tlsOneWay.connect(oneWayOptions, (err, data) => {
306  console.error(err);
307  console.log(data);
308});
309
310// Enable the TCPSocket connection to be automatically closed after use. Then, disable listening for TCPSocket connection events.
311tlsTwoWay.close((err) => {
312  if (err) {
313    console.log("close callback error = " + err);
314  } else {
315    console.log("close success");
316  }
317  tlsTwoWay.off('message');
318  tlsTwoWay.off('connect');
319  tlsTwoWay.off('close');
320});
321```
322