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