js-apis-webSocket.md 21.8 KB
Newer Older
S
shawn_he 已提交
1
# WebSocket Connection
S
shawn_he 已提交
2 3 4 5 6 7 8 9 10 11 12 13

>![](public_sys-resources/icon-note.gif) **NOTE:**
>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.
>

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

## Complete Example

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

var defaultIpAddress = "ws://";
let ws = webSocket.createWebSocket();
ws.on('open', (err, value) => {
S
shawn_he 已提交
26
    console.log("on open, status:" + value['status'] + ", message:" + value['message']);
S
shawn_he 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
    // 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);
    // 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));
            }
        });
    }
});
ws.on('close', (err, value) => {
S
shawn_he 已提交
50
    console.log("on close, code is " + value['code'] + ", reason is " + value['reason']);
S
shawn_he 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
});
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

**Return Value**

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

**Example**

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


## WebSocket

S
shawn_he 已提交
87
Defines a **WebSocket** object. Before invoking WebSocket APIs, you need to call [webSocket.createWebSocket](#websocketcreatewebsocket) to create a **WebSocket** object.
S
shawn_he 已提交
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108

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

**Required permission**: ohos.permission.INTERNET

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


**Example**

S
shawn_he 已提交
109
```js
S
shawn_he 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
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.

**Required permission**: ohos.permission.INTERNET

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


**Example**

S
shawn_he 已提交
143
```js
S
shawn_he 已提交
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
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.

**Required permission**: ohos.permission.INTERNET

**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).|

**Return Value**

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

**Example**

S
shawn_he 已提交
186
```js
S
shawn_he 已提交
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
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.

**Required permission**: ohos.permission.INTERNET

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

**Example**

S
shawn_he 已提交
217
```js
S
shawn_he 已提交
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
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.

**Required permission**: ohos.permission.INTERNET

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

**Parameters**

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

**Return Value**

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

**Example**

S
shawn_he 已提交
256
```js
S
shawn_he 已提交
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
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.

**Required permission**: ohos.permission.INTERNET

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

**Parameters**

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

**Example**

S
shawn_he 已提交
288
```js
S
shawn_he 已提交
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
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.

**Required permission**: ohos.permission.INTERNET

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

**Example**

S
shawn_he 已提交
320
```js
S
shawn_he 已提交
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
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.

**Required permission**: ohos.permission.INTERNET

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

**Parameters**

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

**Return Value**

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

**Example**

S
shawn_he 已提交
360
```js
S
shawn_he 已提交
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
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 已提交
393
```js
S
shawn_he 已提交
394 395
let ws = webSocket.createWebSocket();
ws.on('open', (err, value) => {
S
shawn_he 已提交
396
	console.log("on open, status:" + value['status'] + ", message:" + value['message']);
S
shawn_he 已提交
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
});
```


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

>![](public_sys-resources/icon-note.gif) **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.

**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 已提交
421
```js
S
shawn_he 已提交
422 423
let ws = webSocket.createWebSocket();
let callback1 = (err, value) => {
S
shawn_he 已提交
424
	console.log("on open, status:" + value['status'] + ", message:" + value['message']);
S
shawn_he 已提交
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
}
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

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

>![](public_sys-resources/icon-note.gif) **NOTE:**
>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 已提交
453
```js
S
shawn_he 已提交
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
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

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

>![](public_sys-resources/icon-note.gif) **NOTE:**
>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 已提交
482
```js
S
shawn_he 已提交
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
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 已提交
505
```js
S
shawn_he 已提交
506 507
let ws = webSocket.createWebSocket();
ws.on('close', (err, value) => {
S
shawn_he 已提交
508
	console.log("on close, code is " + value['code'] + ", reason is " + value['reason']);
S
shawn_he 已提交
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
});
```


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

>![](public_sys-resources/icon-note.gif) **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.

**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 已提交
534
```js
S
shawn_he 已提交
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
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 已提交
558
```js
S
shawn_he 已提交
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
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.

>![](public_sys-resources/icon-note.gif) **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.

**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 已提交
586
```js
S
shawn_he 已提交
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
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              |
| :-------- | :----------------- |
| 1000      | Normally closed          |
| 1001      | Connection closed by the server    |
| 1002      | Incorrect protocol          |
| 1003      | Data unable to be processed|
| 1004~1015 | Reserved            |