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](#websocketcreatewebsocket6) API to create a [WebSocket](#websocket6) object and then use the [connect](#connect6) API to connect to the server. 9If the connection is successful, the client will receive a callback of the [open](#onopen6) event. Then, the client can communicate with the server using the [send](#send6) API. 10When the server sends a message to the client, the client will receive a callback of the [message](#onmessage6) event. If the client no longer needs this connection, it can call the [close](#close6) API to disconnect from the server. Then, the client will receive a callback of the [close](#onclose6) event. 11 12If an error occurs in any of the preceding processes, the client will receive a callback of the [error](#onerror6) event. 13 14## Modules to Import 15 16```ts 17import { webSocket } from '@kit.NetworkKit'; 18``` 19 20## Examples 21 22```ts 23import { webSocket } from '@kit.NetworkKit'; 24import { BusinessError } from '@kit.BasicServicesKit'; 25 26let defaultIpAddress = "ws://"; 27let ws = webSocket.createWebSocket(); 28ws.on('open', (err:BusinessError, value: Object) => { 29 if (err != undefined) { 30 console.log(JSON.stringify(err)); 31 return; 32 } 33 // When receiving the on('open') event, the client can use the send() API to communicate with the server. 34 ws.send("Hello, server!", (err: BusinessError, value: boolean) => { 35 if (!err) { 36 console.log("send success"); 37 } else { 38 console.log("send fail, err:" + JSON.stringify(err)); 39 } 40 }); 41}); 42ws.on('message',(error: BusinessError, value: string | ArrayBuffer) => { 43 console.log("on message, message:" + value); 44 // When receiving the `bye` message (the actual message name may differ) from the server, the client proactively disconnects from the server. 45 if (value === 'bye') { 46 ws.close((err: BusinessError, value: boolean) => { 47 if (!err) { 48 console.log("close success"); 49 } else { 50 console.log("close fail, err is " + JSON.stringify(err)); 51 } 52 }); 53 } 54}); 55ws.on('close', (err: BusinessError, value: webSocket.CloseResult) => { 56 console.log("on close, code is " + value.code + ", reason is " + value.reason); 57}); 58ws.on('error', (err: BusinessError) => { 59 console.log("on error, error:" + JSON.stringify(err)); 60}); 61ws.connect(defaultIpAddress, { 62 header:{ 63 name1: 'value1', 64 name2: 'value2', 65 name3: 'value3' 66 }, 67 proxy: { 68 host: '192.168.0.150', 69 port: 8888, 70 exclusionList: [] 71 }, 72 protocol: 'my-protocol', 73 }, (err: BusinessError, value: boolean) => { 74 if (!err) { 75 console.log("connect success"); 76 } else { 77 console.log("connect fail, err:" + JSON.stringify(err)); 78 } 79 ws.close((err: BusinessError) => { 80 if (!err) { 81 console.log("close success"); 82 } else { 83 console.log("close fail, err is " + JSON.stringify(err)); 84 } 85 }); 86}); 87``` 88 89## webSocket.createWebSocket<sup>6+</sup> 90 91createWebSocket(): WebSocket 92 93Creates 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. 94 95**Atomic service API**: This API can be used in atomic services since API version 11. 96 97**System capability**: SystemCapability.Communication.NetStack 98 99**Return value** 100 101| Type | Description | 102| :---------------------------------- | :----------------------------------------------------------- | 103| [WebSocket](#websocket6) | A **WebSocket** object, which contains the **connect**, **send**, **close**, **on**, or **off** method.| 104 105**Example** 106 107```ts 108let ws: webSocket.WebSocket = webSocket.createWebSocket(); 109``` 110 111## WebSocket<sup>6+</sup> 112 113Defines a **WebSocket** object. Before invoking WebSocket APIs, you need to call [webSocket.createWebSocket](#websocketcreatewebsocket6) to create a **WebSocket** object. 114 115### connect<sup>6+</sup> 116 117connect(url: string, callback: AsyncCallback\<boolean\>): void 118 119Initiates a WebSocket request to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result. 120 121> **NOTE** 122> You can listen to **error** events to obtain the operation result. If an error occurs, the error code 200 will be returned. 123 124**Required permissions**: ohos.permission.INTERNET 125 126**Atomic service API**: This API can be used in atomic services since API version 11. 127 128**System capability**: SystemCapability.Communication.NetStack 129 130**Parameters** 131 132| Name | Type | Mandatory| Description | 133| -------- | ------------------------ | ---- | ---------------------------- | 134| url | string | Yes | URL for establishing a WebSocket connection.| 135| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result. | 136 137**Error codes** 138 139| ID | Error Message | 140| --------------------- | ------------------------------------------ | 141| 401 | Parameter error. | 142| 201 | Permission denied. | 143| 2302001<sup>12+</sup> | Websocket url error. | 144| 2302002<sup>12+</sup> | Websocket certificate file does not exist. | 145| 2302003<sup>12+</sup> | Websocket connection already exists. | 146| 2302998<sup>12+</sup> | It is not allowed to access this domain. | 147| 2302999<sup>10+</sup> | Websocket other unknown error. | 148 149> **NOTE** 150> For details about the error codes, see [webSocket Error Codes](errorcode-net-http.md). 151 152**Example** 153 154```ts 155import { webSocket } from '@kit.NetworkKit'; 156import { BusinessError } from '@kit.BasicServicesKit'; 157 158let ws = webSocket.createWebSocket(); 159let url = "ws://"; 160ws.connect(url, (err: BusinessError, value: boolean) => { 161 if (!err) { 162 console.log("connect success"); 163 } else { 164 console.log("connect fail, err:" + JSON.stringify(err)); 165 } 166}); 167``` 168 169### connect<sup>6+</sup> 170 171connect(url: string, options: WebSocketRequestOptions, callback: AsyncCallback\<boolean\>): void 172 173Initiates 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. 174 175> **NOTE** 176> You can listen to **error** events to obtain the operation result. If an error occurs, the error code 200 will be returned. 177 178**Required permissions**: ohos.permission.INTERNET 179 180**Atomic service API**: This API can be used in atomic services since API version 11. 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 | Yes | Request options. For details, see [WebSocketRequestOptions](#websocketrequestoptions).| 190| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result. | 191 192**Error codes** 193 194| ID | Error Message | 195| --------------------- | ------------------------------------------ | 196| 401 | Parameter error. | 197| 201 | Permission denied. | 198| 2302001<sup>12+</sup> | Websocket url error. | 199| 2302002<sup>12+</sup> | Websocket certificate file does not exist. | 200| 2302003<sup>12+</sup> | Websocket connection already exists. | 201| 2302998<sup>12+</sup> | It is not allowed to access this domain. | 202| 2302999<sup>10+</sup> | Websocket other unknown error. | 203 204> **NOTE** 205> For details about the error codes, see [webSocket Error Codes](errorcode-net-http.md). 206 207**Example** 208 209```ts 210import { webSocket } from '@kit.NetworkKit'; 211import { BusinessError } from '@kit.BasicServicesKit'; 212 213let ws = webSocket.createWebSocket(); 214let options: webSocket.WebSocketRequestOptions | undefined; 215if (options !=undefined) { 216 options.header = { 217 name1: "value1", 218 name2: "value2", 219 name3: "value3" 220 }; 221 options.caPath = ""; 222} 223let url = "ws://" 224ws.connect(url, options, (err: BusinessError, value: Object) => { 225 if (!err) { 226 console.log("connect success"); 227 } else { 228 console.log("connect fail, err:" + JSON.stringify(err)) 229 } 230}); 231``` 232 233### connect<sup>6+</sup> 234 235connect(url: string, options?: WebSocketRequestOptions): Promise\<boolean\> 236 237Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses a promise to return the result. 238 239> **NOTE** 240> You can listen to **error** events to obtain the operation result. If an error occurs, the error code 200 will be returned. 241 242**Required permissions**: ohos.permission.INTERNET 243 244**Atomic service API**: This API can be used in atomic services since API version 11. 245 246**System capability**: SystemCapability.Communication.NetStack 247 248**Parameters** 249 250| Name | Type | Mandatory| Description | 251| ------- | ----------------------- | ---- | ------------------------------------------------------- | 252| url | string | Yes | URL for establishing a WebSocket connection. | 253| options | WebSocketRequestOptions | No | Request options. For details, see [WebSocketRequestOptions](#websocketrequestoptions).| 254 255**Return value** 256 257| Type | Description | 258| :----------------- | :-------------------------------- | 259| Promise\<boolean\> | Promise used to return the result.| 260 261**Error codes** 262 263| ID | Error Message | 264| --------------------- | ------------------------------------------ | 265| 401 | Parameter error. | 266| 201 | Permission denied. | 267| 2302001<sup>12+</sup> | Websocket url error. | 268| 2302002<sup>12+</sup> | Websocket certificate file does not exist. | 269| 2302003<sup>12+</sup> | Websocket connection already exists. | 270| 2302998<sup>12+</sup> | It is not allowed to access this domain. | 271| 2302999<sup>10+</sup> | Websocket other unknown error. | 272 273> **NOTE** 274> For details about the error codes, see [webSocket Error Codes](errorcode-net-http.md). 275 276**Example** 277 278```ts 279import { webSocket } from '@kit.NetworkKit'; 280 281let ws = webSocket.createWebSocket(); 282let url = "ws://" 283let promise = ws.connect(url); 284promise.then((value: boolean) => { 285 console.log("connect success") 286}).catch((err:string) => { 287 console.log("connect fail, error:" + JSON.stringify(err)) 288}); 289``` 290 291### send<sup>6+</sup> 292 293send(data: string | ArrayBuffer, callback: AsyncCallback\<boolean\>): void 294 295Sends data through a WebSocket connection. This API uses an asynchronous callback to return the result. 296 297**Required permissions**: ohos.permission.INTERNET 298 299**Atomic service API**: This API can be used in atomic services since API version 11. 300 301**System capability**: SystemCapability.Communication.NetStack 302 303**Parameters** 304 305| Name | Type | Mandatory| Description | 306| -------- | ------------------------ | ---- | ------------ | 307| 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.| 308| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result. | 309 310**Error codes** 311 312| ID| Error Message | 313| ------- | ----------------------- | 314| 401 | Parameter error. | 315| 201 | Permission denied. | 316 317**Example** 318 319```ts 320import { webSocket } from '@kit.NetworkKit'; 321import { BusinessError } from '@kit.BasicServicesKit'; 322 323let ws = webSocket.createWebSocket(); 324let url = "ws://" 325class OutValue { 326 status: number = 0 327 message: string = "" 328} 329ws.connect(url, (err: BusinessError, value: boolean) => { 330 if (!err) { 331 console.log("connect success"); 332 } else { 333 console.log("connect fail, err:" + JSON.stringify(err)) 334 } 335}); 336ws.on('open', (err: BusinessError, value: Object) => { 337 console.log("on open, status:" + (value as OutValue).status + ", message:" + (value as OutValue).message); 338 ws.send("Hello, server!", (err: BusinessError, value: boolean) => { 339 if (!err) { 340 console.log("send success"); 341 } else { 342 console.log("send fail, err:" + JSON.stringify(err)) 343 } 344 }); 345}); 346``` 347 348> **Description** 349> 350> The **send** API can be called only after an **open** event is listened. 351 352### send<sup>6+</sup> 353 354send(data: string | ArrayBuffer): Promise\<boolean\> 355 356Sends data through a WebSocket connection. This API uses a promise to return the result. 357 358**Required permissions**: ohos.permission.INTERNET 359 360**Atomic service API**: This API can be used in atomic services since API version 11. 361 362**System capability**: SystemCapability.Communication.NetStack 363 364**Parameters** 365 366| Name| Type | Mandatory| Description | 367| ------ | ------ | ---- | ------------ | 368| 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.| 369 370**Return value** 371 372| Type | Description | 373| :----------------- | :-------------------------------- | 374| Promise\<boolean\> | Promise used to return the result.| 375 376**Error codes** 377 378| ID| Error Message | 379| ------- | ----------------------- | 380| 401 | Parameter error. | 381| 201 | Permission denied. | 382 383**Example** 384 385```ts 386import { webSocket } from '@kit.NetworkKit'; 387import { BusinessError } from '@kit.BasicServicesKit'; 388 389let ws = webSocket.createWebSocket(); 390let url = "ws://" 391class OutValue { 392 status: number = 0 393 message: string = "" 394} 395ws.connect(url, (err: BusinessError, value: boolean) => { 396 if (!err) { 397 console.log("connect success"); 398 } else { 399 console.log("connect fail, err:" + JSON.stringify(err)) 400 } 401}); 402 403ws.on('open', (err: BusinessError, value: Object) => { 404 console.log("on open, status:" + (value as OutValue).status + ", message:" + (value as OutValue).message); 405 let promise = ws.send("Hello, server!"); 406 promise.then((value: boolean) => { 407 console.log("send success") 408 }).catch((err:string) => { 409 console.log("send fail, error:" + JSON.stringify(err)) 410 }); 411}); 412``` 413 414> **Description** 415> 416> The **send** API can be called only after an **open** event is listened. 417 418### close<sup>6+</sup> 419 420close(callback: AsyncCallback\<boolean\>): void 421 422Closes a WebSocket connection. This API uses an asynchronous callback to return the result. 423 424**Required permissions**: ohos.permission.INTERNET 425 426**Atomic service API**: This API can be used in atomic services since API version 11. 427 428**System capability**: SystemCapability.Communication.NetStack 429 430**Parameters** 431 432| Name | Type | Mandatory| Description | 433| -------- | ------------------------ | ---- | ---------- | 434| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result.| 435 436**Error codes** 437 438| ID| Error Message | 439| ------- | ----------------------- | 440| 401 | Parameter error. | 441| 201 | Permission denied. | 442 443**Example** 444 445```ts 446import { webSocket } from '@kit.NetworkKit'; 447import { BusinessError } from '@kit.BasicServicesKit'; 448 449let ws = webSocket.createWebSocket(); 450ws.close((err: BusinessError) => { 451 if (!err) { 452 console.log("close success") 453 } else { 454 console.log("close fail, err is " + JSON.stringify(err)) 455 } 456}); 457``` 458 459### close<sup>6+</sup> 460 461close(options: WebSocketCloseOptions, callback: AsyncCallback\<boolean\>): void 462 463Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses an asynchronous callback to return the result. 464 465**Required permissions**: ohos.permission.INTERNET 466 467**Atomic service API**: This API can be used in atomic services since API version 11. 468 469**System capability**: SystemCapability.Communication.NetStack 470 471**Parameters** 472 473| Name | Type | Mandatory| Description | 474| -------- | ------------------------ | ---- | ----------------------------------------------------- | 475| options | WebSocketCloseOptions | Yes | Request options. For details, see [WebSocketCloseOptions](#websocketcloseoptions).| 476| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result. | 477 478**Error codes** 479 480| ID| Error Message | 481| ------- | ----------------------- | 482| 401 | Parameter error. | 483| 201 | Permission denied. | 484 485**Example** 486 487```ts 488import { webSocket } from '@kit.NetworkKit'; 489import { BusinessError } from '@kit.BasicServicesKit'; 490 491let ws = webSocket.createWebSocket(); 492 493let options: webSocket.WebSocketCloseOptions | undefined; 494if (options != undefined) { 495 options.code = 1000 496 options.reason = "your reason" 497} 498ws.close(options, (err: BusinessError) => { 499 if (!err) { 500 console.log("close success") 501 } else { 502 console.log("close fail, err is " + JSON.stringify(err)) 503 } 504}); 505``` 506 507### close<sup>6+</sup> 508 509close(options?: WebSocketCloseOptions): Promise\<boolean\> 510 511Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses a promise to return the result. 512 513**Required permissions**: ohos.permission.INTERNET 514 515**Atomic service API**: This API can be used in atomic services since API version 11. 516 517**System capability**: SystemCapability.Communication.NetStack 518 519**Parameters** 520 521| Name | Type | Mandatory| Description | 522| ------- | --------------------- | ---- | ----------------------------------------------------- | 523| options | WebSocketCloseOptions | No | Request options. For details, see [WebSocketCloseOptions](#websocketcloseoptions).| 524 525**Return value** 526 527| Type | Description | 528| :----------------- | :-------------------------------- | 529| Promise\<boolean\> | Promise used to return the result.| 530 531**Error codes** 532 533| ID| Error Message | 534| ------- | ----------------------- | 535| 401 | Parameter error. | 536| 201 | Permission denied. | 537 538**Example** 539 540```ts 541import { webSocket } from '@kit.NetworkKit'; 542 543let ws = webSocket.createWebSocket(); 544let options: webSocket.WebSocketCloseOptions | undefined; 545if (options != undefined) { 546 options.code = 1000 547 options.reason = "your reason" 548} 549let promise = ws.close(); 550promise.then((value: boolean) => { 551 console.log("close success") 552}).catch((err:string) => { 553 console.log("close fail, err is " + JSON.stringify(err)) 554}); 555``` 556 557### on('open')<sup>6+</sup> 558 559on(type: 'open', callback: AsyncCallback\<Object\>): void 560 561Enables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result. 562 563**Atomic service API**: This API can be used in atomic services since API version 11. 564 565**System capability**: SystemCapability.Communication.NetStack 566 567**Parameters** 568 569| Name | Type | Mandatory| Description | 570| -------- | ----------------------- | ---- | ----------------------------- | 571| type | string | Yes | Event type. <br />**open**: event indicating that a WebSocket connection has been opened.| 572| callback | AsyncCallback\<Object\> | Yes | Callback used to return the result. | 573 574**Example** 575 576```ts 577import { webSocket } from '@kit.NetworkKit'; 578import { BusinessError, Callback } from '@kit.BasicServicesKit'; 579 580let ws= webSocket.createWebSocket(); 581class OutValue { 582 status: number = 0 583 message: string = "" 584} 585ws.on('open', (err: BusinessError, value: Object) => { 586 console.log("on open, status:" + (value as OutValue).status + ", message:" + (value as OutValue).message); 587}); 588``` 589 590### off('open')<sup>6+</sup> 591 592off(type: 'open', callback?: AsyncCallback\<Object\>): void 593 594Disables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result. 595 596> **NOTE** 597> 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. 598 599**Atomic service API**: This API can be used in atomic services since API version 11. 600 601**System capability**: SystemCapability.Communication.NetStack 602 603**Parameters** 604 605| Name | Type | Mandatory| Description | 606| -------- | ----------------------- | ---- | ----------------------------- | 607| type | string | Yes | Event type. <br />**open**: event indicating that a WebSocket connection has been opened.| 608| callback | AsyncCallback\<Object\> | No | Callback used to return the result. | 609 610**Example** 611 612```ts 613import { webSocket } from '@kit.NetworkKit'; 614import { BusinessError } from '@kit.BasicServicesKit'; 615 616let ws = webSocket.createWebSocket(); 617class OutValue { 618 status: number = 0 619 message: string = "" 620} 621let callback1 = (err: BusinessError, value: Object) => { 622 console.log("on open, status:" + ((value as OutValue).status + ", message:" + (value as OutValue).message)); 623} 624ws.on('open', callback1); 625// 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. 626ws.off('open', callback1); 627``` 628 629### on('message')<sup>6+</sup> 630 631on(type: 'message', callback: AsyncCallback\<string | ArrayBuffer\>): void 632 633Enables 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. 634 635> **NOTE** 636> The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8). 637 638**Atomic service API**: This API can be used in atomic services since API version 11. 639 640**System capability**: SystemCapability.Communication.NetStack 641 642**Parameters** 643 644| Name | Type | Mandatory| Description | 645| -------- | ----------------------- | ---- | -------------------------------------------- | 646| type | string | Yes | Event type.<br />**message**: event indicating that a message has been received from the server.| 647| callback | AsyncCallback\<string \| ArrayBuffer <sup>8+</sup>\> | Yes | Callback used to return the result. | 648 649**Example** 650 651```ts 652import { webSocket } from '@kit.NetworkKit'; 653import { BusinessError } from '@kit.BasicServicesKit'; 654 655let ws = webSocket.createWebSocket(); 656ws.on('message', (err: BusinessError<void>, value: string | ArrayBuffer) => { 657 console.log("on message, message:" + value); 658}); 659``` 660 661### off('message')<sup>6+</sup> 662 663off(type: 'message', callback?: AsyncCallback\<string | ArrayBuffer\>): void 664 665Disables 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. 666 667> **NOTE** 668> The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8). 669> 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. 670 671**Atomic service API**: This API can be used in atomic services since API version 11. 672 673**System capability**: SystemCapability.Communication.NetStack 674 675**Parameters** 676 677| Name | Type | Mandatory| Description | 678| -------- | --------------------------------------------------- | ---- | -------------------------------------------- | 679| type | string | Yes | Event type.<br />**message**: event indicating that a message has been received from the server.| 680| callback | AsyncCallback\<string \|ArrayBuffer <sup>8+</sup>\> | No | Callback used to return the result. | 681 682**Example** 683 684```ts 685import { webSocket } from '@kit.NetworkKit'; 686 687let ws = webSocket.createWebSocket(); 688ws.off('message'); 689``` 690 691### on('close')<sup>6+</sup> 692 693on(type: 'close', callback: AsyncCallback\<CloseResult\>): void 694 695Enables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result. 696 697**Atomic service API**: This API can be used in atomic services since API version 11. 698 699**System capability**: SystemCapability.Communication.NetStack 700 701**Parameters** 702 703| Name | Type | Mandatory| Description | 704| -------- | ----------------------------------------------- | ---- | ------------------------------ | 705| type | string | Yes | Event type. <br />**close**: event indicating that a WebSocket connection has been closed.| 706| callback | AsyncCallback\<CloseResult\> | Yes | Callback used to return the result.<br>**close** and **reason** indicate the error code and error cause for closing the connection, respectively.| 707 708**Example** 709 710```ts 711import { webSocket } from '@kit.NetworkKit'; 712import { BusinessError } from '@kit.BasicServicesKit'; 713 714let ws = webSocket.createWebSocket(); 715ws.on('close', (err: BusinessError, value: webSocket.CloseResult) => { 716 console.log("on close, code is " + value.code + ", reason is " + value.reason); 717}); 718``` 719 720### off('close')<sup>6+</sup> 721 722off(type: 'close', callback?: AsyncCallback\<CloseResult\>): void 723 724Disables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result. 725 726> **NOTE** 727> 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. 728 729**Atomic service API**: This API can be used in atomic services since API version 11. 730 731**System capability**: SystemCapability.Communication.NetStack 732 733**Parameters** 734 735| Name | Type | Mandatory| Description | 736| -------- | ----------------------------------------------- | ---- | ------------------------------ | 737| type | string | Yes | Event type. <br />**close**: event indicating that a WebSocket connection has been closed.| 738| callback | AsyncCallback\<CloseResult\> | No | Callback used to return the result.<br>**close** and **reason** indicate the error code and error cause for closing the connection, respectively.| 739 740**Example** 741 742```ts 743import { webSocket } from '@kit.NetworkKit'; 744 745let ws = webSocket.createWebSocket(); 746ws.off('close'); 747``` 748 749### on('error')<sup>6+</sup> 750 751on(type: 'error', callback: ErrorCallback): void 752 753Enables listening for the **error** events of a WebSocket connection. This API uses an asynchronous callback to return the result. 754 755**Atomic service API**: This API can be used in atomic services since API version 11. 756 757**System capability**: SystemCapability.Communication.NetStack 758 759**Parameters** 760 761| Name | Type | Mandatory| Description | 762| -------- | ------------- | ---- | ------------------------------- | 763| type | string | Yes | Event type.<br />**error**: event indicating the WebSocket connection has encountered an error.| 764| callback | ErrorCallback | Yes | Callback used to return the result.<br>Common error code: 200| 765 766**Example** 767 768```ts 769import { webSocket } from '@kit.NetworkKit'; 770import { BusinessError } from '@kit.BasicServicesKit'; 771 772let ws = webSocket.createWebSocket(); 773ws.on('error', (err: BusinessError) => { 774 console.log("on error, error:" + JSON.stringify(err)) 775}); 776``` 777 778### off('error')<sup>6+</sup> 779 780off(type: 'error', callback?: ErrorCallback): void 781 782Disables listening for the **error** events of a WebSocket connection. This API uses an asynchronous callback to return the result. 783 784> **NOTE** 785> 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. 786 787**Atomic service API**: This API can be used in atomic services since API version 11. 788 789**System capability**: SystemCapability.Communication.NetStack 790 791**Parameters** 792 793| Name | Type | Mandatory| Description | 794| -------- | ------------- | ---- | ------------------------------- | 795| type | string | Yes | Event type.<br />**error**: event indicating the WebSocket connection has encountered an error.| 796| callback | ErrorCallback | No | Callback used to return the result. | 797 798**Example** 799 800```ts 801import { webSocket } from '@kit.NetworkKit'; 802 803let ws = webSocket.createWebSocket(); 804ws.off('error'); 805``` 806 807### on('dataEnd')<sup>11+</sup> 808 809on(type: 'dataEnd', callback: Callback\<void\>): void 810 811Enables listening for the **dataEnd** events of a WebSocket connection. This API uses an asynchronous callback to return the result. 812 813**System capability**: SystemCapability.Communication.NetStack 814 815**Parameters** 816 817| Name | Type | Mandatory| Description | 818| -------- | ---------------- | ---- | --------------------------------------- | 819| type | string | Yes | Event type.<br />**dataEnd**: event indicating the data receiving over the WebSocket connection has ended.| 820| callback | Callback\<void\> | Yes | Callback used to return the result. | 821 822**Example** 823 824```ts 825import { webSocket } from '@kit.NetworkKit'; 826 827let ws = webSocket.createWebSocket(); 828ws.on('dataEnd', () => { 829 console.log("on dataEnd") 830}); 831``` 832 833### off('dataEnd')<sup>11+</sup> 834 835off(type: 'dataEnd', callback?: Callback\<void\>): void 836 837Disables listening for the **dataEnd** events of a WebSocket connection. This API uses an asynchronous callback to return the result. 838 839> **NOTE** 840> 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. 841 842**System capability**: SystemCapability.Communication.NetStack 843 844**Parameters** 845 846| Name | Type | Mandatory| Description | 847| -------- | ---------------- | ---- | -------------------------------------- | 848| type | string | Yes | Event type.<br />**dataEnd**: event indicating the data receiving over the WebSocket connection has ended.| 849| callback | Callback\<void\> | No | Callback used to return the result. | 850 851**Example** 852 853```ts 854import { webSocket } from '@kit.NetworkKit'; 855 856let ws = webSocket.createWebSocket(); 857ws.off('dataEnd'); 858``` 859 860### on('headerReceive')<sup>12+</sup> 861 862on(type: 'headerReceive', callback: Callback\<ResponseHeaders\>): void 863 864Registers an observer for HTTP Response Header events. This API uses an asynchronous callback to return the result. 865 866**System capability**: SystemCapability.Communication.NetStack 867 868**Parameters** 869 870| Name | Type | Mandatory| Description | 871| -------- | ---------------- | ---- | -------------------------------------- | 872| type | string | Yes | Event type. The value is **headerReceive**.| 873| callback | Callback\<ResponseHeaders\> | Yes | Callback used to return the result. | 874 875**Example** 876 877```ts 878import { webSocket } from '@kit.NetworkKit'; 879 880let ws = webSocket.createWebSocket(); 881ws.on('headerReceive', (data) => { 882 console.log("on headerReceive " + JSON.stringify(data)); 883}); 884``` 885 886### off('headerReceive')<sup>12+</sup> 887 888off(type: 'headerReceive', callback?: Callback\<ResponseHeaders\>): void 889 890Unregisters the observer for HTTP Response Header events. This API uses an asynchronous callback to return the result. 891 892> **NOTE** 893> 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. 894 895**System capability**: SystemCapability.Communication.NetStack 896 897**Parameters** 898 899| Name | Type | Mandatory| Description | 900| -------- | ---------------- | ---- | -------------------------------------- | 901| type | string | Yes | Event type. The value is **headerReceive**.| 902| callback | Callback\<ResponseHeaders\> | No | Callback used to return the result. | 903 904**Example** 905 906```ts 907import { webSocket } from '@kit.NetworkKit'; 908 909let ws = webSocket.createWebSocket(); 910ws.off('headerReceive'); 911``` 912 913## WebSocketRequestOptions 914 915Defines the optional parameters carried in the request for establishing a WebSocket connection. 916 917**System capability**: SystemCapability.Communication.NetStack 918 919| Name| Type| Read Only | Optional| Description | 920| ------ | ------ |------ | ---- | ------------------------------------------------------------ | 921| header | Object | No | Yes | Header carrying optional parameters in the request for establishing a WebSocket connection. You can customize the parameter or leave it unspecified.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 922| caPath<sup>11+</sup> | string | No | Yes | Path of CA certificates. If a path is set, the system uses the CA certificates in this path. If a path is not set, the system uses the preset CA certificate, namely, **/etc/ssl/certs/cacert.pem**. This path is the sandbox mapping path, which can be obtained through **Global.getContext().filesDir**. Currently, only text certificates in PEM format are supported.| 923| clientCert<sup>11+</sup> | [ClientCert](#clientcert11) | No | Yes | Client certificate.| 924| proxy<sup>12+</sup> | ProxyConfiguration | No | Yes| Proxy configuration. By default, the system network proxy is used.| 925| protocol<sup>12+</sup> | string | No | Yes| Custom **Sec-WebSocket-Protocol** field. The default value is "". | 926 927## ClientCert<sup>11+</sup> 928 929Defines the client certificate type. 930 931**System capability**: SystemCapability.Communication.NetStack 932 933| Name| Type | Mandatory| Description | 934| ------ | ------ | ---- | ------------------------------------------------------------ | 935| certPath | string | Yes | Path of the certificate file.| 936| keyPath | string | Yes | Path of the certificate key file.| 937| keyPassword | string | No | Password of the certificate key file.| 938 939## ProxyConfiguration<sup>12+</sup> 940type ProxyConfiguration = 'system' | 'no-proxy' | HttpProxy 941 942Represents the HTTP proxy configuration. 943 944**System capability**: SystemCapability.Communication.NetStack 945 946| Type | Description | 947| ------ |------------------------- | 948| 'system' | The default network proxy is used.| 949| 'no-proxy' | No network proxy is used.| 950| [HttpProxy](js-apis-net-connection.md#httpproxy10) | The specified network proxy is used.| 951 952## WebSocketCloseOptions 953 954Defines the optional parameters carried in the request for closing a WebSocket connection. 955 956**Atomic service API**: This API can be used in atomic services since API version 11. 957 958**System capability**: SystemCapability.Communication.NetStack 959 960| Name| Type | Mandatory| Description | 961| ------ | ------ | ---- | ------------------------------------------------------------ | 962| code | number | No | Error code. Set this parameter based on the actual situation. The default value is **1000**.| 963| reason | string | No | Error cause. Set this parameter based on the actual situation. The default value is an empty string ("").| 964 965## CloseResult<sup>10+</sup> 966 967Represents the result obtained from the **close** event reported when the WebSocket connection is closed. 968 969**Atomic service API**: This API can be used in atomic services since API version 11. 970 971**System capability**: SystemCapability.Communication.NetStack 972 973| Name| Type | Mandatory| Description | 974| ------ | ------ | ---- | ------------------------------------------------------------ | 975| code | number | Yes | Error code for closing the connection.| 976| reason | string | Yes | Error cause for closing the connection.| 977 978## ResponseHeaders<sup>12+</sup> 979type ResponseHeaders = {[k: string]: string | string[] | undefined;} 980 981Enumerates the response headers sent by the server. 982 983**System capability**: SystemCapability.Communication.NetStack 984 985| Type | Description | 986| ------ | ------------------------------------------------------------ | 987| {[k:string]:string \| string[] \| undefined} | The header data type can be key-value pair, string, or undefined.| 988 989## Result Codes for Connection Closing 990 991You can customize the result codes sent to the server. The result codes in the following table are for reference only. 992 993**System capability**: SystemCapability.Communication.NetStack 994 995| Value | Description | 996| :-------- | :----------------- | 997| 1000 | Normally closed. | 998| 1001 | Connection closed by the server. | 999| 1002 | Incorrect protocol. | 1000| 1003 | Data unable to be processed.| 1001| 1004~1015 | Reserved. | 1002