js-apis-webSocket.md 24.1 KB
Newer Older
S
shawn_he 已提交
1
# # @ohos.net.webSocket (WebSocket Connection)
S
shawn_he 已提交
2

S
shawn_he 已提交
3
> **NOTE**
S
shawn_he 已提交
4
>
S
shawn_he 已提交
5 6
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.

S
shawn_he 已提交
7

S
shawn_he 已提交
8 9 10
You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the [createWebSocket](#websocketcreatewebsocket) API to create a [WebSocket](#websocket) object and then use the [connect](#connect) API to connect to the server.
If the connection is successful, the client will receive a callback of the [open](#onopen) event. Then, the client can communicate with the server using the [send](#send) API.
When the server sends a message to the client, the client will receive a callback of the [message](#onmessage) event. If the client no longer needs this connection, it can call the [close](#close) API to disconnect from the server. Then, the client will receive a callback of the [close](#onclose) event.
S
shawn_he 已提交
11 12 13 14 15

If an error occurs in any of the preceding processes, the client will receive a callback of the [error](#onerror) event.

## Modules to Import

S
shawn_he 已提交
16
```js
S
shawn_he 已提交
17 18 19
import webSocket from '@ohos.net.webSocket';
```

S
shawn_he 已提交
20
## Examples
S
shawn_he 已提交
21

S
shawn_he 已提交
22
```js
S
shawn_he 已提交
23 24
import webSocket from '@ohos.net.webSocket';

S
shawn_he 已提交
25
let defaultIpAddress = "ws://";
S
shawn_he 已提交
26 27
let ws = webSocket.createWebSocket();
ws.on('open', (err, value) => {
S
shawn_he 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40
  if (err != undefined) {
    console.log(JSON.stringify(err))
    return
  }
  console.log("on open, status:" + value['status'] + ", message:" + value['message']);
  // 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) {
      console.log("send success");
    } else {
      console.log("send fail, err:" + JSON.stringify(err));
    }
  });
S
shawn_he 已提交
41 42
});
ws.on('message', (err, value) => {
S
shawn_he 已提交
43 44 45 46 47 48 49 50 51 52 53
  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) {
        console.log("close success");
      } else {
        console.log("close fail, err is " + JSON.stringify(err));
      }
    });
  }
S
shawn_he 已提交
54 55
});
ws.on('close', (err, value) => {
S
shawn_he 已提交
56
  console.log("on close, code is " + value.code + ", reason is " + value.reason);
S
shawn_he 已提交
57 58
});
ws.on('error', (err) => {
S
shawn_he 已提交
59
  console.log("on error, error:" + JSON.stringify(err));
S
shawn_he 已提交
60 61
});
ws.connect(defaultIpAddress, (err, value) => {
S
shawn_he 已提交
62 63 64 65 66
  if (!err) {
    console.log("connect success");
  } else {
    console.log("connect fail, err:" + JSON.stringify(err));
  }
S
shawn_he 已提交
67 68 69
});
```

S
shawn_he 已提交
70
## webSocket.createWebSocket<sup>6+</sup>
S
shawn_he 已提交
71

S
shawn_he 已提交
72
createWebSocket(): WebSocket
S
shawn_he 已提交
73 74 75 76 77

Creates a WebSocket connection. You can use this API to create or close a WebSocket connection, send data over it, or enable or disable listening for the **open**, **close**, **message**, and **error** events.

**System capability**: SystemCapability.Communication.NetStack

S
shawn_he 已提交
78
**Return value**
S
shawn_he 已提交
79 80 81 82 83 84 85

| Type                               | Description                                                        |
| :---------------------------------- | :----------------------------------------------------------- |
| [WebSocket](#websocket) | A **WebSocket** object, which contains the **connect**, **send**, **close**, **on**, or **off** method.|

**Example**

S
shawn_he 已提交
86
```js
S
shawn_he 已提交
87 88 89
let ws = webSocket.createWebSocket();
```

S
shawn_he 已提交
90
## WebSocket<sup>6+</sup>
S
shawn_he 已提交
91

S
shawn_he 已提交
92
Defines a **WebSocket** object. Before invoking WebSocket APIs, you need to call [webSocket.createWebSocket](#websocketcreatewebsocket) to create a **WebSocket** object.
S
shawn_he 已提交
93

S
shawn_he 已提交
94
### connect<sup>6+</sup>
S
shawn_he 已提交
95

S
shawn_he 已提交
96
connect(url: string, callback: AsyncCallback\<boolean\>): void
S
shawn_he 已提交
97 98 99

Initiates a WebSocket request to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result.

S
shawn_he 已提交
100 101 102
> **NOTE**
> You can listen to **error** events to obtain the operation result. If an error occurs, the error code 200 will be returned.

S
shawn_he 已提交
103
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
104 105 106 107 108 109 110 111 112 113

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                    | Mandatory| Description                        |
| -------- | ------------------------ | ---- | ---------------------------- |
| url      | string                   | Yes  | URL for establishing a WebSocket connection.|
| callback | AsyncCallback\<boolean\> | Yes  | Callback used to return the result.                  |

S
shawn_he 已提交
114 115 116 117 118 119
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 401     | Parameter error.        |
| 201     | Permission denied.      |
S
shawn_he 已提交
120 121 122

**Example**

S
shawn_he 已提交
123
```js
S
shawn_he 已提交
124 125 126
let ws = webSocket.createWebSocket();
let url = "ws://"
ws.connect(url, (err, value) => {
S
shawn_he 已提交
127 128 129 130 131
  if (!err) {
    console.log("connect success");
  } else {
    console.log("connect fail, err:" + JSON.stringify(err))
  }
S
shawn_he 已提交
132 133 134
});
```

S
shawn_he 已提交
135
### connect<sup>6+</sup>
S
shawn_he 已提交
136

S
shawn_he 已提交
137
connect(url: string, options: WebSocketRequestOptions, callback: AsyncCallback\<boolean\>): void
S
shawn_he 已提交
138 139 140

Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result.

S
shawn_he 已提交
141 142 143
> **NOTE**
> You can listen to **error** events to obtain the operation result. If an error occurs, the error code 200 will be returned.

S
shawn_he 已提交
144
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
145 146 147 148 149 150 151 152 153 154 155

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                    | Mandatory| Description                                                   |
| -------- | ------------------------ | ---- | ------------------------------------------------------- |
| url      | string                   | Yes  | URL for establishing a WebSocket connection.                           |
| options  | WebSocketRequestOptions  | Yes  | Request options. For details, see [WebSocketRequestOptions](#websocketrequestoptions).|
| callback | AsyncCallback\<boolean\> | Yes  | Callback used to return the result.                                             |

S
shawn_he 已提交
156 157 158 159 160 161
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 401     | Parameter error.        |
| 201     | Permission denied.      |
S
shawn_he 已提交
162 163 164

**Example**

S
shawn_he 已提交
165
```js
S
shawn_he 已提交
166 167 168
let ws = webSocket.createWebSocket();
let url = "ws://"
ws.connect(url, {
S
shawn_he 已提交
169 170 171 172
  header: {
    "key": "value",
    "key2": "value2"
  }
S
shawn_he 已提交
173
}, (err, value) => {
S
shawn_he 已提交
174 175 176 177 178
  if (!err) {
    console.log("connect success");
  } else {
    console.log("connect fail, err:" + JSON.stringify(err))
  }
S
shawn_he 已提交
179 180 181
});
```

S
shawn_he 已提交
182
### connect<sup>6+</sup>
S
shawn_he 已提交
183

S
shawn_he 已提交
184
connect(url: string, options?: WebSocketRequestOptions): Promise\<boolean\>
S
shawn_he 已提交
185 186 187

Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses a promise to return the result.

S
shawn_he 已提交
188 189 190
> **NOTE**
> You can listen to **error** events to obtain the operation result. If an error occurs, the error code 200 will be returned.

S
shawn_he 已提交
191
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
192 193 194 195 196 197 198 199 200 201

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name | Type                   | Mandatory| Description                                                   |
| ------- | ----------------------- | ---- | ------------------------------------------------------- |
| url     | string                  | Yes  | URL for establishing a WebSocket connection.                           |
| options | WebSocketRequestOptions | No  | Request options. For details, see [WebSocketRequestOptions](#websocketrequestoptions).|

S
shawn_he 已提交
202
**Return value**
S
shawn_he 已提交
203 204 205 206 207

| Type              | Description                             |
| :----------------- | :-------------------------------- |
| Promise\<boolean\> | Promise used to return the result.|

S
shawn_he 已提交
208 209 210 211 212 213 214
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 401     | Parameter error.        |
| 201     | Permission denied.      |

S
shawn_he 已提交
215 216
**Example**

S
shawn_he 已提交
217
```js
S
shawn_he 已提交
218 219 220 221
let ws = webSocket.createWebSocket();
let url = "ws://"
let promise = ws.connect(url);
promise.then((value) => {
S
shawn_he 已提交
222
  console.log("connect success")
S
shawn_he 已提交
223
}).catch((err) => {
S
shawn_he 已提交
224
  console.log("connect fail, error:" + JSON.stringify(err))
S
shawn_he 已提交
225 226 227
});
```

S
shawn_he 已提交
228
### send<sup>6+</sup>
S
shawn_he 已提交
229

S
shawn_he 已提交
230
send(data: string | ArrayBuffer, callback: AsyncCallback\<boolean\>): void
S
shawn_he 已提交
231 232 233

Sends data through a WebSocket connection. This API uses an asynchronous callback to return the result.

S
shawn_he 已提交
234
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
235 236 237 238 239 240 241

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                    | Mandatory| Description        |
| -------- | ------------------------ | ---- | ------------ |
S
shawn_he 已提交
242
| data     | string \| ArrayBuffer | Yes  | Data to send.<br>Only the string type is supported for API version 6 or earlier. Both the string and ArrayBuffer types are supported for API version 8 or later.|
S
shawn_he 已提交
243 244
| callback | AsyncCallback\<boolean\> | Yes  | Callback used to return the result.  |

S
shawn_he 已提交
245 246 247 248 249 250 251
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 401     | Parameter error.        |
| 201     | Permission denied.      |

S
shawn_he 已提交
252 253
**Example**

S
shawn_he 已提交
254
```js
S
shawn_he 已提交
255 256 257
let ws = webSocket.createWebSocket();
let url = "ws://"
ws.connect(url, (err, value) => {
S
shawn_he 已提交
258 259 260 261 262 263 264
  ws.send("Hello, server!", (err, value) => {
    if (!err) {
      console.log("send success");
    } else {
      console.log("send fail, err:" + JSON.stringify(err))
    }
  });
S
shawn_he 已提交
265 266 267
});
```

S
shawn_he 已提交
268
### send<sup>6+</sup>
S
shawn_he 已提交
269

S
shawn_he 已提交
270
send(data: string | ArrayBuffer): Promise\<boolean\>
S
shawn_he 已提交
271 272 273

Sends data through a WebSocket connection. This API uses a promise to return the result.

S
shawn_he 已提交
274
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
275 276 277 278 279 280 281

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name| Type  | Mandatory| Description        |
| ------ | ------ | ---- | ------------ |
S
shawn_he 已提交
282
| data     | string \| ArrayBuffer | Yes  | Data to send.<br>Only the string type is supported for API version 6 or earlier. Both the string and ArrayBuffer types are supported for API version 8 or later.|
S
shawn_he 已提交
283

S
shawn_he 已提交
284
**Return value**
S
shawn_he 已提交
285 286 287 288 289

| Type              | Description                             |
| :----------------- | :-------------------------------- |
| Promise\<boolean\> | Promise used to return the result.|

S
shawn_he 已提交
290 291 292 293 294 295 296
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 401     | Parameter error.        |
| 201     | Permission denied.      |

S
shawn_he 已提交
297 298
**Example**

S
shawn_he 已提交
299
```js
S
shawn_he 已提交
300 301 302
let ws = webSocket.createWebSocket();
let url = "ws://"
ws.connect(url, (err, value) => {
S
shawn_he 已提交
303 304 305 306 307 308
  let promise = ws.send("Hello, server!");
  promise.then((value) => {
    console.log("send success")
  }).catch((err) => {
    console.log("send fail, error:" + JSON.stringify(err))
  });
S
shawn_he 已提交
309 310 311
});
```

S
shawn_he 已提交
312
### close<sup>6+</sup>
S
shawn_he 已提交
313

S
shawn_he 已提交
314
close(callback: AsyncCallback\<boolean\>): void
S
shawn_he 已提交
315 316 317

Closes a WebSocket connection. This API uses an asynchronous callback to return the result.

S
shawn_he 已提交
318
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
319 320 321 322 323 324 325 326 327

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                    | Mandatory| Description      |
| -------- | ------------------------ | ---- | ---------- |
| callback | AsyncCallback\<boolean\> | Yes  | Callback used to return the result.|

S
shawn_he 已提交
328 329 330 331 332 333 334
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 401     | Parameter error.        |
| 201     | Permission denied.      |

S
shawn_he 已提交
335 336
**Example**

S
shawn_he 已提交
337
```js
S
shawn_he 已提交
338 339
let ws = webSocket.createWebSocket();
ws.close((err, value) => {
S
shawn_he 已提交
340 341 342 343 344
  if (!err) {
    console.log("close success")
  } else {
    console.log("close fail, err is " + JSON.stringify(err))
  }
S
shawn_he 已提交
345 346 347
});
```

S
shawn_he 已提交
348
### close<sup>6+</sup>
S
shawn_he 已提交
349

S
shawn_he 已提交
350
close(options: WebSocketCloseOptions, callback: AsyncCallback\<boolean\>): void
S
shawn_he 已提交
351 352 353

Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses an asynchronous callback to return the result.

S
shawn_he 已提交
354
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
355 356 357 358 359 360 361 362 363 364

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                    | Mandatory| Description                                                 |
| -------- | ------------------------ | ---- | ----------------------------------------------------- |
| options  | WebSocketCloseOptions    | Yes  | Request options. For details, see [WebSocketCloseOptions](#websocketcloseoptions).|
| callback | AsyncCallback\<boolean\> | Yes  | Callback used to return the result.                                           |

S
shawn_he 已提交
365 366 367 368 369 370 371
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 401     | Parameter error.        |
| 201     | Permission denied.      |

S
shawn_he 已提交
372 373
**Example**

S
shawn_he 已提交
374
```js
S
shawn_he 已提交
375 376
let ws = webSocket.createWebSocket();
ws.close({
S
shawn_he 已提交
377 378
  code: 1000,
  reason: "your reason"
S
shawn_he 已提交
379
}, (err, value) => {
S
shawn_he 已提交
380 381 382 383 384
  if (!err) {
    console.log("close success")
  } else {
    console.log("close fail, err is " + JSON.stringify(err))
  }
S
shawn_he 已提交
385 386 387
});
```

S
shawn_he 已提交
388
### close<sup>6+</sup>
S
shawn_he 已提交
389

S
shawn_he 已提交
390
close(options?: WebSocketCloseOptions): Promise\<boolean\>
S
shawn_he 已提交
391 392 393

Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses a promise to return the result.

S
shawn_he 已提交
394
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
395 396 397 398 399 400 401 402 403

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name | Type                 | Mandatory| Description                                                 |
| ------- | --------------------- | ---- | ----------------------------------------------------- |
| options | WebSocketCloseOptions | No  | Request options. For details, see [WebSocketCloseOptions](#websocketcloseoptions).|

S
shawn_he 已提交
404
**Return value**
S
shawn_he 已提交
405 406 407 408 409

| Type              | Description                             |
| :----------------- | :-------------------------------- |
| Promise\<boolean\> | Promise used to return the result.|

S
shawn_he 已提交
410 411 412 413 414 415 416
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 401     | Parameter error.        |
| 201     | Permission denied.      |

S
shawn_he 已提交
417 418
**Example**

S
shawn_he 已提交
419
```js
S
shawn_he 已提交
420 421
let ws = webSocket.createWebSocket();
let promise = ws.close({
S
shawn_he 已提交
422 423
  code: 1000,
  reason: "your reason"
S
shawn_he 已提交
424 425
});
promise.then((value) => {
S
shawn_he 已提交
426
  console.log("close success")
S
shawn_he 已提交
427
}).catch((err) => {
S
shawn_he 已提交
428
  console.log("close fail, err is " + JSON.stringify(err))
S
shawn_he 已提交
429 430 431
});
```

S
shawn_he 已提交
432
### on('open')<sup>6+</sup>
S
shawn_he 已提交
433

S
shawn_he 已提交
434
on(type: 'open', callback: AsyncCallback\<Object\>): void
S
shawn_he 已提交
435 436 437 438 439 440 441 442 443 444 445 446 447 448

Enables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                   | Mandatory| Description                         |
| -------- | ----------------------- | ---- | ----------------------------- |
| type     | string                  | Yes  | Event type. <br />**open**: event indicating that a WebSocket connection has been opened.|
| callback | AsyncCallback\<Object\> | Yes  | Callback used to return the result.                   |

**Example**

S
shawn_he 已提交
449
```js
S
shawn_he 已提交
450 451
let ws = webSocket.createWebSocket();
ws.on('open', (err, value) => {
S
shawn_he 已提交
452
  console.log("on open, status:" + value['status'] + ", message:" + value['message']);
S
shawn_he 已提交
453 454 455
});
```

S
shawn_he 已提交
456
### off('open')<sup>6+</sup>
S
shawn_he 已提交
457

S
shawn_he 已提交
458
off(type: 'open', callback?: AsyncCallback\<Object\>): void
S
shawn_he 已提交
459 460 461

Disables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result.

S
shawn_he 已提交
462 463
> **NOTE**
> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
S
shawn_he 已提交
464 465 466 467 468 469 470 471 472 473 474 475

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                   | Mandatory| Description                         |
| -------- | ----------------------- | ---- | ----------------------------- |
| type     | string                  | Yes  | Event type. <br />**open**: event indicating that a WebSocket connection has been opened.|
| callback | AsyncCallback\<Object\> | No  | Callback used to return the result.                   |

**Example**

S
shawn_he 已提交
476
```js
S
shawn_he 已提交
477 478
let ws = webSocket.createWebSocket();
let callback1 = (err, value) => {
S
shawn_he 已提交
479
  console.log("on open, status:" + value['status'] + ", message:" + value['message']);
S
shawn_he 已提交
480 481 482 483 484 485
}
ws.on('open', callback1);
// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
ws.off('open', callback1);
```

S
shawn_he 已提交
486
### on('message')<sup>6+</sup>
S
shawn_he 已提交
487

S
shawn_he 已提交
488
on(type: 'message', callback: AsyncCallback\<string | ArrayBuffer\>): void
S
shawn_he 已提交
489

S
shawn_he 已提交
490
Enables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented.
S
shawn_he 已提交
491

S
shawn_he 已提交
492 493
> **NOTE**
> The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8).
S
shawn_he 已提交
494 495 496 497 498 499 500 501 502 503 504 505

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                   | Mandatory| Description                                        |
| -------- | ----------------------- | ---- | -------------------------------------------- |
| type     | string                  | Yes  | Event type.<br />**message**: event indicating that a message has been received from the server.|
| callback | AsyncCallback\<string \| ArrayBuffer <sup>8+</sup>\> | Yes  | Callback used to return the result.                                  |

**Example**

S
shawn_he 已提交
506
```js
S
shawn_he 已提交
507 508
let ws = webSocket.createWebSocket();
ws.on('message', (err, value) => {
S
shawn_he 已提交
509
  console.log("on message, message:" + value);
S
shawn_he 已提交
510 511 512
});
```

S
shawn_he 已提交
513
### off('message')<sup>6+</sup>
S
shawn_he 已提交
514

S
shawn_he 已提交
515
off(type: 'message', callback?: AsyncCallback\<string | ArrayBuffer\>): void
S
shawn_he 已提交
516

S
shawn_he 已提交
517
Disables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented.
S
shawn_he 已提交
518

S
shawn_he 已提交
519 520 521
> **NOTE**
> The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8).
> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
S
shawn_he 已提交
522 523 524 525 526 527 528 529 530 531 532 533

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                               | Mandatory| Description                                        |
| -------- | --------------------------------------------------- | ---- | -------------------------------------------- |
| type     | string                                              | Yes  | Event type.<br />**message**: event indicating that a message has been received from the server.|
| callback | AsyncCallback\<string \|ArrayBuffer <sup>8+</sup>\> | No  | Callback used to return the result.                                  |

**Example**

S
shawn_he 已提交
534
```js
S
shawn_he 已提交
535 536 537 538
let ws = webSocket.createWebSocket();
ws.off('message');
```

S
shawn_he 已提交
539
### on('close')<sup>6+</sup>
S
shawn_he 已提交
540

S
shawn_he 已提交
541
on(type: 'close', callback: AsyncCallback\<{ code: number, reason: string }\>): void
S
shawn_he 已提交
542 543 544 545 546 547 548 549 550 551

Enables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                           | Mandatory| Description                          |
| -------- | ----------------------------------------------- | ---- | ------------------------------ |
| type     | string                                          | Yes  | Event type. <br />**close**: event indicating that a WebSocket connection has been closed.|
S
shawn_he 已提交
552
| callback | AsyncCallback\<{ code: number, reason: string }\> | Yes  | Callback used to return the result.<br>**close** indicates the close error code and **reason** indicates the error code description.|
S
shawn_he 已提交
553 554 555

**Example**

S
shawn_he 已提交
556
```js
S
shawn_he 已提交
557 558
let ws = webSocket.createWebSocket();
ws.on('close', (err, value) => {
S
shawn_he 已提交
559
  console.log("on close, code is " + value.code + ", reason is " + value.reason);
S
shawn_he 已提交
560 561 562
});
```

S
shawn_he 已提交
563
### off('close')<sup>6+</sup>
S
shawn_he 已提交
564

S
shawn_he 已提交
565
off(type: 'close', callback?: AsyncCallback\<{ code: number, reason: string }\>): void
S
shawn_he 已提交
566 567 568

Disables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result.

S
shawn_he 已提交
569 570
> **NOTE**
> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
S
shawn_he 已提交
571 572 573 574 575 576 577 578

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type                                           | Mandatory| Description                          |
| -------- | ----------------------------------------------- | ---- | ------------------------------ |
| type     | string                                          | Yes  | Event type. <br />**close**: event indicating that a WebSocket connection has been closed.|
S
shawn_he 已提交
579
| callback | AsyncCallback\<{ code: number, reason: string }\> | No  | Callback used to return the result.<br>**close** indicates the close error code and **reason** indicates the error code description.|
S
shawn_he 已提交
580 581 582

**Example**

S
shawn_he 已提交
583
```js
S
shawn_he 已提交
584 585 586 587
let ws = webSocket.createWebSocket();
ws.off('close');
```

S
shawn_he 已提交
588
### on('error')<sup>6+</sup>
S
shawn_he 已提交
589

S
shawn_he 已提交
590
on(type: 'error', callback: ErrorCallback): void
S
shawn_he 已提交
591 592 593 594 595 596 597 598 599 600

Enables listening for the **error** events of a WebSocket connection. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type         | Mandatory| Description                           |
| -------- | ------------- | ---- | ------------------------------- |
| type     | string        | Yes  | Event type.<br />**error**: event indicating the WebSocket connection has encountered an error.|
S
shawn_he 已提交
601
| callback | ErrorCallback | Yes  | Callback used to return the result.<br>Common error code: 200|
S
shawn_he 已提交
602 603 604

**Example**

S
shawn_he 已提交
605
```js
S
shawn_he 已提交
606 607
let ws = webSocket.createWebSocket();
ws.on('error', (err) => {
S
shawn_he 已提交
608
  console.log("on error, error:" + JSON.stringify(err))
S
shawn_he 已提交
609 610 611
});
```

S
shawn_he 已提交
612
### off('error')<sup>6+</sup>
S
shawn_he 已提交
613

S
shawn_he 已提交
614
off(type: 'error', callback?: ErrorCallback): void
S
shawn_he 已提交
615 616 617

Disables listening for the **error** events of a WebSocket connection. This API uses an asynchronous callback to return the result.

S
shawn_he 已提交
618 619
> **NOTE**
> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
S
shawn_he 已提交
620 621 622 623 624 625 626 627 628 629 630 631

**System capability**: SystemCapability.Communication.NetStack

**Parameters**

| Name  | Type         | Mandatory| Description                           |
| -------- | ------------- | ---- | ------------------------------- |
| type     | string        | Yes  | Event type.<br />**error**: event indicating the WebSocket connection has encountered an error.|
| callback | ErrorCallback | No  | Callback used to return the result.                     |

**Example**

S
shawn_he 已提交
632
```js
S
shawn_he 已提交
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
let ws = webSocket.createWebSocket();
ws.off('error');
```

## WebSocketRequestOptions

Defines the optional parameters carried in the request for establishing a WebSocket connection.

**System capability**: SystemCapability.Communication.NetStack

| Name| Type  | Mandatory| Description                                                        |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| header | Object | No  | Header carrying optional parameters in the request for establishing a WebSocket connection. You can customize the parameter or leave it unspecified.|

## WebSocketCloseOptions

Defines the optional parameters carried in the request for closing a WebSocket connection.

**System capability**: SystemCapability.Communication.NetStack

| Name| Type  | Mandatory| Description                                                        |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| code   | number | No  | Error code. Set this parameter based on the actual situation. The default value is **1000**.|
| reason | string | No  | Error cause. Set this parameter based on the actual situation. The default value is an empty string ("").|

## Result Codes for Closing a WebSocket Connection

You can customize the result codes sent to the server. The result codes in the following table are for reference only.

**System capability**: SystemCapability.Communication.NetStack

| Value       | Description              |
| :-------- | :----------------- |
S
shawn_he 已提交
666 667 668 669 670
| 1000      | Normally closed.          |
| 1001      | Connection closed by the server.    |
| 1002      | Incorrect protocol.          |
| 1003      | Data unable to be processed.|
| 1004~1015 | Reserved.            |