1# # @ohos.net.webSocket (WebSocket Connection) 2 3> **NOTE** 4> 5> 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. 6 7 8You 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. 9 10If an error occurs in any of the preceding processes, the client will receive a callback of the [error](#onerror) event. 11 12 13## Modules to Import 14 15```js 16import webSocket from '@ohos.net.webSocket'; 17``` 18 19## Examples 20 21```js 22import webSocket from '@ohos.net.webSocket'; 23 24var defaultIpAddress = "ws://"; 25let ws = webSocket.createWebSocket(); 26ws.on('open', (err, value) => { 27 console.log("on open, status:" + value['status'] + ", message:" + value['message']); 28 // When receiving the on('open') event, the client can use the send() API to communicate with the server. 29 ws.send("Hello, server!", (err, value) => { 30 if (!err) { 31 console.log("send success"); 32 } else { 33 console.log("send fail, err:" + JSON.stringify(err)); 34 } 35 }); 36}); 37ws.on('message', (err, value) => { 38 console.log("on message, message:" + value); 39 // When receiving the `bye` message (the actual message name may differ) from the server, the client proactively disconnects from the server. 40 if (value === 'bye') { 41 ws.close((err, value) => { 42 if (!err) { 43 console.log("close success"); 44 } else { 45 console.log("close fail, err is " + JSON.stringify(err)); 46 } 47 }); 48 } 49}); 50ws.on('close', (err, value) => { 51 console.log("on close, code is " + value.code + ", reason is " + value.reason); 52}); 53ws.on('error', (err) => { 54 console.log("on error, error:" + JSON.stringify(err)); 55}); 56ws.connect(defaultIpAddress, (err, value) => { 57 if (!err) { 58 console.log("connect success"); 59 } else { 60 console.log("connect fail, err:" + JSON.stringify(err)); 61 } 62}); 63``` 64 65## webSocket.createWebSocket 66 67createWebSocket(): WebSocket 68 69Creates 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. 70 71**System capability**: SystemCapability.Communication.NetStack 72 73**Return value** 74 75| Type | Description | 76| :---------------------------------- | :----------------------------------------------------------- | 77| [WebSocket](#websocket) | A **WebSocket** object, which contains the **connect**, **send**, **close**, **on**, or **off** method.| 78 79**Example** 80 81```js 82let ws = webSocket.createWebSocket(); 83``` 84 85 86## WebSocket 87 88Defines a **WebSocket** object. Before invoking WebSocket APIs, you need to call [webSocket.createWebSocket](#websocketcreatewebsocket) to create a **WebSocket** object. 89 90### connect 91 92connect(url: string, callback: AsyncCallback\<boolean\>): void 93 94Initiates a WebSocket request to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result. 95 96**Required permissions**: ohos.permission.INTERNET 97 98**System capability**: SystemCapability.Communication.NetStack 99 100**Parameters** 101 102| Name | Type | Mandatory| Description | 103| -------- | ------------------------ | ---- | ---------------------------- | 104| url | string | Yes | URL for establishing a WebSocket connection.| 105| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result. | 106 107**Error codes** 108 109| ID| Error Message | 110| ------- | ----------------------- | 111| 401 | Parameter error. | 112| 201 | Permission denied. | 113 114**Example** 115 116```js 117let ws = webSocket.createWebSocket(); 118let url = "ws://" 119ws.connect(url, (err, value) => { 120 if (!err) { 121 console.log("connect success"); 122 } else { 123 console.log("connect fail, err:" + JSON.stringify(err)) 124 } 125}); 126``` 127 128 129### connect 130 131connect(url: string, options: WebSocketRequestOptions, callback: AsyncCallback\<boolean\>): void 132 133Initiates 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. 134 135**Required permissions**: ohos.permission.INTERNET 136 137**System capability**: SystemCapability.Communication.NetStack 138 139**Parameters** 140 141| Name | Type | Mandatory| Description | 142| -------- | ------------------------ | ---- | ------------------------------------------------------- | 143| url | string | Yes | URL for establishing a WebSocket connection. | 144| options | WebSocketRequestOptions | Yes | Request options. For details, see [WebSocketRequestOptions](#websocketrequestoptions).| 145| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result. | 146 147**Error codes** 148 149| ID| Error Message | 150| ------- | ----------------------- | 151| 401 | Parameter error. | 152| 201 | Permission denied. | 153 154**Example** 155 156```js 157let ws = webSocket.createWebSocket(); 158let url = "ws://" 159ws.connect(url, { 160 header: { 161 "key": "value", 162 "key2": "value2" 163 } 164}, (err, value) => { 165 if (!err) { 166 console.log("connect success"); 167 } else { 168 console.log("connect fail, err:" + JSON.stringify(err)) 169 } 170}); 171``` 172 173 174### connect 175 176connect(url: string, options?: WebSocketRequestOptions): Promise\<boolean\> 177 178Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses a promise to return the result. 179 180**Required permissions**: ohos.permission.INTERNET 181 182**System capability**: SystemCapability.Communication.NetStack 183 184**Parameters** 185 186| Name | Type | Mandatory| Description | 187| ------- | ----------------------- | ---- | ------------------------------------------------------- | 188| url | string | Yes | URL for establishing a WebSocket connection. | 189| options | WebSocketRequestOptions | No | Request options. For details, see [WebSocketRequestOptions](#websocketrequestoptions).| 190 191**Return value** 192 193| Type | Description | 194| :----------------- | :-------------------------------- | 195| Promise\<boolean\> | Promise used to return the result.| 196 197**Error codes** 198 199| ID| Error Message | 200| ------- | ----------------------- | 201| 401 | Parameter error. | 202| 201 | Permission denied. | 203 204**Example** 205 206```js 207let ws = webSocket.createWebSocket(); 208let url = "ws://" 209let promise = ws.connect(url); 210promise.then((value) => { 211 console.log("connect success") 212}).catch((err) => { 213 console.log("connect fail, error:" + JSON.stringify(err)) 214}); 215``` 216 217 218### send 219 220send(data: string | ArrayBuffer, callback: AsyncCallback\<boolean\>): void 221 222Sends data through a WebSocket connection. This API uses an asynchronous callback to return the result. 223 224**Required permissions**: ohos.permission.INTERNET 225 226**System capability**: SystemCapability.Communication.NetStack 227 228**Parameters** 229 230| Name | Type | Mandatory| Description | 231| -------- | ------------------------ | ---- | ------------ | 232| 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.| 233| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result. | 234 235**Error codes** 236 237| ID| Error Message | 238| ------- | ----------------------- | 239| 401 | Parameter error. | 240| 201 | Permission denied. | 241 242**Example** 243 244```js 245let ws = webSocket.createWebSocket(); 246let url = "ws://" 247ws.connect(url, (err, value) => { 248 ws.send("Hello, server!", (err, value) => { 249 if (!err) { 250 console.log("send success"); 251 } else { 252 console.log("send fail, err:" + JSON.stringify(err)) 253 } 254 }); 255}); 256``` 257 258 259### send 260 261send(data: string | ArrayBuffer): Promise\<boolean\> 262 263Sends data through a WebSocket connection. This API uses a promise to return the result. 264 265**Required permissions**: ohos.permission.INTERNET 266 267**System capability**: SystemCapability.Communication.NetStack 268 269**Parameters** 270 271| Name| Type | Mandatory| Description | 272| ------ | ------ | ---- | ------------ | 273| 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.| 274 275**Return value** 276 277| Type | Description | 278| :----------------- | :-------------------------------- | 279| Promise\<boolean\> | Promise used to return the result.| 280 281**Error codes** 282 283| ID| Error Message | 284| ------- | ----------------------- | 285| 401 | Parameter error. | 286| 201 | Permission denied. | 287 288**Example** 289 290```js 291let ws = webSocket.createWebSocket(); 292let url = "ws://" 293ws.connect(url, (err, value) => { 294 let promise = ws.send("Hello, server!"); 295 promise.then((value) => { 296 console.log("send success") 297 }).catch((err) => { 298 console.log("send fail, error:" + JSON.stringify(err)) 299 }); 300}); 301``` 302 303 304### close 305 306close(callback: AsyncCallback\<boolean\>): void 307 308Closes a WebSocket connection. This API uses an asynchronous callback to return the result. 309 310**Required permissions**: ohos.permission.INTERNET 311 312**System capability**: SystemCapability.Communication.NetStack 313 314**Parameters** 315 316| Name | Type | Mandatory| Description | 317| -------- | ------------------------ | ---- | ---------- | 318| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result.| 319 320**Error codes** 321 322| ID| Error Message | 323| ------- | ----------------------- | 324| 401 | Parameter error. | 325| 201 | Permission denied. | 326 327**Example** 328 329```js 330let ws = webSocket.createWebSocket(); 331let url = "ws://" 332ws.close((err, value) => { 333 if (!err) { 334 console.log("close success") 335 } else { 336 console.log("close fail, err is " + JSON.stringify(err)) 337 } 338}); 339``` 340 341 342### close 343 344close(options: WebSocketCloseOptions, callback: AsyncCallback\<boolean\>): void 345 346Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses an asynchronous callback to return the result. 347 348**Required permissions**: ohos.permission.INTERNET 349 350**System capability**: SystemCapability.Communication.NetStack 351 352**Parameters** 353 354| Name | Type | Mandatory| Description | 355| -------- | ------------------------ | ---- | ----------------------------------------------------- | 356| options | WebSocketCloseOptions | Yes | Request options. For details, see [WebSocketCloseOptions](#websocketcloseoptions).| 357| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result. | 358 359**Error codes** 360 361| ID| Error Message | 362| ------- | ----------------------- | 363| 401 | Parameter error. | 364| 201 | Permission denied. | 365 366**Example** 367 368```js 369let ws = webSocket.createWebSocket(); 370let url = "ws://" 371ws.close({ 372 code: 1000, 373 reason: "your reason" 374}, (err, value) => { 375 if (!err) { 376 console.log("close success") 377 } else { 378 console.log("close fail, err is " + JSON.stringify(err)) 379 } 380}); 381``` 382 383 384### close 385 386close(options?: WebSocketCloseOptions): Promise\<boolean\> 387 388Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses a promise to return the result. 389 390**Required permissions**: ohos.permission.INTERNET 391 392**System capability**: SystemCapability.Communication.NetStack 393 394**Parameters** 395 396| Name | Type | Mandatory| Description | 397| ------- | --------------------- | ---- | ----------------------------------------------------- | 398| options | WebSocketCloseOptions | No | Request options. For details, see [WebSocketCloseOptions](#websocketcloseoptions).| 399 400**Return value** 401 402| Type | Description | 403| :----------------- | :-------------------------------- | 404| Promise\<boolean\> | Promise used to return the result.| 405 406**Error codes** 407 408| ID| Error Message | 409| ------- | ----------------------- | 410| 401 | Parameter error. | 411| 201 | Permission denied. | 412 413**Example** 414 415```js 416let ws = webSocket.createWebSocket(); 417let url = "ws://" 418let promise = ws.close({ 419 code: 1000, 420 reason: "your reason" 421}); 422promise.then((value) => { 423 console.log("close success") 424}).catch((err) => { 425 console.log("close fail, err is " + JSON.stringify(err)) 426}); 427``` 428 429 430### on('open') 431 432on(type: 'open', callback: AsyncCallback\<Object\>): void 433 434Enables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result. 435 436**System capability**: SystemCapability.Communication.NetStack 437 438**Parameters** 439 440| Name | Type | Mandatory| Description | 441| -------- | ----------------------- | ---- | ----------------------------- | 442| type | string | Yes | Event type. <br />**open**: event indicating that a WebSocket connection has been opened.| 443| callback | AsyncCallback\<Object\> | Yes | Callback used to return the result. | 444 445 446**Example** 447 448```js 449let ws = webSocket.createWebSocket(); 450ws.on('open', (err, value) => { 451 console.log("on open, status:" + value['status'] + ", message:" + value['message']); 452}); 453``` 454 455 456### off('open') 457 458off(type: 'open', callback?: AsyncCallback\<Object\>): void 459 460Disables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result. 461 462>**NOTE** 463>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. 464 465**System capability**: SystemCapability.Communication.NetStack 466 467**Parameters** 468 469| Name | Type | Mandatory| Description | 470| -------- | ----------------------- | ---- | ----------------------------- | 471| type | string | Yes | Event type. <br />**open**: event indicating that a WebSocket connection has been opened.| 472| callback | AsyncCallback\<Object\> | No | Callback used to return the result. | 473 474**Example** 475 476```js 477let ws = webSocket.createWebSocket(); 478let callback1 = (err, value) => { 479 console.log("on open, status:" + value['status'] + ", message:" + value['message']); 480} 481ws.on('open', callback1); 482// 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. 483ws.off('open', callback1); 484``` 485 486 487### on('message') 488 489on(type: 'message', callback: AsyncCallback\<string | ArrayBuffer\>): void 490 491Enables 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. 492 493>**NOTE** 494>The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8). 495 496**System capability**: SystemCapability.Communication.NetStack 497 498**Parameters** 499 500| Name | Type | Mandatory| Description | 501| -------- | ----------------------- | ---- | -------------------------------------------- | 502| type | string | Yes | Event type.<br />**message**: event indicating that a message has been received from the server.| 503| callback | AsyncCallback\<string \| ArrayBuffer <sup>8+</sup>\> | Yes | Callback used to return the result. | 504 505**Example** 506 507```js 508let ws = webSocket.createWebSocket(); 509ws.on('message', (err, value) => { 510 console.log("on message, message:" + value); 511}); 512``` 513 514 515### off('message') 516 517off(type: 'message', callback?: AsyncCallback\<string | ArrayBuffer\>): void 518 519Disables 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. 520 521>**NOTE** 522>The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8). 523>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. 524 525**System capability**: SystemCapability.Communication.NetStack 526 527**Parameters** 528 529| Name | Type | Mandatory| Description | 530| -------- | --------------------------------------------------- | ---- | -------------------------------------------- | 531| type | string | Yes | Event type.<br />**message**: event indicating that a message has been received from the server.| 532| callback | AsyncCallback\<string \|ArrayBuffer <sup>8+</sup>\> | No | Callback used to return the result. | 533 534**Example** 535 536```js 537let ws = webSocket.createWebSocket(); 538ws.off('message'); 539``` 540 541 542### on('close') 543 544on(type: 'close', callback: AsyncCallback\<{ code: number, reason: string }\>): void 545 546Enables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result. 547 548**System capability**: SystemCapability.Communication.NetStack 549 550**Parameters** 551 552| Name | Type | Mandatory| Description | 553| -------- | ----------------------------------------------- | ---- | ------------------------------ | 554| type | string | Yes | Event type. <br />**close**: event indicating that a WebSocket connection has been closed.| 555| 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.| 556 557**Example** 558 559```js 560let ws = webSocket.createWebSocket(); 561ws.on('close', (err, value) => { 562 console.log("on close, code is " + value.code + ", reason is " + value.reason); 563}); 564``` 565 566 567### off('close') 568 569off(type: 'close', callback?: AsyncCallback\<{ code: number, reason: string }\>): void 570 571Disables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result. 572 573>**NOTE** 574>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. 575 576**System capability**: SystemCapability.Communication.NetStack 577 578**Parameters** 579 580| Name | Type | Mandatory| Description | 581| -------- | ----------------------------------------------- | ---- | ------------------------------ | 582| type | string | Yes | Event type. <br />**close**: event indicating that a WebSocket connection has been closed.| 583| 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.| 584 585**Example** 586 587```js 588let ws = webSocket.createWebSocket(); 589ws.off('close'); 590``` 591 592 593### on('error') 594 595on(type: 'error', callback: ErrorCallback): void 596 597Enables listening for the **error** events of a WebSocket connection. This API uses an asynchronous callback to return the result. 598 599**System capability**: SystemCapability.Communication.NetStack 600 601**Parameters** 602 603| Name | Type | Mandatory| Description | 604| -------- | ------------- | ---- | ------------------------------- | 605| type | string | Yes | Event type.<br />**error**: event indicating the WebSocket connection has encountered an error.| 606| callback | ErrorCallback | Yes | Callback used to return the result. | 607 608**Example** 609 610```js 611let ws = webSocket.createWebSocket(); 612ws.on('error', (err) => { 613 console.log("on error, error:" + JSON.stringify(err)) 614}); 615``` 616 617 618### off('error') 619 620off(type: 'error', callback?: ErrorCallback): void 621 622Disables listening for the **error** events of a WebSocket connection. This API uses an asynchronous callback to return the result. 623 624>**NOTE** 625>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. 626 627**System capability**: SystemCapability.Communication.NetStack 628 629**Parameters** 630 631| Name | Type | Mandatory| Description | 632| -------- | ------------- | ---- | ------------------------------- | 633| type | string | Yes | Event type.<br />**error**: event indicating the WebSocket connection has encountered an error.| 634| callback | ErrorCallback | No | Callback used to return the result. | 635 636**Example** 637 638```js 639let ws = webSocket.createWebSocket(); 640ws.off('error'); 641``` 642 643 644## WebSocketRequestOptions 645 646Defines the optional parameters carried in the request for establishing a WebSocket connection. 647 648**System capability**: SystemCapability.Communication.NetStack 649 650| Name| Type | Mandatory| Description | 651| ------ | ------ | ---- | ------------------------------------------------------------ | 652| header | Object | No | Header carrying optional parameters in the request for establishing a WebSocket connection. You can customize the parameter or leave it unspecified.| 653 654 655## WebSocketCloseOptions 656 657Defines the optional parameters carried in the request for closing a WebSocket connection. 658 659**System capability**: SystemCapability.Communication.NetStack 660 661| Name| Type | Mandatory| Description | 662| ------ | ------ | ---- | ------------------------------------------------------------ | 663| code | number | No | Error code. Set this parameter based on the actual situation. The default value is **1000**.| 664| reason | string | No | Error cause. Set this parameter based on the actual situation. The default value is an empty string ("").| 665 666## Result Codes for Closing a WebSocket Connection 667 668You can customize the result codes sent to the server. The result codes in the following table are for reference only. 669 670**System capability**: SystemCapability.Communication.NetStack 671 672| Value | Description | 673| :-------- | :----------------- | 674| 1000 | Normally closed. | 675| 1001 | Connection closed by the server. | 676| 1002 | Incorrect protocol. | 677| 1003 | Data unable to be processed.| 678| 1004~1015 | Reserved. | 679