• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# WebSocket Connection
2
3> **NOTE**<br>
4> 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.
5
6You 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. If 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. When 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.
7
8If an error occurs in any of the preceding processes, the client will receive a callback of the [error](#onerror) event.
9
10
11## Modules to Import
12
13```js
14import webSocket from '@ohos.net.webSocket';
15```
16
17## Complete Example
18
19```js
20import webSocket from '@ohos.net.webSocket';
21
22var defaultIpAddress = "ws://";
23let ws = webSocket.createWebSocket();
24ws.on('open', (err, value) => {
25    console.log("on open, status:" + value['status'] + ", message:" + value['message']);
26    // When receiving the on('open') event, the client can use the send() API to communicate with the server.
27    ws.send("Hello, server!", (err, value) => {
28        if (!err) {
29            console.log("send success");
30        } else {
31            console.log("send fail, err:" + JSON.stringify(err));
32        }
33    });
34});
35ws.on('message', (err, value) => {
36    console.log("on message, message:" + value);
37    // When receiving the bye message (the actual message name may differ) from the server, the client proactively disconnects from the server.
38    if (value === 'bye') {
39        ws.close((err, value) => {
40            if (!err) {
41                console.log("close success");
42            } else {
43                console.log("close fail, err is " + JSON.stringify(err));
44            }
45        });
46    }
47});
48ws.on('close', (err, value) => {
49    console.log("on close, code is " + value['code'] + ", reason is " + value['reason']);
50});
51ws.on('error', (err) => {
52    console.log("on error, error:" + JSON.stringify(err));
53});
54ws.connect(defaultIpAddress, (err, value) => {
55    if (!err) {
56        console.log("connect success");
57    } else {
58        console.log("connect fail, err:" + JSON.stringify(err));
59    }
60});
61```
62
63## webSocket.createWebSocket
64
65createWebSocket\(\): WebSocket
66
67Creates 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.
68
69**System capability**: SystemCapability.Communication.NetStack
70
71**Return Value**
72
73| Type                               | Description                                                        |
74| :---------------------------------- | :----------------------------------------------------------- |
75| [WebSocket](#websocket) | A **WebSocket** object, which contains the **connect**, **send**, **close**, **on**, or **off** method.|
76
77**Example**
78
79```js
80let ws = webSocket.createWebSocket();
81```
82
83
84## WebSocket
85
86Defines a **WebSocket** object. Before invoking WebSocket APIs, you need to call [webSocket.createWebSocket](#websocketcreatewebsocket) to create a **WebSocket** object.
87
88### connect
89
90connect\(url: string, callback: AsyncCallback<boolean\>\): void
91
92Initiates a WebSocket request to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result.
93
94**Required permission**: ohos.permission.INTERNET
95
96**System capability**: SystemCapability.Communication.NetStack
97
98**Parameters**
99
100| Name  | Type                    | Mandatory| Description                        |
101| -------- | ------------------------ | ---- | ---------------------------- |
102| url      | string                   | Yes  | URL for establishing a WebSocket connection.|
103| callback | AsyncCallback\<boolean\> | Yes  | Callback used to return the result.                  |
104
105
106**Example**
107
108```js
109let ws = webSocket.createWebSocket();
110let url = "ws://"
111ws.connect(url, (err, value) => {
112	if (!err) {
113		console.log("connect success");
114	} else {
115		console.log("connect fail, err:" + JSON.stringify(err))
116	}
117});
118```
119
120
121### connect
122
123connect\(url: string, options: WebSocketRequestOptions, callback: AsyncCallback<boolean\>\): void
124
125Initiates 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.
126
127**Required permission**: ohos.permission.INTERNET
128
129**System capability**: SystemCapability.Communication.NetStack
130
131**Parameters**
132
133| Name  | Type                    | Mandatory| Description                                                   |
134| -------- | ------------------------ | ---- | ------------------------------------------------------- |
135| url      | string                   | Yes  | URL for establishing a WebSocket connection.                           |
136| options  | WebSocketRequestOptions  | Yes  | Request options. For details, see [WebSocketRequestOptions](#websocketrequestoptions).|
137| callback | AsyncCallback\<boolean\> | Yes  | Callback used to return the result.                                             |
138
139
140**Example**
141
142```js
143let ws = webSocket.createWebSocket();
144let url = "ws://"
145ws.connect(url, {
146	header: {
147		"key": "value",
148		"key2": "value2"
149	}
150}, (err, value) => {
151	if (!err) {
152		console.log("connect success");
153	} else {
154		console.log("connect fail, err:" + JSON.stringify(err))
155	}
156});
157```
158
159
160### connect
161
162connect\(url: string, options?: WebSocketRequestOptions\): Promise<boolean\>
163
164Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses a promise to return the result.
165
166**Required permission**: ohos.permission.INTERNET
167
168**System capability**: SystemCapability.Communication.NetStack
169
170**Parameters**
171
172| Name | Type                   | Mandatory| Description                                                   |
173| ------- | ----------------------- | ---- | ------------------------------------------------------- |
174| url     | string                  | Yes  | URL for establishing a WebSocket connection.                           |
175| options | WebSocketRequestOptions | No  | Request options. For details, see [WebSocketRequestOptions](#websocketrequestoptions).|
176
177**Return Value**
178
179| Type              | Description                             |
180| :----------------- | :-------------------------------- |
181| Promise\<boolean\> | Promise used to return the result.|
182
183**Example**
184
185```js
186let ws = webSocket.createWebSocket();
187let url = "ws://"
188let promise = ws.connect(url);
189promise.then((value) => {
190	console.log("connect success")
191}).catch((err) => {
192	console.log("connect fail, error:" + JSON.stringify(err))
193});
194```
195
196
197### send
198
199send\(data: string | ArrayBuffer, callback: AsyncCallback<boolean\>\): void
200
201Sends data through a WebSocket connection. This API uses an asynchronous callback to return the result.
202
203**Required permission**: ohos.permission.INTERNET
204
205**System capability**: SystemCapability.Communication.NetStack
206
207**Parameters**
208
209| Name  | Type                    | Mandatory| Description        |
210| -------- | ------------------------ | ---- | ------------ |
211| data     | string \| ArrayBuffer <sup>8+</sup> | Yes  | Data to send.|
212| callback | AsyncCallback\<boolean\> | Yes  | Callback used to return the result.  |
213
214**Example**
215
216```js
217let ws = webSocket.createWebSocket();
218let url = "ws://"
219ws.connect(url, (err, value) => {
220	ws.send("Hello, server!", (err, value) => {
221		if (!err) {
222			console.log("send success");
223		} else {
224			console.log("send fail, err:" + JSON.stringify(err))
225		}
226	});
227});
228```
229
230
231### send
232
233send\(data: string | ArrayBuffer\): Promise<boolean\>
234
235Sends data through a WebSocket connection. This API uses a promise to return the result.
236
237**Required permission**: ohos.permission.INTERNET
238
239**System capability**: SystemCapability.Communication.NetStack
240
241**Parameters**
242
243| Name| Type  | Mandatory| Description        |
244| ------ | ------ | ---- | ------------ |
245| data     | string \| ArrayBuffer <sup>8+</sup> | Yes  | Data to send.|
246
247**Return Value**
248
249| Type              | Description                             |
250| :----------------- | :-------------------------------- |
251| Promise\<boolean\> | Promise used to return the result.|
252
253**Example**
254
255```js
256let ws = webSocket.createWebSocket();
257let url = "ws://"
258ws.connect(url, (err, value) => {
259	let promise = ws.send("Hello, server!");
260	promise.then((value) => {
261		console.log("send success")
262	}).catch((err) => {
263		console.log("send fail, error:" + JSON.stringify(err))
264	});
265});
266```
267
268
269### close
270
271close\(callback: AsyncCallback<boolean\>\): void
272
273Closes a WebSocket connection. This API uses an asynchronous callback to return the result.
274
275**Required permission**: ohos.permission.INTERNET
276
277**System capability**: SystemCapability.Communication.NetStack
278
279**Parameters**
280
281| Name  | Type                    | Mandatory| Description      |
282| -------- | ------------------------ | ---- | ---------- |
283| callback | AsyncCallback\<boolean\> | Yes  | Callback used to return the result.|
284
285**Example**
286
287```js
288let ws = webSocket.createWebSocket();
289let url = "ws://"
290ws.close((err, value) => {
291	if (!err) {
292		console.log("close success")
293	} else {
294		console.log("close fail, err is " + JSON.stringify(err))
295	}
296});
297```
298
299
300### close
301
302close\(options: WebSocketCloseOptions, callback: AsyncCallback<boolean\>\): void
303
304Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses an asynchronous callback to return the result.
305
306**Required permission**: ohos.permission.INTERNET
307
308**System capability**: SystemCapability.Communication.NetStack
309
310**Parameters**
311
312| Name  | Type                    | Mandatory| Description                                                 |
313| -------- | ------------------------ | ---- | ----------------------------------------------------- |
314| options  | WebSocketCloseOptions    | Yes  | Request options. For details, see [WebSocketCloseOptions](#websocketcloseoptions).|
315| callback | AsyncCallback\<boolean\> | Yes  | Callback used to return the result.                                           |
316
317**Example**
318
319```js
320let ws = webSocket.createWebSocket();
321let url = "ws://"
322ws.close({
323	code: 1000,
324	reason: "your reason"
325}, (err, value) => {
326	if (!err) {
327		console.log("close success")
328	} else {
329		console.log("close fail, err is " + JSON.stringify(err))
330	}
331});
332```
333
334
335### close
336
337close\(options?: WebSocketCloseOptions\): Promise<boolean\>
338
339Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses a promise to return the result.
340
341**Required permission**: ohos.permission.INTERNET
342
343**System capability**: SystemCapability.Communication.NetStack
344
345**Parameters**
346
347| Name | Type                 | Mandatory| Description                                                 |
348| ------- | --------------------- | ---- | ----------------------------------------------------- |
349| options | WebSocketCloseOptions | No  | Request options. For details, see [WebSocketCloseOptions](#websocketcloseoptions).|
350
351**Return Value**
352
353| Type              | Description                             |
354| :----------------- | :-------------------------------- |
355| Promise\<boolean\> | Promise used to return the result.|
356
357**Example**
358
359```js
360let ws = webSocket.createWebSocket();
361let url = "ws://"
362let promise = ws.close({
363	code: 1000,
364	reason: "your reason"
365});
366promise.then((value) => {
367	console.log("close success")
368}).catch((err) => {
369	console.log("close fail, err is " + JSON.stringify(err))
370});
371```
372
373
374### on\('open'\)
375
376on\(type: 'open', callback: AsyncCallback<Object\>\): void
377
378Enables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
379
380**System capability**: SystemCapability.Communication.NetStack
381
382**Parameters**
383
384| Name  | Type                   | Mandatory| Description                         |
385| -------- | ----------------------- | ---- | ----------------------------- |
386| type     | string                  | Yes  | Event type. <br />**open**: event indicating that a WebSocket connection has been opened.|
387| callback | AsyncCallback\<Object\> | Yes  | Callback used to return the result.                   |
388
389
390**Example**
391
392```js
393let ws = webSocket.createWebSocket();
394ws.on('open', (err, value) => {
395	console.log("on open, status:" + value['status'] + ", message:" + value['message']);
396});
397```
398
399
400### off\('open'\)
401
402off\(type: 'open', callback?: AsyncCallback<Object\>\): void
403
404Disables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
405
406>![](public_sys-resources/icon-note.gif) **NOTE:**
407>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.
408
409**System capability**: SystemCapability.Communication.NetStack
410
411**Parameters**
412
413| Name  | Type                   | Mandatory| Description                         |
414| -------- | ----------------------- | ---- | ----------------------------- |
415| type     | string                  | Yes  | Event type. <br />**open**: event indicating that a WebSocket connection has been opened.|
416| callback | AsyncCallback\<Object\> | No  | Callback used to return the result.                   |
417
418**Example**
419
420```js
421let ws = webSocket.createWebSocket();
422let callback1 = (err, value) => {
423	console.log("on open, status:" + value['status'] + ", message:" + value['message']);
424}
425ws.on('open', callback1);
426// 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.
427ws.off('open', callback1);
428```
429
430
431### on\('message'\)
432
433on\(type: 'message', callback: AsyncCallback<string | ArrayBuffer\>\): void
434
435Enables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
436
437>![](public_sys-resources/icon-note.gif) **NOTE:**
438>The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\).
439
440**System capability**: SystemCapability.Communication.NetStack
441
442**Parameters**
443
444| Name  | Type                   | Mandatory| Description                                        |
445| -------- | ----------------------- | ---- | -------------------------------------------- |
446| type     | string                  | Yes  | Event type.<br />**message**: event indicating that a message has been received from the server.|
447| callback | AsyncCallback\<string \| ArrayBuffer <sup>8+</sup>\> | Yes  | Callback used to return the result.                                  |
448
449
450**Example**
451
452```js
453let ws = webSocket.createWebSocket();
454ws.on('message', (err, value) => {
455	console.log("on message, message:" + value);
456});
457```
458
459
460### off\('message'\)
461
462off\(type: 'message', callback?: AsyncCallback<string | ArrayBuffer\>\): void
463
464Disables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
465
466>![](public_sys-resources/icon-note.gif) **NOTE:**
467>The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\).
468>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.
469
470**System capability**: SystemCapability.Communication.NetStack
471
472**Parameters**
473
474| Name  | Type                                               | Mandatory| Description                                        |
475| -------- | --------------------------------------------------- | ---- | -------------------------------------------- |
476| type     | string                                              | Yes  | Event type.<br />**message**: event indicating that a message has been received from the server.|
477| callback | AsyncCallback\<string \|ArrayBuffer <sup>8+</sup>\> | No  | Callback used to return the result.                                  |
478
479**Example**
480
481```js
482let ws = webSocket.createWebSocket();
483ws.off('message');
484```
485
486
487### on\('close'\)
488
489on\(type: 'close', callback: AsyncCallback<\{ code: number, reason: string \}\>\): void
490
491Enables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
492
493**System capability**: SystemCapability.Communication.NetStack
494
495**Parameters**
496
497| Name  | Type                                           | Mandatory| Description                          |
498| -------- | ----------------------------------------------- | ---- | ------------------------------ |
499| type     | string                                          | Yes  | Event type. <br />**close**: event indicating that a WebSocket connection has been closed.|
500| callback | AsyncCallback<{ code: number, reason: string }> | Yes  | Callback used to return the result.                    |
501
502**Example**
503
504```js
505let ws = webSocket.createWebSocket();
506ws.on('close', (err, value) => {
507	console.log("on close, code is " + value['code'] + ", reason is " + value['reason']);
508});
509```
510
511
512### off\('close'\)
513
514off\(type: 'close', callback?: AsyncCallback<\{ code: number, reason: string \}\>\): void
515
516Disables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
517
518>![](public_sys-resources/icon-note.gif) **NOTE:**
519>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.
520
521**System capability**: SystemCapability.Communication.NetStack
522
523**Parameters**
524
525| Name  | Type                                           | Mandatory| Description                          |
526| -------- | ----------------------------------------------- | ---- | ------------------------------ |
527| type     | string                                          | Yes  | Event type. <br />**close**: event indicating that a WebSocket connection has been closed.|
528| callback | AsyncCallback<{ code: number, reason: string }> | No  | Callback used to return the result.                    |
529
530
531**Example**
532
533```js
534let ws = webSocket.createWebSocket();
535ws.off('close');
536```
537
538
539### on\('error'\)
540
541on\(type: 'error', callback: ErrorCallback\): void
542
543Enables listening for the **error** 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 />**error**: event indicating the WebSocket connection has encountered an error.|
552| callback | ErrorCallback | Yes  | Callback used to return the result.                     |
553
554
555**Example**
556
557```js
558let ws = webSocket.createWebSocket();
559ws.on('error', (err) => {
560	console.log("on error, error:" + JSON.stringify(err))
561});
562```
563
564
565### off\('error'\)
566
567off\(type: 'error', callback?: ErrorCallback\): void
568
569Disables listening for the **error** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
570
571>![](public_sys-resources/icon-note.gif) **NOTE:**
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 />**error**: event indicating the WebSocket connection has encountered an error.|
581| callback | ErrorCallback | No  | Callback used to return the result.                     |
582
583**Example**
584
585```js
586let ws = webSocket.createWebSocket();
587ws.off('error');
588```
589
590
591## WebSocketRequestOptions
592
593Defines the optional parameters carried in the request for establishing a WebSocket connection.
594
595**System capability**: SystemCapability.Communication.NetStack
596
597| Name| Type  | Mandatory| Description                                                        |
598| ------ | ------ | ---- | ------------------------------------------------------------ |
599| header | Object | No  | Header carrying optional parameters in the request for establishing a WebSocket connection. You can customize the parameter or leave it unspecified.|
600
601
602## WebSocketCloseOptions
603
604Defines the optional parameters carried in the request for closing a WebSocket connection.
605
606**System capability**: SystemCapability.Communication.NetStack
607
608| Name| Type  | Mandatory| Description                                                        |
609| ------ | ------ | ---- | ------------------------------------------------------------ |
610| code   | number | No  | Error code. Set this parameter based on the actual situation. The default value is **1000**.|
611| reason | string | No  | Error cause. Set this parameter based on the actual situation. The default value is an empty string ("").|
612
613## Result Codes for Closing a WebSocket Connection
614
615You can customize the result codes sent to the server. The result codes in the following table are for reference only.
616
617**System capability**: SystemCapability.Communication.NetStack
618
619| Value       | Description              |
620| :-------- | :----------------- |
621| 1000      | Normally closed          |
622| 1001      | Connection closed by the server    |
623| 1002      | Incorrect protocol          |
624| 1003      | Data unable to be processed|
625| 1004~1015 | Reserved            |
626