js-apis-webSocket.md 23.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 8 9 10 11 12 13 14

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.

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 已提交
15
```js
S
shawn_he 已提交
16 17 18
import webSocket from '@ohos.net.webSocket';
```

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

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

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

## webSocket.createWebSocket

createWebSocket\(\): WebSocket

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 已提交
73
**Return value**
S
shawn_he 已提交
74 75 76 77 78 79 80

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

**Example**

S
shawn_he 已提交
81
```js
S
shawn_he 已提交
82 83 84 85 86 87
let ws = webSocket.createWebSocket();
```


## WebSocket

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

### connect

connect\(url: string, callback: AsyncCallback<boolean\>\): void

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 已提交
96
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
97 98 99 100 101 102 103 104 105 106

**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 已提交
107 108 109 110 111 112
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 401     | Parameter error.        |
| 201     | Permission denied.      |
S
shawn_he 已提交
113 114 115

**Example**

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


### connect

connect\(url: string, options: WebSocketRequestOptions, callback: AsyncCallback<boolean\>\): void

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 已提交
135
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
136 137 138 139 140 141 142 143 144 145 146

**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 已提交
147 148 149 150 151 152
**Error codes**

| ID| Error Message                |
| ------- | ----------------------- |
| 401     | Parameter error.        |
| 201     | Permission denied.      |
S
shawn_he 已提交
153 154 155

**Example**

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


### connect

connect\(url: string, options?: WebSocketRequestOptions\): Promise<boolean\>

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 已提交
180
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
181 182 183 184 185 186 187 188 189 190

**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 已提交
191
**Return value**
S
shawn_he 已提交
192 193 194 195 196

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

S
shawn_he 已提交
197 198 199 200 201 202 203
**Error codes**

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

S
shawn_he 已提交
204 205
**Example**

S
shawn_he 已提交
206
```js
S
shawn_he 已提交
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
let ws = webSocket.createWebSocket();
let url = "ws://"
let promise = ws.connect(url);
promise.then((value) => {
	console.log("connect success")
}).catch((err) => {
	console.log("connect fail, error:" + JSON.stringify(err))
});
```


### send

send\(data: string | ArrayBuffer, callback: AsyncCallback<boolean\>\): void

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

S
shawn_he 已提交
224
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
225 226 227 228 229 230 231 232 233 234

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

**Parameters**

| Name  | Type                    | Mandatory| Description        |
| -------- | ------------------------ | ---- | ------------ |
| data     | string \| ArrayBuffer <sup>8+</sup> | Yes  | Data to send.|
| callback | AsyncCallback\<boolean\> | Yes  | Callback used to return the result.  |

S
shawn_he 已提交
235 236 237 238 239 240 241
**Error codes**

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

S
shawn_he 已提交
242 243
**Example**

S
shawn_he 已提交
244
```js
S
shawn_he 已提交
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
let ws = webSocket.createWebSocket();
let url = "ws://"
ws.connect(url, (err, value) => {
	ws.send("Hello, server!", (err, value) => {
		if (!err) {
			console.log("send success");
		} else {
			console.log("send fail, err:" + JSON.stringify(err))
		}
	});
});
```


### send

send\(data: string | ArrayBuffer\): Promise<boolean\>

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

S
shawn_he 已提交
265
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
266 267 268 269 270 271 272 273 274

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

**Parameters**

| Name| Type  | Mandatory| Description        |
| ------ | ------ | ---- | ------------ |
| data     | string \| ArrayBuffer <sup>8+</sup> | Yes  | Data to send.|

S
shawn_he 已提交
275
**Return value**
S
shawn_he 已提交
276 277 278 279 280

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

S
shawn_he 已提交
281 282 283 284 285 286 287
**Error codes**

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

S
shawn_he 已提交
288 289
**Example**

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


### close

close\(callback: AsyncCallback<boolean\>\): void

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

S
shawn_he 已提交
310
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
311 312 313 314 315 316 317 318 319

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

**Parameters**

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

S
shawn_he 已提交
320 321 322 323 324 325 326
**Error codes**

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

S
shawn_he 已提交
327 328
**Example**

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


### close

close\(options: WebSocketCloseOptions, callback: AsyncCallback<boolean\>\): void

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 已提交
348
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
349 350 351 352 353 354 355 356 357 358

**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 已提交
359 360 361 362 363 364 365
**Error codes**

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

S
shawn_he 已提交
366 367
**Example**

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


### close

close\(options?: WebSocketCloseOptions\): Promise<boolean\>

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

S
shawn_he 已提交
390
**Required permissions**: ohos.permission.INTERNET
S
shawn_he 已提交
391 392 393 394 395 396 397 398 399

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

