# # @ohos.net.webSocket (WebSocket Connection)
> **NOTE**
>
> 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.
You 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.
If 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.
When 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.
If an error occurs in any of the preceding processes, the client will receive a callback of the [error](#onerror6) event.
## Modules to Import
```ts
import { webSocket } from '@kit.NetworkKit';
```
## Examples
```ts
import { webSocket } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
let defaultIpAddress = "ws://";
let ws = webSocket.createWebSocket();
ws.on('open', (err:BusinessError, value: Object) => {
if (err != undefined) {
console.log(JSON.stringify(err));
return;
}
// When receiving the on('open') event, the client can use the send() API to communicate with the server.
ws.send("Hello, server!", (err: BusinessError, value: boolean) => {
if (!err) {
console.log("send success");
} else {
console.log("send fail, err:" + JSON.stringify(err));
}
});
});
ws.on('message',(error: BusinessError, value: string | ArrayBuffer) => {
console.log("on message, message:" + value);
// When receiving the `bye` message (the actual message name may differ) from the server, the client proactively disconnects from the server.
if (value === 'bye') {
ws.close((err: BusinessError, value: boolean) => {
if (!err) {
console.log("close success");
} else {
console.log("close fail, err is " + JSON.stringify(err));
}
});
}
});
ws.on('close', (err: BusinessError, value: webSocket.CloseResult) => {
console.log("on close, code is " + value.code + ", reason is " + value.reason);
});
ws.on('error', (err: BusinessError) => {
console.log("on error, error:" + JSON.stringify(err));
});
ws.connect(defaultIpAddress, {
header:{
name1: 'value1',
name2: 'value2',
name3: 'value3'
},
proxy: {
host: '192.168.0.150',
port: 8888,
exclusionList: []
},
protocol: 'my-protocol',
}, (err: BusinessError, value: boolean) => {
if (!err) {
console.log("connect success");
} else {
console.log("connect fail, err:" + JSON.stringify(err));
}
ws.close((err: BusinessError) => {
if (!err) {
console.log("close success");
} else {
console.log("close fail, err is " + JSON.stringify(err));
}
});
});
```
## webSocket.createWebSocket6+
createWebSocket(): WebSocket
Creates 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.
**Atomic service API**: This API can be used in atomic services since API version 11.
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| :---------------------------------- | :----------------------------------------------------------- |
| [WebSocket](#websocket6) | A **WebSocket** object, which contains the **connect**, **send**, **close**, **on**, or **off** method.|
**Example**
```ts
let ws: webSocket.WebSocket = webSocket.createWebSocket();
```
## WebSocket6+
Defines a **WebSocket** object. Before invoking WebSocket APIs, you need to call [webSocket.createWebSocket](#websocketcreatewebsocket6) to create a **WebSocket** object.
### connect6+
connect(url: string, callback: AsyncCallback\): void
Initiates a WebSocket request to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result.
> **NOTE**
> You can listen to **error** events to obtain the operation result. If an error occurs, the error code 200 will be returned.
**Required permissions**: ohos.permission.INTERNET
**Atomic service API**: This API can be used in atomic services since API version 11.
**System capability**: SystemCapability.Communication.NetStack
**Note**: The URL cannot contain more than 1024 characters. Otherwise, the connection fails.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------ | ---- | ---------------------------- |
| url | string | Yes | URL for establishing a WebSocket connection.|
| callback | AsyncCallback\ | Yes | Callback used to return the result. |
**Error codes**
| ID | Error Message |
| --------------------- | ------------------------------------------ |
| 401 | Parameter error. |
| 201 | Permission denied. |
| 230200112+ | Websocket url error. |
| 230200212+ | Websocket certificate file does not exist. |
| 230200312+ | Websocket connection already exists. |
| 230299812+ | It is not allowed to access this domain. |
| 230299910+ | Websocket other unknown error. |
> **NOTE**
> For details about the error codes, see [webSocket Error Codes](errorcode-net-http.md).
**Example**
```ts
import { webSocket } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
let ws = webSocket.createWebSocket();
let url = "ws://";
ws.connect(url, (err: BusinessError, value: boolean) => {
if (!err) {
console.log("connect success");
} else {
console.log("connect fail, err:" + JSON.stringify(err));
}
});
```
### connect6+
connect(url: string, options: WebSocketRequestOptions, callback: AsyncCallback\): void
Initiates 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.
> **NOTE**
> You can listen to **error** events to obtain the operation result. If an error occurs, the error code 200 will be returned.
**Required permissions**: ohos.permission.INTERNET
**Atomic service API**: This API can be used in atomic services since API version 11.
**System capability**: SystemCapability.Communication.NetStack
**Note**: The URL cannot contain more than 1024 characters. Otherwise, the connection fails.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------ | ---- | ------------------------------------------------------- |
| url | string | Yes | URL for establishing a WebSocket connection. |
| options | WebSocketRequestOptions | Yes | Request options. For details, see [WebSocketRequestOptions](#websocketrequestoptions).|
| callback | AsyncCallback\ | Yes | Callback used to return the result. |
**Error codes**
| ID | Error Message |
| --------------------- | ------------------------------------------ |
| 401 | Parameter error. |
| 201 | Permission denied. |
| 230200112+ | Websocket url error. |
| 230200212+ | Websocket certificate file does not exist. |
| 230200312+ | Websocket connection already exists. |
| 230299812+ | It is not allowed to access this domain. |
| 230299910+ | Websocket other unknown error. |
> **NOTE**
> For details about the error codes, see [webSocket Error Codes](errorcode-net-http.md).
**Example**
```ts
import { webSocket } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
let ws = webSocket.createWebSocket();
let options: webSocket.WebSocketRequestOptions | undefined;
if (options !=undefined) {
options.header = {
name1: "value1",
name2: "value2",
name3: "value3"
};
options.caPath = "";
}
let url = "ws://"
ws.connect(url, options, (err: BusinessError, value: Object) => {
if (!err) {
console.log("connect success");
} else {
console.log("connect fail, err:" + JSON.stringify(err))
}
});
```
### connect6+
connect(url: string, options?: WebSocketRequestOptions): Promise\
Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses a promise to return the result.
> **NOTE**
> You can listen to **error** events to obtain the operation result. If an error occurs, the error code 200 will be returned.
**Required permissions**: ohos.permission.INTERNET
**Atomic service API**: This API can be used in atomic services since API version 11.
**System capability**: SystemCapability.Communication.NetStack
**Note**: The URL cannot contain more than 1024 characters. Otherwise, the connection fails.
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ----------------------- | ---- | ------------------------------------------------------- |
| url | string | Yes | URL for establishing a WebSocket connection. |
| options | WebSocketRequestOptions | No | Request options. For details, see [WebSocketRequestOptions](#websocketrequestoptions).|
**Return value**
| Type | Description |
| :----------------- | :-------------------------------- |
| Promise\ | Promise used to return the result.|
**Error codes**
| ID | Error Message |
| --------------------- | ------------------------------------------ |
| 401 | Parameter error. |
| 201 | Permission denied. |
| 230200112+ | Websocket url error. |
| 230200212+ | Websocket certificate file does not exist. |
| 230200312+ | Websocket connection already exists. |
| 230299812+ | It is not allowed to access this domain. |
| 230299910+ | Websocket other unknown error. |
> **NOTE**
> For details about the error codes, see [webSocket Error Codes](errorcode-net-http.md).
**Example**
```ts
import { webSocket } from '@kit.NetworkKit';
let ws = webSocket.createWebSocket();
let url = "ws://"
let promise = ws.connect(url);
promise.then((value: boolean) => {
console.log("connect success")
}).catch((err:string) => {
console.log("connect fail, error:" + JSON.stringify(err))
});
```
### send6+
send(data: string | ArrayBuffer, callback: AsyncCallback\): void
Sends data through a WebSocket connection. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERNET
**Atomic service API**: This API can be used in atomic services since API version 11.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------ | ---- | ------------ |
| data | string \| ArrayBuffer | Yes | Data to send. 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.|
| callback | AsyncCallback\ | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example**
```ts
import { webSocket } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
let ws = webSocket.createWebSocket();
let url = "ws://"
class OutValue {
status: number = 0
message: string = ""
}
ws.connect(url, (err: BusinessError, value: boolean) => {
if (!err) {
console.log("connect success");
} else {
console.log("connect fail, err:" + JSON.stringify(err))
}
});
ws.on('open', (err: BusinessError, value: Object) => {
console.log("on open, status:" + (value as OutValue).status + ", message:" + (value as OutValue).message);
ws.send("Hello, server!", (err: BusinessError, value: boolean) => {
if (!err) {
console.log("send success");
} else {
console.log("send fail, err:" + JSON.stringify(err))
}
});
});
```
> **Description**
>
> The **send** API can be called only after an **open** event is listened.
### send6+
send(data: string | ArrayBuffer): Promise\
Sends data through a WebSocket connection. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INTERNET
**Atomic service API**: This API can be used in atomic services since API version 11.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------ |
| data | string \| ArrayBuffer | Yes | Data to send. 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.|
**Return value**
| Type | Description |
| :----------------- | :-------------------------------- |
| Promise\ | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example**
```ts
import { webSocket } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
let ws = webSocket.createWebSocket();
let url = "ws://"
class OutValue {
status: number = 0
message: string = ""
}
ws.connect(url, (err: BusinessError, value: boolean) => {
if (!err) {
console.log("connect success");
} else {
console.log("connect fail, err:" + JSON.stringify(err))
}
});
ws.on('open', (err: BusinessError, value: Object) => {
console.log("on open, status:" + (value as OutValue).status + ", message:" + (value as OutValue).message);
let promise = ws.send("Hello, server!");
promise.then((value: boolean) => {
console.log("send success")
}).catch((err:string) => {
console.log("send fail, error:" + JSON.stringify(err))
});
});
```
> **Description**
>
> The **send** API can be called only after an **open** event is listened.
### close6+
close(callback: AsyncCallback\): void
Closes a WebSocket connection. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERNET
**Atomic service API**: This API can be used in atomic services since API version 11.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------ | ---- | ---------- |
| callback | AsyncCallback\ | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example**
```ts
import { webSocket } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
let ws = webSocket.createWebSocket();
ws.close((err: BusinessError) => {
if (!err) {
console.log("close success")
} else {
console.log("close fail, err is " + JSON.stringify(err))
}
});
```
### close6+
close(options: WebSocketCloseOptions, callback: AsyncCallback\): void
Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERNET
**Atomic service API**: This API can be used in atomic services since API version 11.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------ | ---- | ----------------------------------------------------- |
| options | WebSocketCloseOptions | Yes | Request options. For details, see [WebSocketCloseOptions](#websocketcloseoptions).|
| callback | AsyncCallback\ | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example**
```ts
import { webSocket } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
let ws = webSocket.createWebSocket();
let options: webSocket.WebSocketCloseOptions | undefined;
if (options != undefined) {
options.code = 1000
options.reason = "your reason"
}
ws.close(options, (err: BusinessError) => {
if (!err) {
console.log("close success")
} else {
console.log("close fail, err is " + JSON.stringify(err))
}
});
```
### close6+
close(options?: WebSocketCloseOptions): Promise\
Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INTERNET
**Atomic service API**: This API can be used in atomic services since API version 11.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | --------------------- | ---- | ----------------------------------------------------- |
| options | WebSocketCloseOptions | No | Request options. For details, see [WebSocketCloseOptions](#websocketcloseoptions).|
**Return value**
| Type | Description |
| :----------------- | :-------------------------------- |
| Promise\ | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example**
```ts
import { webSocket } from '@kit.NetworkKit';
let ws = webSocket.createWebSocket();
let options: webSocket.WebSocketCloseOptions | undefined;
if (options != undefined) {
options.code = 1000
options.reason = "your reason"
}
let promise = ws.close();
promise.then((value: boolean) => {
console.log("close success")
}).catch((err:string) => {
console.log("close fail, err is " + JSON.stringify(err))
});
```
### on('open')6+
on(type: 'open', callback: AsyncCallback\