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. If 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. When 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.
6
7If an error occurs in any of the preceding processes, the client will receive a callback of the **error** event.
8
9## Available APIs
10
11The 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.
12
13| API             | Description                                     |
14| ------------------ | ----------------------------------------- |
15| createWebSocket()  | Creates a WebSocket connection.                   |
16| connect()          | Establishes a WebSocket connection to a given URL.      |
17| send()             | Sends data through the WebSocket connection.               |
18| close()            | Closes a WebSocket connection.                       |
19| on(type: 'open')   | Enables listening for **open** events of a WebSocket connection.                 |
20| off(type: 'open')   | Disables listening for **open** events of a WebSocket connection.            |
21| on(type: 'message') | Enables listening for **message** events of a WebSocket connection.     |
22| off(type: 'message') | Disables listening for **message** events of a WebSocket connection.|
23| on(type: 'close')   | Enables listening for **close** events of a WebSocket connection.                |
24| off(type: 'close') | Disables listening for **close** events of a WebSocket connection.               |
25| on(type: 'error')  | Enables listening for **error** events of a WebSocket connection.                |
26| off(type: 'error') | Disables listening for **error** events of a WebSocket connection.            |
27
28## How to Develop
29
301. Import the required webSocket module.
31
322. Create a **WebSocket** object.
33
343. (Optional) Subscribe to WebSocket **open**, **message**, **close**, and **error** events.
35
364. Establish a WebSocket connection to a given URL.
37
385. Close the WebSocket connection if it is no longer needed.
39
40```js
41import { webSocket } from '@kit.NetworkKit';
42import { BusinessError } from '@kit.BasicServicesKit';
43
44let defaultIpAddress = "ws://";
45let ws = webSocket.createWebSocket();
46ws.on('open', (err: BusinessError, value: Object) => {
47  console.log("on open, status:" + JSON.stringify(value));
48  // When receiving the on('open') event, the client can use the send() API to communicate with the server.
49  ws.send("Hello, server!", (err: BusinessError, value: boolean) => {
50    if (!err) {
51      console.log("Message sent successfully");
52    } else {
53      console.log("Failed to send the message. Err:" + JSON.stringify(err));
54    }
55  });
56});
57ws.on('message', (err: BusinessError, value: string | ArrayBuffer) => {
58  console.log("on message, message:" + value);
59  // When receiving the `bye` message (the actual message name may differ) from the server, the client proactively disconnects from the server.
60  if (value === 'bye') {
61    ws.close((err: BusinessError, value: boolean) => {
62      if (!err) {
63        console.log("Connection closed successfully");
64      } else {
65        console.log("Failed to close the connection. Err: " + JSON.stringify(err));
66      }
67    });
68  }
69});
70ws.on('close', (err: BusinessError, value: webSocket.CloseResult) => {
71  console.log("on close, code is " + value.code + ", reason is " + value.reason);
72});
73ws.on('error', (err: BusinessError) => {
74  console.log("on error, error:" + JSON.stringify(err));
75});
76ws.connect(defaultIpAddress, (err: BusinessError, value: boolean) => {
77  if (!err) {
78    console.log("Connected successfully");
79  } else {
80    console.log("Connection failed. Err:" + JSON.stringify(err));
81  }
82});
83```
84