**Parameters**

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

S
shawn_he 已提交
400
**Return value**
S
shawn_he 已提交
401 402 403 404 405

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

S
shawn_he 已提交
406 407 408 409 410 411 412
**Error codes**

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

S
shawn_he 已提交
413 414
**Example**

S
shawn_he 已提交
415
```js
S
shawn_he 已提交
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
let ws = webSocket.createWebSocket();
let url = "ws://"
let promise = ws.close({
	code: 1000,
	reason: "your reason"
});
promise.then((value) => {
	console.log("close success")
}).catch((err) => {
	console.log("close fail, err is " + JSON.stringify(err))
});
```


### on\('open'\)

on\(type: 'open', callback: AsyncCallback<Object\>\): void

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 已提交
448
```js
S
shawn_he 已提交
449 450
let ws = webSocket.createWebSocket();
ws.on('open', (err, value) => {
S
shawn_he 已提交
451
	console.log("on open, status:" + value['status'] + ", message:" + value['message']);
S
shawn_he 已提交
452 453 454 455 456 457 458 459 460 461
});
```


### off\('open'\)

off\(type: 'open', callback?: AsyncCallback<Object\>\): void

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

S
shawn_he 已提交
462
>**NOTE**
S
shawn_he 已提交
463 464 465 466 467 468 469 470 471 472 473 474 475
>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.

**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 486 487 488 489 490
}
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);
```


### on\('message'\)

on\(type: 'message', callback: AsyncCallback<string | ArrayBuffer\>\): void

S
shawn_he 已提交
491
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 已提交
492

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

**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 已提交
507
```js
S
shawn_he 已提交
508 509 510 511 512 513 514 515 516 517 518
let ws = webSocket.createWebSocket();
ws.on('message', (err, value) => {
	console.log("on message, message:" + value);
});
```


### off\('message'\)

off\(type: 'message', callback?: AsyncCallback<string | ArrayBuffer\>\): void

S
shawn_he 已提交
519
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 已提交
520

S
shawn_he 已提交
521
>**NOTE**
S
shawn_he 已提交
522 523 524 525 526 527 528 529 530 531 532 533 534 535
>The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 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.

**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 已提交
536
```js
S
shawn_he 已提交
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
let ws = webSocket.createWebSocket();
ws.off('message');
```


### on\('close'\)

on\(type: 'close', callback: AsyncCallback<\{ code: number, reason: string \}\>\): void

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.|
| callback | AsyncCallback<{ code: number, reason: string }> | Yes  | Callback used to return the result.                    |

**Example**

S
shawn_he 已提交
559
```js
S
shawn_he 已提交
560 561
let ws = webSocket.createWebSocket();
ws.on('close', (err, value) => {
S
shawn_he 已提交
562
	console.log("on close, code is " + value.code + ", reason is " + value.reason);
S
shawn_he 已提交
563 564 565 566 567 568 569 570 571 572
});
```


### off\('close'\)

off\(type: 'close', callback?: AsyncCallback<\{ code: number, reason: string \}\>\): void

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

S
shawn_he 已提交
573
>**NOTE**
S
shawn_he 已提交
574 575 576 577 578 579 580 581 582 583 584 585 586
>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.

**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.|
| callback | AsyncCallback<{ code: number, reason: string }> | No  | Callback used to return the result.                    |

**Example**

S
shawn_he 已提交
587
```js
S
shawn_he 已提交
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
let ws = webSocket.createWebSocket();
ws.off('close');
```


### on\('error'\)

on\(type: 'error', callback: ErrorCallback\): void

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.|
| callback | ErrorCallback | Yes  | Callback used to return the result.                     |

**Example**

S
shawn_he 已提交
610
```js
S
shawn_he 已提交
611 612 613 614 615 616 617 618 619 620 621 622 623
let ws = webSocket.createWebSocket();
ws.on('error', (err) => {
	console.log("on error, error:" + JSON.stringify(err))
});
```


### off\('error'\)

off\(type: 'error', callback?: ErrorCallback\): void

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

S
shawn_he 已提交
624
>**NOTE**
S
shawn_he 已提交
625 626 627 628 629 630 631 632 633 634 635 636 637
>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.

**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 已提交
638
```js
S
shawn_he 已提交
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 666 667 668 669 670 671 672 673
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 已提交
674 675 676 677 678
| 1000      | Normally closed.          |
| 1001      | Connection closed by the server.    |
| 1002      | Incorrect protocol.          |
| 1003      | Data unable to be processed.|
| 1004~1015 | Reserved.            |