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