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