websocket-connection.md 3.9 KB
Newer Older
S
shawn_he 已提交
1 2 3 4 5
# WebSocket Connection


## Use Cases

S
shawn_he 已提交
6
You 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.
S
shawn_he 已提交
7 8 9 10 11 12 13 14

If an error occurs in any of the preceding processes, the client will receive a callback of the **error** event.


## Available APIs

The 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.

15
| API | Description |
S
shawn_he 已提交
16
| -------- | -------- |
17 18 19 20
| createWebSocket() | Creates a WebSocket connection. |
| connect() | Establishes a WebSocket connection to a given URL. |
| send() | Sends data through the WebSocket connection. |
| close() | Closes a WebSocket connection. |
S
shawn_he 已提交
21 22 23 24 25 26 27 28
| on(type: 'open') | Enables listening for **open** events of a WebSocket connection. |
| off(type: 'open') | Disables listening for **open** events of a WebSocket connection. |
| on(type: 'message') | Enables listening for **message** events of a WebSocket connection. |
| off(type: 'message') | Disables listening for **message** events of a WebSocket connection. |
| on(type: 'close') | Enables listening for **close** events of a WebSocket connection. |
| off(type: 'close') | Disables listening for **close** events of a WebSocket connection. |
| on(type: 'error') | Enables listening for **error** events of a WebSocket connection. |
| off(type: 'error') | Disables listening for **error** events of a WebSocket connection. |
S
shawn_he 已提交
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52


## How to Develop

1. Import the required WebSocket module.

2. Create a **WebSocket** object.

3. (Optional) Subscribe to WebSocket open, message, close, and error events.

4. Establish a WebSocket connection to a given URL.

5. Close the WebSocket connection if it is no longer needed.
   
   ```js
   import webSocket from '@ohos.net.webSocket';
   
   var defaultIpAddress = "ws://";
   let ws = webSocket.createWebSocket();
   ws.on('open', (err, value) => {
       console.log("on open, status:" + JSON.stringify(value));
       // When receiving the on('open') event, the client can use the send() API to communicate with the server.
       ws.send("Hello, server!", (err, value) => {
           if (!err) {
S
shawn_he 已提交
53
               console.log("Message sent successfully");
S
shawn_he 已提交
54
           } else {
S
shawn_he 已提交
55
               console.log("Failed to send the message. Err:" + JSON.stringify(err));
S
shawn_he 已提交
56 57 58 59 60 61 62 63 64
           }
       });
   });
   ws.on('message', (err, value) => {
       console.log("on message, message:" + value);
       // When receiving the `bye` message (the actual message name may differ) from the server, the client proactively disconnects from the server.
       if (value === 'bye') {
           ws.close((err, value) => {
               if (!err) {
S
shawn_he 已提交
65
                   console.log("Connection closed successfully");
S
shawn_he 已提交
66
               } else {
S
shawn_he 已提交
67
                   console.log("Failed to close the connection. Err: " + JSON.stringify(err));
S
shawn_he 已提交
68 69 70 71 72 73 74 75 76 77 78 79
               }
           });
       }
   });
   ws.on('close', (err, value) => {
       console.log("on close, code is " + value.code + ", reason is " + value.reason);
   });
   ws.on('error', (err) => {
       console.log("on error, error:" + JSON.stringify(err));
   });
   ws.connect(defaultIpAddress, (err, value) => {
       if (!err) {
S
shawn_he 已提交
80
           console.log("Connected successfully");
S
shawn_he 已提交
81
       } else {
S
shawn_he 已提交
82
           console.log("Connection failed. Err:" + JSON.stringify(err));
S
shawn_he 已提交
83 84 85
       }
   });
   ```