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