• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 '@ohos.net.webSocket';
18```
19
20## Examples
21
22```ts
23import webSocket from '@ohos.net.webSocket';
24import { BusinessError } from '@ohos.base';
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',(BusinessError<void>, 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, (err: BusinessError, value: boolean) => {
62  if (!err) {
63    console.log("connect success");
64  } else {
65    console.log("connect fail, err:" + JSON.stringify(err));
66  }
67  ws.close((err: BusinessError) => {
68    if (!err) {
69      console.log("close success");
70    } else {
71      console.log("close fail, err is " + JSON.stringify(err));
72    }
73  });
74});
75```
76
77## webSocket.createWebSocket<sup>6+</sup>
78
79createWebSocket(): WebSocket
80
81Creates 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.
82
83**System capability**: SystemCapability.Communication.NetStack
84
85**Return value**
86
87| Type                               | Description                                                        |
88| :---------------------------------- | :----------------------------------------------------------- |
89| [WebSocket](#websocket6) | A **WebSocket** object, which contains the **connect**, **send**, **close**, **on**, or **off** method.|
90
91**Example**
92
93```ts
94let ws: webSocket = webSocket.createWebSocket();
95```
96
97## WebSocket<sup>6+</sup>
98
99Defines a **WebSocket** object. Before invoking WebSocket APIs, you need to call [webSocket.createWebSocket](#websocketcreatewebsocket6) to create a **WebSocket** object.
100
101### connect<sup>6+</sup>
102
103connect(url: string, callback: AsyncCallback\<boolean\>): void
104
105Initiates a WebSocket request to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result.
106
107> **NOTE**
108> You can listen to **error** events to obtain the operation result. If an error occurs, the error code 200 will be returned.
109
110**Required permissions**: ohos.permission.INTERNET
111
112**System capability**: SystemCapability.Communication.NetStack
113
114**Parameters**
115
116| Name  | Type                    | Mandatory| Description                        |
117| -------- | ------------------------ | ---- | ---------------------------- |
118| url      | string                   | Yes  | URL for establishing a WebSocket connection.|
119| callback | AsyncCallback\<boolean\> | Yes  | Callback used to return the result.                  |
120
121**Error codes**
122
123| ID| Error Message                |
124| ------- | ----------------------- |
125| 401     | Parameter error.        |
126| 201     | Permission denied.      |
127
128**Example**
129
130```ts
131import webSocket from '@ohos.net.webSocket';
132import { BusinessError } from '@ohos.base';
133
134let ws = webSocket.createWebSocket();
135let url = "ws://";
136ws.connect(url, (err: BusinessError, value: boolean) => {
137  if (!err) {
138    console.log("connect success");
139  } else {
140    console.log("connect fail, err:" + JSON.stringify(err));
141  }
142});
143```
144
145### connect<sup>6+</sup>
146
147connect(url: string, options: WebSocketRequestOptions, callback: AsyncCallback\<boolean\>): void
148
149Initiates 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.
150
151> **NOTE**
152> You can listen to **error** events to obtain the operation result. If an error occurs, the error code 200 will be returned.
153
154**Required permissions**: ohos.permission.INTERNET
155
156**System capability**: SystemCapability.Communication.NetStack
157
158**Parameters**
159
160| Name  | Type                    | Mandatory| Description                                                   |
161| -------- | ------------------------ | ---- | ------------------------------------------------------- |
162| url      | string                   | Yes  | URL for establishing a WebSocket connection.                           |
163| options  | WebSocketRequestOptions  | Yes  | Request options. For details, see [WebSocketRequestOptions](#websocketrequestoptions).|
164| callback | AsyncCallback\<boolean\> | Yes  | Callback used to return the result.                                             |
165
166**Error codes**
167
168| ID| Error Message                |
169| ------- | ----------------------- |
170| 401     | Parameter error.        |
171| 201     | Permission denied.      |
172
173**Example**
174
175```ts
176import webSocket from '@ohos.net.webSocket';
177import { BusinessError } from '@ohos.base';
178
179let ws = webSocket.createWebSocket();
180let header: Map<string, string> | undefined;
181if (header !=undefined) {
182    header.set("key", "value")
183    header.set("key2", "value2")
184}
185let url = "ws://"
186ws.connect(url, header as webSocket.WebSocketRequestOptions, (err: BusinessError, value: Object) => {
187  if (!err) {
188    console.log("connect success");
189  } else {
190    console.log("connect fail, err:" + JSON.stringify(err))
191  }
192});
193```
194
195### connect<sup>6+</sup>
196
197connect(url: string, options?: WebSocketRequestOptions): Promise\<boolean\>
198
199Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses a promise to return the result.
200
201> **NOTE**
202> You can listen to **error** events to obtain the operation result. If an error occurs, the error code 200 will be returned.
203
204**Required permissions**: ohos.permission.INTERNET
205
206**System capability**: SystemCapability.Communication.NetStack
207
208**Parameters**
209
210| Name | Type                   | Mandatory| Description                                                   |
211| ------- | ----------------------- | ---- | ------------------------------------------------------- |
212| url     | string                  | Yes  | URL for establishing a WebSocket connection.                           |
213| options | WebSocketRequestOptions | No  | Request options. For details, see [WebSocketRequestOptions](#websocketrequestoptions).|
214
215**Return value**
216
217| Type              | Description                             |
218| :----------------- | :-------------------------------- |
219| Promise\<boolean\> | Promise used to return the result.|
220
221**Error codes**
222
223| ID| Error Message                |
224| ------- | ----------------------- |
225| 401     | Parameter error.        |
226| 201     | Permission denied.      |
227
228**Example**
229
230```ts
231import webSocket from '@ohos.net.webSocket';
232
233let ws = webSocket.createWebSocket();
234let url = "ws://"
235let promise = ws.connect(url);
236promise.then((value: boolean) => {
237  console.log("connect success")
238}).catch((err:string) => {
239  console.log("connect fail, error:" + JSON.stringify(err))
240});
241```
242
243### send<sup>6+</sup>
244
245send(data: string | ArrayBuffer, callback: AsyncCallback\<boolean\>): void
246
247Sends data through a WebSocket connection. This API uses an asynchronous callback to return the result.
248
249**Required permissions**: ohos.permission.INTERNET
250
251**System capability**: SystemCapability.Communication.NetStack
252
253**Parameters**
254
255| Name  | Type                    | Mandatory| Description        |
256| -------- | ------------------------ | ---- | ------------ |
257| 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.|
258| callback | AsyncCallback\<boolean\> | Yes  | Callback used to return the result.  |
259
260**Error codes**
261
262| ID| Error Message                |
263| ------- | ----------------------- |
264| 401     | Parameter error.        |
265| 201     | Permission denied.      |
266
267**Example**
268
269```ts
270import webSocket from '@ohos.net.webSocket';
271import { BusinessError } from '@ohos.base';
272
273let ws = webSocket.createWebSocket();
274let url = "ws://"
275ws.connect(url, (err: BusinessError, value: boolean) => {
276  ws.send("Hello, server!", (err: BusinessError, value: boolean) => {
277    if (!err) {
278      console.log("send success");
279    } else {
280      console.log("send fail, err:" + JSON.stringify(err))
281    }
282  });
283});
284```
285
286### send<sup>6+</sup>
287
288send(data: string | ArrayBuffer): Promise\<boolean\>
289
290Sends data through a WebSocket connection. This API uses a promise to return the result.
291
292**Required permissions**: ohos.permission.INTERNET
293
294**System capability**: SystemCapability.Communication.NetStack
295
296**Parameters**
297
298| Name| Type  | Mandatory| Description        |
299| ------ | ------ | ---- | ------------ |
300| 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.|
301
302**Return value**
303
304| Type              | Description                             |
305| :----------------- | :-------------------------------- |
306| Promise\<boolean\> | Promise used to return the result.|
307
308**Error codes**
309
310| ID| Error Message                |
311| ------- | ----------------------- |
312| 401     | Parameter error.        |
313| 201     | Permission denied.      |
314
315**Example**
316
317```ts
318import webSocket from '@ohos.net.webSocket';
319import { BusinessError } from '@ohos.base';
320
321let ws = webSocket.createWebSocket();
322let url = "ws://"
323ws.connect(url, (err: BusinessError, value: boolean) => {
324  let promise = ws.send("Hello, server!");
325  promise.then((value: boolean) => {
326    console.log("send success")
327  }).catch((err:string) => {
328    console.log("send fail, error:" + JSON.stringify(err))
329  });
330});
331```
332
333### close<sup>6+</sup>
334
335close(callback: AsyncCallback\<boolean\>): void
336
337Closes a WebSocket connection. This API uses an asynchronous callback to return the result.
338
339**Required permissions**: ohos.permission.INTERNET
340
341**System capability**: SystemCapability.Communication.NetStack
342
343**Parameters**
344
345| Name  | Type                    | Mandatory| Description      |
346| -------- | ------------------------ | ---- | ---------- |
347| callback | AsyncCallback\<boolean\> | Yes  | Callback used to return the result.|
348
349**Error codes**
350
351| ID| Error Message                |
352| ------- | ----------------------- |
353| 401     | Parameter error.        |
354| 201     | Permission denied.      |
355
356**Example**
357
358```ts
359import webSocket from '@ohos.net.webSocket';
360import { BusinessError } from '@ohos.base';
361
362let ws = webSocket.createWebSocket();
363ws.close((err: BusinessError) => {
364  if (!err) {
365    console.log("close success")
366  } else {
367    console.log("close fail, err is " + JSON.stringify(err))
368  }
369});
370```
371
372### close<sup>6+</sup>
373
374close(options: WebSocketCloseOptions, callback: AsyncCallback\<boolean\>): void
375
376Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses an asynchronous callback to return the result.
377
378**Required permissions**: ohos.permission.INTERNET
379
380**System capability**: SystemCapability.Communication.NetStack
381
382**Parameters**
383
384| Name  | Type                    | Mandatory| Description                                                 |
385| -------- | ------------------------ | ---- | ----------------------------------------------------- |
386| options  | WebSocketCloseOptions    | Yes  | Request options. For details, see [WebSocketCloseOptions](#websocketcloseoptions).|
387| callback | AsyncCallback\<boolean\> | Yes  | Callback used to return the result.                                           |
388
389**Error codes**
390
391| ID| Error Message                |
392| ------- | ----------------------- |
393| 401     | Parameter error.        |
394| 201     | Permission denied.      |
395
396**Example**
397
398```ts
399import webSocket from '@ohos.net.webSocket';
400import { BusinessError } from '@ohos.base';
401
402let ws = webSocket.createWebSocket();
403
404let options: webSocket.WebSocketCloseOptions | undefined;
405if (options != undefined) {
406    options.code = 1000
407    options.reason = "your reason"
408}
409ws.close(options, (err: BusinessError) => {
410    if (!err) {
411        console.log("close success")
412    } else {
413        console.log("close fail, err is " + JSON.stringify(err))
414    }
415});
416```
417
418### close<sup>6+</sup>
419
420close(options?: WebSocketCloseOptions): Promise\<boolean\>
421
422Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses a promise to return the result.
423
424**Required permissions**: ohos.permission.INTERNET
425
426**System capability**: SystemCapability.Communication.NetStack
427
428**Parameters**
429
430| Name | Type                 | Mandatory| Description                                                 |
431| ------- | --------------------- | ---- | ----------------------------------------------------- |
432| options | WebSocketCloseOptions | No  | Request options. For details, see [WebSocketCloseOptions](#websocketcloseoptions).|
433
434**Return value**
435
436| Type              | Description                             |
437| :----------------- | :-------------------------------- |
438| Promise\<boolean\> | Promise used to return the result.|
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 '@ohos.net.webSocket';
451
452let ws = webSocket.createWebSocket();
453let options: webSocket.WebSocketCloseOptions | undefined;
454if (options != undefined) {
455    options.code = 1000
456    options.reason = "your reason"
457}
458let promise = ws.close();
459promise.then((value: boolean) => {
460    console.log("close success")
461}).catch((err:string) => {
462    console.log("close fail, err is " + JSON.stringify(err))
463});
464```
465
466### on('open')<sup>6+</sup>
467
468on(type: 'open', callback: AsyncCallback\<Object\>): void
469
470Enables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
471
472**System capability**: SystemCapability.Communication.NetStack
473
474**Parameters**
475
476| Name  | Type                   | Mandatory| Description                         |
477| -------- | ----------------------- | ---- | ----------------------------- |
478| type     | string                  | Yes  | Event type. <br />**open**: event indicating that a WebSocket connection has been opened.|
479| callback | AsyncCallback\<Object\> | Yes  | Callback used to return the result.                   |
480
481**Example**
482
483```ts
484import webSocket from '@ohos.net.webSocket';
485import { BusinessError, Callback } from '@ohos.base';
486
487let ws= webSocket.createWebSocket();
488class OutValue {
489  status: number = 0
490  message: string = ""
491}
492ws.on('open', (err: BusinessError, value: Object) => {
493  console.log("on open, status:" + (value as OutValue).status + ", message:" + (value as OutValue).message);
494});
495```
496
497### off('open')<sup>6+</sup>
498
499off(type: 'open', callback?: AsyncCallback\<Object\>): void
500
501Disables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
502
503> **NOTE**
504> 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.
505
506**System capability**: SystemCapability.Communication.NetStack
507
508**Parameters**
509
510| Name  | Type                   | Mandatory| Description                         |
511| -------- | ----------------------- | ---- | ----------------------------- |
512| type     | string                  | Yes  | Event type. <br />**open**: event indicating that a WebSocket connection has been opened.|
513| callback | AsyncCallback\<Object\> | No  | Callback used to return the result.                   |
514
515**Example**
516
517```ts
518import webSocket from '@ohos.net.webSocket';
519import { BusinessError } from '@ohos.base';
520
521let ws = webSocket.createWebSocket();
522class OutValue {
523  status: number = 0
524  message: string = ""
525}
526let callback1 = (err: BusinessError, value: Object) => {
527 console.log("on open, status:" + ((value as OutValue).status + ", message:" + (value as OutValue).message));
528}
529ws.on('open', callback1);
530// 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.
531ws.off('open', callback1);
532```
533
534### on('message')<sup>6+</sup>
535
536on(type: 'message', callback: AsyncCallback\<string | ArrayBuffer\>): void
537
538Enables 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.
539
540> **NOTE**
541> The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8).
542
543**System capability**: SystemCapability.Communication.NetStack
544
545**Parameters**
546
547| Name  | Type                   | Mandatory| Description                                        |
548| -------- | ----------------------- | ---- | -------------------------------------------- |
549| type     | string                  | Yes  | Event type.<br />**message**: event indicating that a message has been received from the server.|
550| callback | AsyncCallback\<string \| ArrayBuffer <sup>8+</sup>\> | Yes  | Callback used to return the result.                                  |
551
552**Example**
553
554```ts
555import webSocket from '@ohos.net.webSocket';
556import { BusinessError } from '@ohos.base';
557
558let ws = webSocket.createWebSocket();
559ws.on('message', (err: BusinessError<void>, value: string | ArrayBuffer) => {
560  console.log("on message, message:" + value);
561});
562```
563
564### off('message')<sup>6+</sup>
565
566off(type: 'message', callback?: AsyncCallback\<string | ArrayBuffer\>): void
567
568Disables 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.
569
570> **NOTE**
571> The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8).
572> 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.
573
574**System capability**: SystemCapability.Communication.NetStack
575
576**Parameters**
577
578| Name  | Type                                               | Mandatory| Description                                        |
579| -------- | --------------------------------------------------- | ---- | -------------------------------------------- |
580| type     | string                                              | Yes  | Event type.<br />**message**: event indicating that a message has been received from the server.|
581| callback | AsyncCallback\<string \|ArrayBuffer <sup>8+</sup>\> | No  | Callback used to return the result.                                  |
582
583**Example**
584
585```ts
586import webSocket from '@ohos.net.webSocket';
587
588let ws = webSocket.createWebSocket();
589ws.off('message');
590```
591
592### on('close')<sup>6+</sup>
593
594on(type: 'close', callback: AsyncCallback\<CloseResult\>): void
595
596Enables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
597
598**System capability**: SystemCapability.Communication.NetStack
599
600**Parameters**
601
602| Name  | Type                                           | Mandatory| Description                          |
603| -------- | ----------------------------------------------- | ---- | ------------------------------ |
604| type     | string                                          | Yes  | Event type. <br />**close**: event indicating that a WebSocket connection has been closed.|
605| 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.|
606
607**Example**
608
609```ts
610import webSocket from '@ohos.net.webSocket';
611import { BusinessError } from '@ohos.base';
612
613let ws = webSocket.createWebSocket();
614ws.on('close', (err: BusinessError, value: webSocket.CloseResult) => {
615  console.log("on close, code is " + value.code + ", reason is " + value.reason);
616});
617```
618
619### off('close')<sup>6+</sup>
620
621off(type: 'close', callback?: AsyncCallback\<CloseResult\>): void
622
623Disables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
624
625> **NOTE**
626> 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.
627
628**System capability**: SystemCapability.Communication.NetStack
629
630**Parameters**
631
632| Name  | Type                                           | Mandatory| Description                          |
633| -------- | ----------------------------------------------- | ---- | ------------------------------ |
634| type     | string                                          | Yes  | Event type. <br />**close**: event indicating that a WebSocket connection has been closed.|
635| 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.|
636
637**Example**
638
639```ts
640import webSocket from '@ohos.net.webSocket';
641
642let ws = webSocket.createWebSocket();
643ws.off('close');
644```
645
646### on('error')<sup>6+</sup>
647
648on(type: 'error', callback: ErrorCallback): void
649
650Enables listening for the **error** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
651
652**System capability**: SystemCapability.Communication.NetStack
653
654**Parameters**
655
656| Name  | Type         | Mandatory| Description                           |
657| -------- | ------------- | ---- | ------------------------------- |
658| type     | string        | Yes  | Event type.<br />**error**: event indicating the WebSocket connection has encountered an error.|
659| callback | ErrorCallback | Yes  | Callback used to return the result.<br>Common error code: 200|
660
661**Example**
662
663```ts
664import webSocket from '@ohos.net.webSocket';
665import { BusinessError } from '@ohos.base';
666
667let ws = webSocket.createWebSocket();
668ws.on('error', (err: BusinessError) => {
669  console.log("on error, error:" + JSON.stringify(err))
670});
671```
672
673### off('error')<sup>6+</sup>
674
675off(type: 'error', callback?: ErrorCallback): void
676
677Disables listening for the **error** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
678
679> **NOTE**
680> 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.
681
682**System capability**: SystemCapability.Communication.NetStack
683
684**Parameters**
685
686| Name  | Type         | Mandatory| Description                           |
687| -------- | ------------- | ---- | ------------------------------- |
688| type     | string        | Yes  | Event type.<br />**error**: event indicating the WebSocket connection has encountered an error.|
689| callback | ErrorCallback | No  | Callback used to return the result.                     |
690
691**Example**
692
693```ts
694import webSocket from '@ohos.net.webSocket';
695let ws = webSocket.createWebSocket();
696ws.off('error');
697```
698
699### on('dataEnd')<sup>11+</sup>
700
701on(type: 'dataEnd', callback: Callback\<void\>): void
702
703Enables listening for the **dataEnd** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
704
705**System capability**: SystemCapability.Communication.NetStack
706
707**Parameters**
708
709| Name  |       Type       | Mandatory|                  Description                  |
710| -------- | ---------------- | ---- | --------------------------------------- |
711| type     | string           | Yes  | Event type.<br />**dataEnd**: event indicating the data receiving over the WebSocket connection has ended.|
712| callback | Callback\<void\> | Yes  | Callback used to return the result.                             |
713
714**Example**
715
716```ts
717import webSocket from '@ohos.net.webSocket';
718
719let ws = webSocket.createWebSocket();
720ws.on('dataEnd', () => {
721  console.log("on dataEnd")
722});
723```
724
725### off('dataEnd')<sup>11+</sup>
726
727off(type: 'dataEnd', callback?: Callback\<void\>): void
728
729Disables listening for the **dataEnd** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
730
731> **NOTE**
732> 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.
733
734**System capability**: SystemCapability.Communication.NetStack
735
736**Parameters**
737
738| Name  |        Type      | Mandatory|                Description                   |
739| -------- | ---------------- | ---- | -------------------------------------- |
740| type     | string           | Yes  | Event type.<br />**dataEnd**: event indicating the data receiving over the WebSocket connection has ended.|
741| callback | Callback\<void\> | No  | Callback used to return the result.                            |
742
743**Example**
744
745```ts
746import webSocket from '@ohos.net.webSocket';
747let ws = webSocket.createWebSocket();
748ws.off('dataEnd');
749```
750
751## WebSocketRequestOptions
752
753Defines the optional parameters carried in the request for establishing a WebSocket connection.
754
755**System capability**: SystemCapability.Communication.NetStack
756
757| Name| Type  | Mandatory| Description                                                        |
758| ------ | ------ | ---- | ------------------------------------------------------------ |
759| header | Object | No  | Header carrying optional parameters in the request for establishing a WebSocket connection. You can customize the parameter or leave it unspecified.|
760| caPath<sup>11+</sup> | string | No  | 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.|
761| clientCert<sup>11+</sup> | [ClientCert](#clientcert11) | No  | Client certificate.|
762
763## ClientCert<sup>11+</sup>
764
765Defines the client certificate type.
766
767**System capability**: SystemCapability.Communication.NetStack
768
769| Name| Type  | Mandatory| Description                                                        |
770| ------ | ------ | ---- | ------------------------------------------------------------ |
771| certPath   | string  | Yes  | Path of the certificate file.|
772| keyPath | string | Yes  | Path of the certificate key file.|
773| keyPassword | string | No  | Password of the certificate key file.|
774
775## WebSocketCloseOptions
776
777Defines the optional parameters carried in the request for closing a WebSocket connection.
778
779**System capability**: SystemCapability.Communication.NetStack
780
781| Name| Type  | Mandatory| Description                                                        |
782| ------ | ------ | ---- | ------------------------------------------------------------ |
783| code   | number | No  | Error code. Set this parameter based on the actual situation. The default value is **1000**.|
784| reason | string | No  | Error cause. Set this parameter based on the actual situation. The default value is an empty string ("").|
785
786## CloseResult<sup>10+</sup>
787
788Represents the result obtained from the **close** event reported when the WebSocket connection is closed.
789
790**System capability**: SystemCapability.Communication.NetStack
791
792| Name| Type  | Mandatory| Description                                                        |
793| ------ | ------ | ---- | ------------------------------------------------------------ |
794| code   | number | Yes  | Error code for closing the connection.|
795| reason | string | Yes  | Error cause for closing the connection.|
796
797## Result Codes for Closing a WebSocket Connection
798
799You can customize the result codes sent to the server. The result codes in the following table are for reference only.
800
801**System capability**: SystemCapability.Communication.NetStack
802
803| Value       | Description              |
804| :-------- | :----------------- |
805| 1000      | Normally closed.          |
806| 1001      | Connection closed by the server.    |
807| 1002      | Incorrect protocol.          |
808| 1003      | Data unable to be processed.|
809| 1004~1015 | Reserved.            |
810