• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# WebSocket Connection
2
3## When to Use
4
5You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the **createWebSocket()** API to create a **WebSocket** object and then use the **connect()** API to connect to the server.
6If the connection is successful, the client will receive a callback of the **open** event. Then, the client can communicate with the server using the **send()** API.
7When the server sends a message to the client, the client will receive a callback of the **message** event. If the client no longer needs this connection, it can call the **close()** API to disconnect from the server. Then, the client will receive a callback of the **close** event.
8
9If an error occurs in any of the preceding processes, the client will receive a callback of the **error** event.
10
11## Available APIs
12
13The WebSocket connection function is mainly implemented by the WebSocket module. To use related APIs, you must declare the **ohos.permission.INTERNET** permission. The following table describes the related APIs.
14
15| API| Description|
16| -------- | -------- |
17| createWebSocket() | Creates a WebSocket connection.|
18| connect() | Establishes a WebSocket connection to a given URL.|
19| send() | Sends data through the WebSocket connection.|
20| close() | Closes a WebSocket connection.|
21| on(type: 'open') | Enables listening for **open** events of a WebSocket connection.|
22| off(type: 'open') | Disables listening for **open** events of a WebSocket connection.|
23| on(type: 'message') | Enables listening for **message** events of a WebSocket connection.|
24| off(type: 'message') | Disables listening for **message** events of a WebSocket connection.|
25| on(type: 'close') | Enables listening for **close** events of a WebSocket connection.|
26| off(type: 'close') | Disables listening for **close** events of a WebSocket connection.|
27| on(type: 'error') | Enables listening for **error** events of a WebSocket connection.|
28| off(type: 'error') | Disables listening for **error** events of a WebSocket connection.|
29
30## How to Develop
31
321. Import the required webSocket module.
33
342. Create a **WebSocket** object.
35
363. (Optional) Subscribe to WebSocket **open**, **message**, **close**, and **error** events.
37
384. Establish a WebSocket connection to a given URL.
39
405. Close the WebSocket connection if it is no longer needed.
41
42```js
43import webSocket from '@ohos.net.webSocket';
44
45var defaultIpAddress = "ws://";
46let ws = webSocket.createWebSocket();
47ws.on('open', (err, value) => {
48  console.log("on open, status:" + JSON.stringify(value));
49  // When receiving the on('open') event, the client can use the send() API to communicate with the server.
50  ws.send("Hello, server!", (err, value) => {
51    if (!err) {
52      console.log("Message sent successfully");
53    } else {
54      console.log("Failed to send the message. Err:" + JSON.stringify(err));
55    }
56  });
57});
58ws.on('message', (err, value) => {
59  console.log("on message, message:" + value);
60  // When receiving the `bye` message (the actual message name may differ) from the server, the client proactively disconnects from the server.
61  if (value === 'bye') {
62    ws.close((err, value) => {
63      if (!err) {
64        console.log("Connection closed successfully");
65      } else {
66        console.log("Failed to close the connection. Err: " + JSON.stringify(err));
67      }
68    });
69  }
70});
71ws.on('close', (err, value) => {
72  console.log("on close, code is " + value.code + ", reason is " + value.reason);
73});
74ws.on('error', (err) => {
75  console.log("on error, error:" + JSON.stringify(err));
76});
77ws.connect(defaultIpAddress, (err, value) => {
78  if (!err) {
79    console.log("Connected successfully");
80  } else {
81    console.log("Connection failed. Err:" + JSON.stringify(err));
82  }
83});
84```
85