You need to sign in or sign up before continuing.
提交 0dfc2a58 编写于 作者: S shawn_he

update doc

Signed-off-by: Nshawn_he <shawn.he@huawei.com>
上级 fdf12ab7
......@@ -5,6 +5,10 @@
- [HTTP Data Request](http-request.md)
- [WebSocket Connection](websocket-connection.md)
- [Socket Connection](socket-connection.md)
- [Network Policy Management](net-policy-management.md)
- [Network Sharing](net-sharing.md)
- [Ethernet Connection](net-ethernet.md)
- [Network Connection Management](net-connection-manager.md)
- IPC & RPC
- [IPC & RPC Overview](ipc-rpc-overview.md)
- [IPC & RPC Development](ipc-rpc-development-guideline.md)
......
# Network Connection Management
## Introduction
The Network Connection Management module provides basic network management capabilities, including management of Wi-Fi/cellular/Ethernet connection priorities, network quality evaluation, subscription to network connection status changes, query of network connection information, and DNS resolution.
> **NOTE**
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-connection.md).
## Basic Concepts
- Producer: a provider of data networks, such as Wi-Fi, cellular, and Ethernet.
- Consumer: a user of data networks, for example, an application or a system service.
- Network probe: a mechanism used to detect the network availability to prevent the switch from an available network to an unavailable network. The probe type can be binding network detection, DNS detection, HTTP detection, or HTTPS detection.
- Network selection: a mechanism used to select the optimal network when multiple networks coexist. It is triggered when the network status, network information, or network quality evaluation score changes.
## **Constraints**
- Programming language: C++ and JS
- System: Linux kernel
- The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## When to Use
Typical application scenarios of network connection management are as follows:
- Subscribing to status changes of the specified network
- Obtaining the list of all registered networks
- Querying network connection information based on the data network
- Resolving the domain name of a network to obtain all IP addresses
The following describes the development procedure specific to each application scenario.
## Available APIs
For the complete list of APIs and example code, see [Network Connection Management](../reference/apis/js-apis-net-connection.md).
| Type| API| Description|
| ---- | ---- | ---- |
| ohos.net.connection | function getDefaultNet(callback: AsyncCallback\<NetHandle>): void; |Creates a **NetHandle** object that contains the **netId** of the default network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function getGlobalHttpProxy<sup>10+</sup>(callback: AsyncCallback\<HttpProxy>): void;| Obtains the global HTTP proxy for the network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function setGlobalHttpProxy<sup>10+</sup>(httpProxy: HttpProxy, callback: AsyncCallback<void>): void;| Sets the global HTTP proxy for the network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function getAppNet<sup>9+</sup>(callback: AsyncCallback\<NetHandle>): void;| Obtains a **NetHandle** object that contains the **netId** of the network bound to the application. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function setAppNet<sup>9+</sup>(netHandle: NetHandle, callback: AsyncCallback\<void>): void;| Binds an application to the specified network. The application can access the external network only through this network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function getDefaultNetSync<sup>9+</sup>(): NetHandle; |Obtains the default active data network in synchronous mode. You can use **getNetCapabilities** to obtain information such as the network type and capabilities.|
| ohos.net.connection | function hasDefaultNet(callback: AsyncCallback\<boolean>): void; |Checks whether the default network is available. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function getAllNets(callback: AsyncCallback\<Array\<NetHandle>>): void;| Obtains the list of **NetHandle** objects of the connected network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\<ConnectionProperties>): void; |Obtains link information of the default network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback\<NetCapabilities>): void; |Obtains the capability set of the default network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function isDefaultNetMetered<sup>9+</sup>(callback: AsyncCallback<boolean>): void; |Checks whether the data traffic usage on the current network is metered. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function reportNetConnected(netHandle: NetHandle, callback: AsyncCallback\<void>): void;| Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback\<void>): void;| Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>): void; |Obtains all IP addresses of the specified network by resolving the domain name. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function enableAirplaneMode(callback: AsyncCallback\<void>): void; | Enables the airplane mode. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function disableAirplaneMode(callback: AsyncCallback\<void>): void;| Disables the airplane mode. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection; | Creates a **NetConnection** object. **netSpecifier** specifies the network, and **timeout** specifies the timeout interval in ms. **timeout** is configurable only when **netSpecifier** is specified. If neither of them is present, the default network is used.|
| ohos.net.connection.NetHandle | bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\<void>): void; | Binds a **TCPSocket** or **UDPSocket** to the current network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection.NetHandle | getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>): void; |Obtains all IP addresses of the default network by resolving the domain name. This API uses an asynchronous callback to return the result.|
| ohos.net.connection.NetHandle | getAddressByName(host: string, callback: AsyncCallback\<NetAddress>): void; |Obtains an IP address of the specified network by resolving the domain name. This API uses an asynchronous callback to return the result.|
| ohos.net.connection.NetConnection | on(type: 'netAvailable', callback: Callback\<NetHandle>): void; |Subscribes to **netAvailable** events.|
| ohos.net.connection.NetConnection | on(type: 'netCapabilitiesChange', callback: Callback\<{ netHandle: NetHandle, netCap: NetCapabilities }>): void; |Subscribes to **netCapabilitiesChange** events.|
| ohos.net.connection.NetConnection | on(type: 'netConnectionPropertiesChange', callback: Callback\<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void; |Subscribes to **netConnectionPropertiesChange** events.|
| ohos.net.connection.NetConnection | on(type: 'netBlockStatusChange', callback: Callback<{ netHandle: NetHandle, blocked: boolean }>): void; |Subscribes to **netBlockStatusChange** events.|
| ohos.net.connection.NetConnection | on(type: 'netLost', callback: Callback\<NetHandle>): void; |Subscribes to **netLost** events.|
| ohos.net.connection.NetConnection | on(type: 'netUnavailable', callback: Callback\<void>): void; |Subscribes to **netUnavailable** events.|
| ohos.net.connection.NetConnection | register(callback: AsyncCallback\<void>): void; |Registers an observer for the default network or the network specified in **createNetConnection**.|
| ohos.net.connection.NetConnection | unregister(callback: AsyncCallback\<void>): void; |Unregisters the observer for the default network or the network specified in **createNetConnection**.|
## Subscribing to Status Changes of the Specified Network
1. Import the connection namespace from **@ohos.net.connection.d.ts**.
2. Call **createNetConnection()** to create a **NetConnection** object. You can specify the network type, capability, and timeout interval. If you do not specify parameters, the default values will be used.
3. Call **conn.on()** to subscribe to the target event. You must pass in **type** and **callback**.
4. Call **conn.register()** to subscribe to network status changes of the specified network.
5. When the network is available, the callback will be invoked to return the **netAvailable** event. When the network is unavailable, the callback will be invoked to return the **netUnavailable** event.
6. Call **conn.unregister()** to unsubscribe from the network status changes if required.
```js
// Import the connection namespace.
import connection from '@ohos.net.connection'
let netCap = {
// Assume that the default network is Wi-Fi. If you need to create a cellular network connection, set the network type to CELLULAR.
bearerTypes: [connection.NetBearType.BEARER_CELLULAR],
// Set the network capability to INTERNET.
networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET],
};
let netSpec = {
netCapabilities: netCap,
};
// Set the timeout value to 10s. The default value is 0.
let timeout = 10 * 1000;
// Create a NetConnection object.
let conn = connection.createNetConnection(netSpec, timeout);
// Listen to network status change events. If the network is available, an on_netAvailable event is returned.
conn.on('netAvailable', (data=> {
console.log("net is available, netId is " + data.netId);
}));
// Listen to network status change events. If the network is unavailable, an on_netUnavailable event is returned.
conn.on('netUnavailable', (data=> {
console.log("net is unavailable, netId is " + data.netId);
}));
// Register an observer for network status changes.
conn.register((err, data) => {});
// Unregister the observer for network status changes.
conn.unregister((err, data) => {});
```
## Obtaining the List of All Registered Networks
### How to Develop
1. Import the connection namespace from **@ohos.net.connection.d.ts**.
2. Call **getAllNets** to obtain the list of all connected networks.
```js
// Import the connection namespace.
import connection from '@ohos.net.connection'
// Obtain the list of all connected networks.
connection.getAllNets((err, data) => {
console.log(JSON.stringify(err));
console.log(JSON.stringify(data));
if (data) {
this.netList = data;
}
})
```
## Querying Network Capability Information and Connection Information of Specified Data Network
### How to Develop
1. Import the connection namespace from **@ohos.net.connection.d.ts**.
2. Call **getDefaultNet** to obtain the default data network via **NetHandle** or call **getAllNets** to obtain the list of all connected networks via **Array\<NetHandle>**.
3. Call **getNetCapabilities** to obtain the network capability information of the data network specified by **NetHandle**. The capability information includes information such as the network type (cellular, Wi-Fi, or Ethernet network) and the specific network capabilities.
4. Call **getConnectionProperties** to obtain the connection information of the data network specified by **NetHandle**.
```js
// Import the connection namespace.
import connection from '@ohos.net.connection'
// Call getDefaultNet to obtain the default data network specified by **NetHandle**.
connection.getDefaultNet((err, data) => {
console.log(JSON.stringify(err));
console.log(JSON.stringify(data));
if (data) {
this.netHandle = data;
}
})
// Obtain the network capability information of the data network specified by **NetHandle**. The capability information includes information such as the network type and specific network capabilities.
connection.getNetCapabilities(this.netHandle, (err, data) => {
console.log(JSON.stringify(err));
// Obtain the network type via bearerTypes.
for (let item of data.bearerTypes) {
if (item == 0) {
// Cellular network
console.log(JSON.stringify("BEARER_CELLULAR"));
} else if (item == 1) {
// Wi-Fi network
console.log(JSON.stringify("BEARER_WIFI"));
} else if (item == 3) {
// Ethernet network
console.log(JSON.stringify("BEARER_ETHERNET"));
}
}
// Obtain the specific network capabilities via networkCap.
for (let item of data.networkCap) {
if (item == 0) {
// The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages.
console.log(JSON.stringify("NET_CAPABILITY_MMS"));
} else if (item == 11) {
// The network traffic is not metered.
console.log(JSON.stringify("NET_CAPABILITY_NOT_METERED"));
} else if (item == 12) {
// The network has the Internet access capability, which is set by the network provider.
console.log(JSON.stringify("NET_CAPABILITY_INTERNET"));
} else if (item == 15) {
// The network does not use a Virtual Private Network (VPN).
console.log(JSON.stringify("NET_CAPABILITY_NOT_VPN"));
} else if (item == 16) {
// The Internet access capability of the network is successfully verified by the connection management module.
console.log(JSON.stringify("NET_CAPABILITY_VALIDATED"));
}
}
})
// Obtain the connection information of the data network specified by NetHandle. Connection information includes link and route information.
connection.getConnectionProperties(this.netHandle, (err, data) => {
console.log(JSON.stringify(err));
console.log(JSON.stringify(data));
})
// Call getAllNets to obtain the list of all connected networks via Array<NetHandle>.
connection.getAllNets((err, data) => {
console.log(JSON.stringify(err));
console.log(JSON.stringify(data));
if (data) {
this.netList = data;
}
})
for (let item of this.netList) {
// Obtain the network capability information of the network specified by each netHandle on the network list cyclically.
connection.getNetCapabilities(item, (err, data) => {
console.log(JSON.stringify(err));
console.log(JSON.stringify(data));
})
// Obtain the connection information of the network specified by each netHandle on the network list cyclically.
connection.getConnectionProperties(item, (err, data) => {
console.log(JSON.stringify(err));
console.log(JSON.stringify(data));
})
}
```
## Resolving the domain name of a network to obtain all IP addresses
### How to Develop
1. Import the connection namespace from **@ohos.net.connection.d.ts**.
2. Call **getAddressesByName** to use the default network to resolve the host name to obtain the list of all IP addresses.
```js
// Import the connection namespace.
import connection from '@ohos.net.connection'
// Use the default network to resolve the host name to obtain the list of all IP addresses.
connection.getAddressesByName(this.host, (err, data) => {
console.log(JSON.stringify(err));
console.log(JSON.stringify(data));
})
```
# Ethernet Connection
## Introduction
The Ethernet Connection module allows a device to access the Internet through a network cable.
After a device is connected to the Ethernet through a network cable, the device can obtain a series of network attributes, such as the dynamically allocated IP address, subnet mask, gateway, and DNS. You can manually configure and obtain the network attributes of the device in static mode.
> **NOTE**
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-ethernet.md).
## **Constraints**
- Programming language: C++ and JS
- System: Linux kernel
- The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## When to Use
Typical application scenarios of Ethernet connection are as follows:
- Dynamically assigning a series of network attributes, such as the IP address, subnet mask, gateway, and DNS in DHCP mode to enable network access
- Configuring a series of network attributes, such as the IP address, subnet mask, gateway, and DNS, in static mode to enable network access.
The following describes the development procedure specific to each application scenario.
## Available APIs
For the complete list of APIs and example code, see [Ethernet Connection](../reference/apis/js-apis-net-ethernet.md).
| Type| API| Description|
| ---- | ---- | ---- |
| ohos.net.ethernet | function setIfaceConfig(iface: string, ic: InterfaceConfiguration, callback: AsyncCallback\<void>): void | Configures the network attributes of the specified Ethernet network. This API uses an asynchronous callback to return the result.|
| ohos.net.ethernet | function getIfaceConfig(iface: string, callback: AsyncCallback\<InterfaceConfiguration>): void | Obtains the network attributes of the specified Ethernet network. This API uses an asynchronous callback to return the result.|
| ohos.net.ethernet | function isIfaceActive(iface: string, callback: AsyncCallback\<number>): void | Checks whether the specified network port is active. This API uses an asynchronous callback to return the result.|
| ohos.net.ethernet | function getAllActiveIfaces(callback: AsyncCallback\<Array\<string>>): void; | Obtains the list of all active network ports. This API uses an asynchronous callback to return the result.|
## Ethernet Connection – DHCP Mode
1. Use a network cable to connect the device to a network port.
2. Import the **ethernet** namespace from **@ohos.net.ethernet**.
3. Call **getAllActiveIfaces** to obtain the list of all active network ports, for example, **eth0** and **eth1**.
4. Call **isIfaceActive** in user mode to check whether the **eth0** port is active.
5. Call **getIfaceConfig** in user mode to obtain the static network attributes of the **eth0** port. By default, an unconfigured Ethernet network uses the DHCP mode, in which the Ethernet network obtains the automatically assigned network attributes.
```js
// Import the ethernet namespace from @ohos.net.ethernet.
import ethernet from '@ohos.net.ethernet'
// Call getAllActiveIfaces to obtain the list of all active network ports.
ethernet.getAllActiveIfaces((error, data) => {
if (error) {
console.log("getAllActiveIfaces callback error = " + error);
} else {
console.log("getAllActiveIfaces callback data.length = " + data.length);
for (let i = 0; i < data.length; i++) {
console.log("getAllActiveIfaces callback = " + data[i]);
}
}
});
// Call isIfaceActive to check whether the specified network port is active.
ethernet.isIfaceActive("eth0", (error, data) => {
if (error) {
console.log("isIfaceActive callback error = " + error);
} else {
console.log("isIfaceActive callback = " + data);
}
});
// Call getIfaceConfig to obtain the network attributes of the specified Ethernet network.
ethernet.getIfaceConfig("eth0", (error, data) => {
if (error) {
console.log("getIfaceConfig callback error = " + error);
} else {
console.log("getIfaceConfig callback mode = " + data.mode);
console.log("getIfaceConfig callback ipAddr = " + data.ipAddr);
console.log("getIfaceConfig callback routeAddr = " + data.routeAddr);
console.log("getIfaceConfig callback gateAddr = " + data.gateAddr);
console.log("getIfaceConfig callback maskAddr = " + data.maskAddr);
console.log("getIfaceConfig callback dns0Addr = " + data.dns0Addr);
console.log("getIfaceConfig callback dns1Addr = " + data.dns1Addr);
}
});
```
## Ethernet Connection – Static Mode
### How to Develop
1. Use a network cable to connect the device to a network port.
2. Import the **ethernet** namespace from **@ohos.net.ethernet**.
3. Call **getAllActiveIfaces** in user mode to obtain the list of all active network ports, for example, **eth0** and **eth1**.
4. Call **isIfaceActive** in user mode to check whether the **eth0** port is active.
5. Call **setIfaceConfig** in user mode to set the **eth0** port to the static mode, in which you need to manually assign the network attributes (including the IP address, subnet mask, gateway, and DNS).
6. Call **getIfaceConfig** in user mode to obtain the static network attributes of the **eth0** port.
```js
// Import the ethernet namespace from @ohos.net.ethernet.
import ethernet from '@ohos.net.ethernet'
// Call getAllActiveIfaces to obtain the list of all active network ports.
ethernet.getAllActiveIfaces((error, data) => {
if (error) {
console.log("getAllActiveIfaces callback error = " + error);
} else {
console.log("getAllActiveIfaces callback data.length = " + data.length);
for (let i = 0; i < data.length; i++) {
console.log("getAllActiveIfaces callback = " + data[i]);
}
}
});
// Call isIfaceActive to check whether the specified network port is active.
ethernet.isIfaceActive("eth0", (error, data) => {
if (error) {
console.log("isIfaceActive callback error = " + error);
} else {
console.log("isIfaceActive callback = " + data);
}
});
// Call setIfaceConfig to configure the network attributes of the specified Ethernet network.
ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.xx.xx", routeAddr:"192.168.xx.xx",
gateAddr:"192.168.xx.xx", maskAddr:"255.255.xx.xx", dnsAddr0:"1.1.xx.xx", dnsAddr1:"2.2.xx.xx"},(error) => {
if (error) {
console.log("setIfaceConfig callback error = " + error);
} else {
console.log("setIfaceConfig callback ok ");
}
});
// Call getIfaceConfig to obtain the network attributes of the specified Ethernet network.
ethernet.getIfaceConfig("eth0", (error, data) => {
if (error) {
console.log("getIfaceConfig callback error = " + error);
} else {
console.log("getIfaceConfig callback mode = " + data.mode);
console.log("getIfaceConfig callback ipAddr = " + data.ipAddr);
console.log("getIfaceConfig callback routeAddr = " + data.routeAddr);
console.log("getIfaceConfig callback gateAddr = " + data.gateAddr);
console.log("getIfaceConfig callback maskAddr = " + data.maskAddr);
console.log("getIfaceConfig callback dns0Addr = " + data.dns0Addr);
console.log("getIfaceConfig callback dns1Addr = " + data.dns1Addr);
}
});
```
......@@ -2,15 +2,19 @@
Network management functions include:
- [HTTP Data Request](http-request.md): Initiates a data request through HTTP.
- [WebSocket Connection](websocket-connection.md): Establishes a bidirectional connection between the server and client through WebSocket.
- [Socket Connection](socket-connection.md): Transmits data through Socket.
- [HTTP data request](http-request.md): Initiates a data request through HTTP.
- [WebSocket connection](websocket-connection.md): Establishes a bidirectional connection between the server and client through WebSocket.
- [Socket connection](socket-connection.md): Transmits data through Socket.
- [Network policy management](net-policy-management.md): Restricts network capabilities by setting network policies, including cellular network policy, sleep/power-saving mode policy, and background network policy, and resets network policies as needed.
- [Network sharing](net-sharing.md): Shares a device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing, and queries the network sharing state and shared mobile data volume.
- [Ethernet connection](net-ethernet.md): Provides wired network capabilities, which allow you to set the IP address, subnet mask, gateway, and Domain Name System (DNS) server of a wired network.
- [Network connection management](net-connection-manager.md): Provides basic network management capabilities, including management of Wi-Fi/cellular/Ethernet connection priorities, network quality evaluation, subscription to network connection status changes, query of network connection information, and DNS resolution.
## Constraints
To use the functions of the network management module, you must obtain the permissions listed in the following table.
| Permission | Description |
| Permission | Description |
| -------------------------------- | -------------------------------------- |
| ohos.permission.GET_NETWORK_INFO | Allows an application to obtain the network connection information. |
| ohos.permission.SET_NETWORK_INFO | Allows an application to modify the network connection state. |
......
# Network Sharing
## Introduction
The Network Sharing module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing. It also allows you to query the network sharing state and shared mobile data volume.
> **NOTE**
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-sharing.md).
## Basic Concepts
- Wi-Fi sharing: Shares the network through a Wi-Fi hotspot.
- Bluetooth sharing: Shares the network through Bluetooth.
- USB tethering: Shares the network using a USB flash drive.
## **Constraints**
- Programming language: C++ and JS
- System: Linux kernel
- The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## When to Use
Typical network sharing scenarios are as follows:
- Enabling network sharing
- Disabling network sharing
- Obtaining the data traffic of the shared network
The following describes the development procedure specific to each application scenario.
## Available APIs
For the complete list of APIs and example code, see [Network Sharing](../reference/apis/js-apis-net-sharing.md).
| Type| API| Description|
| ---- | ---- | ---- |
| ohos.net.sharing | function isSharingSupported(callback: AsyncCallback\<boolean>): void; | Checks whether the system supports network sharing. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function isSharing(callback: AsyncCallback\<boolean>): void; | Checks whether network sharing is active. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function startSharing(type: SharingIfaceType, callback: AsyncCallback\<void>): void; | Starts network sharing. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function stopSharing(type: SharingIfaceType, callback: AsyncCallback\<void>): void; | Stops network sharing. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function getStatsRxBytes(callback: AsyncCallback\<number>): void; | Obtains the received data traffic during network sharing, in KB. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function getStatsTxBytes(callback: AsyncCallback\<number>): void; | Obtains the sent data traffic during network sharing, in KB. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function getStatsTotalBytes(callback: AsyncCallback\<number>): void; | Obtains the total data traffic during network sharing, in KB. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function getSharingIfaces(state: SharingIfaceState, callback: AsyncCallback\<Array\<string>>): void; | Obtains the names of network interface cards (NICs) in the specified network sharing state.. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function getSharingState(type: SharingIfaceType, callback: AsyncCallback\<SharingIfaceState>): void; | Obtains the network sharing state of the specified type. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function getSharableRegexes(type: SharingIfaceType, callback: AsyncCallback\<Array\<string>>): void; | Obtains regular expressions of NICs of a specified type. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function on(type: 'sharingStateChange', callback: Callback\<boolean>): void; | Subscribes to network sharing state changes.|
| ohos.net.sharing | function off(type: 'sharingStateChange', callback?: Callback\<boolean>): void; | Unsubscribes from network sharing state changes.|
| ohos.net.sharing | unction on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void; | Subscribes to network sharing state changes of the specified NIC.|
| ohos.net.sharing | function off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void; | Unsubscribes from network sharing state changes of the specified NIC.|
| ohos.net.sharing | function on(type: 'sharingUpstreamChange', callback: Callback\<NetHandle>): void; | Subscribes to upstream NIC changes.|
| ohos.net.sharing | function off(type: 'sharingUpstreamChange', callback?: Callback\<NetHandle>): void; | Unsubscribes from upstream NIC changes.|
## Enabling Network Sharing
1. Import the **sharing** namespace from **@ohos.net.sharing**.
2. Subscribe to network sharing state changes.
3. Call **startSharing** to start network sharing of the specified type.
4. Return the callback for successfully starting network sharing.
```js
// Import the sharing namespace from @ohos.net.sharing.
import sharing from '@ohos.net.sharing'
// Subscribe to network sharing state changes.
sharing.on('sharingStateChange', (error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
// Call startSharing to start network sharing of the specified type.
sharing.startSharing(SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
});
```
## Disabling network sharing
### How to Develop
1. Import the **sharing** namespace from **@ohos.net.sharing**.
2. Subscribe to network sharing state changes.
3. Call **stopSharing** to stop network sharing of the specified type.
4. Return the callback for successfully stopping network sharing.
```js
// Import the sharing namespace from @ohos.net.sharing.
import sharing from '@ohos.net.sharing'
// Subscribe to network sharing state changes.
sharing.on('sharingStateChange', (error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
// Call stopSharing to stop network sharing of the specified type.
sharing.stopSharing(SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
});
```
## Obtaining the data traffic of the shared network
### How to Develop
1. Import the **sharing** namespace from **@ohos.net.sharing**.
2. Call **startSharing** to start network sharing of the specified type.
3. Call **getStatsTotalBytes** to obtain the data traffic generated during data sharing.
4. Call **stopSharing** to stop network sharing of the specified type and clear the data volume of network sharing.
```js
// Import the sharing namespace from @ohos.net.sharing.
import sharing from '@ohos.net.sharing'
// Call startSharing to start network sharing of the specified type.
sharing.startSharing(SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
});
// Call getStatsTotalBytes to obtain the data traffic generated during data sharing.
sharing.getStatsTotalBytes((error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
// Call stopSharing to stop network sharing of the specified type and clear the data volume of network sharing.
sharing.stopSharing(SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
});
// Call getStatsTotalBytes again. The data volume of network sharing has been cleared.
sharing.getStatsTotalBytes((error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
```
# Socket Connection
## Introduction
## Use Cases
The Socket Connection module allows an application to transmit data over a Socket connection through the TCP, UDP, or TLS protocol.
Your application can transmit data through Socket connections. Currently, the TCP and UDP protocols are supported.
## Basic Concepts
- Socket: An abstraction of endpoints for bidirectional communication between application processes running on different hosts in a network.
- TCP: Transmission Control Protocol, which is a byte stream–based transport layer communication protocol that is connection-oriented and reliable.
- UDP: User Datagram Protocol, which is a simple datagram-oriented transport layer communication protocol.
- TLS: Transport Layer Security, which is a protocol that ensures the data confidentiality and integrity between communication programs.
## When to Use
Applications transmit data over TCP, UDP, or TLS Socket connections. The main application scenarios are as follows:
- Implementing data transmission over TCP/UDP Socket connections
- Implementing encrypted data transmission over TLS Socket connections
## Available APIs
The Socket connection function is mainly implemented by the Socket module. The following table describes the related APIs.
For the complete list of APIs and example code, see [Socket Connection](../reference/apis/js-apis-socket.md).
Socket connection functions are mainly implemented by the **socket** module. The following table describes the related APIs.
| API| Description |
| API| Description|
| -------- | -------- |
| constructUDPSocketInstance() | Creates a **UDPSocket** object. |
| constructTCPSocketInstance() | Creates a **TCPSocket** object. |
| bind() | Binds the IP address and port number. |
| constructUDPSocketInstance() | Creates a **UDPSocket** object.|
| constructTCPSocketInstance() | Creates a **TCPSocket** object.|
| bind() | Binds the IP address and port number.|
| send() | Sends data.|
| close() | Closes a Socket connection. |
| getState() | Obtains the Socket connection status. |
| connect() | Connects to the specified IP address and port. This function is supported only for TCP. |
| getRemoteAddress() | Obtains the peer address of the Socket connection. This function is supported only for TCP. The **connect** API must have been called before you use this API. |
| on(type:&nbsp;'message') | Enables listening for **message** events of the Socket connection. |
| off(type:&nbsp;'message') | Disables listening for **message** events of the Socket connection. |
| on(type:&nbsp;'close') | Enables listening for **close** events of the Socket connection. |
| off(type:&nbsp;'close') | Disables listening for **close** events of the Socket connection. |
| on(type:&nbsp;'error') | Enables listening for **error** events of the Socket connection. |
| off(type:&nbsp;'error') | Disables listening for **error** events of the Socket connection. |
| on(type:&nbsp;'listening') | Enables listening for **listening** events of the UDPSocket connection. |
| off(type:&nbsp;'listening') | Disables listening for **listening** events of the UDPSocket connection. |
| on(type:&nbsp;'connect') | Enables listening for **connect** events of the TCPSocket connection. |
| off(type:&nbsp;'connect') | Disables listening for **connect** events of the TCPSocket connection. |
| close() | Closes a Socket connection.|
| getState() | Obtains the Socket connection status.|
| connect() | Connects to the specified IP address and port. This function is supported only for TCP.|
| getRemoteAddress() | Obtains the peer address of the Socket connection. This function is supported only for TCP. The **connect** API must have been called before you use this API.|
| on(type:&nbsp;'message') | Subscribes to **message** events of the Socket connection.|
| off(type:&nbsp;'message') | Unsubscribes from **message** events of the Socket connection.|
| on(type:&nbsp;'close') | Subscribes to **close** events of the Socket connection.|
| off(type:&nbsp;'close') | Unsubscribes from **close** events of the Socket connection.|
| on(type:&nbsp;'error') | Subscribes to **error** events of the Socket connection.|
| off(type:&nbsp;'error') | Unsubscribes from **error** events of the Socket connection.|
| on(type:&nbsp;'listening') | Subscribes to **listening** events of the UDP Socket connection. |
| off(type:&nbsp;'listening') | Unsubscribes from **listening** events of the UDP Socket connection. |
| on(type:&nbsp;'connect') | Subscribes to **connect** events of the TCP Socket connection. |
| off(type:&nbsp;'connect') | Unsubscribes from **connect** events of the TCP Socket connection.|
TLS Socket connection functions are mainly provided by the **tls_socket** module. The following table describes the related APIs.
| API| Description|
| -------- | -------- |
| bind() | Binds the IP address and port number.|
| close(type:&nbsp;'error') | Closes a Socket connection.|
| connect() | Sets up a connection to the specified IP address and port number.|
| getCertificate() | Obtains an object representing the local certificate.|
| getCipherSuite() | Obtains a list containing information about the negotiated cipher suite.|
| getProtocol() | Obtains a string containing the SSL/TLS protocol version negotiated for the current connection.|
| getRemoteAddress() | Obtains the peer address of the TLS Socket connection.|
| getRemoteCertificate() | Obtains an object representing a peer certificate.|
| getSignatureAlgorithms() | Obtains a list containing signature algorithms shared between the server and client, in descending order of priority.|
| getState() | Obtains the TLS Socket connection status.|
| off(type:&nbsp;'close') | Unsubscribes from **close** events of the TLS Socket connection.|
| off(type:&nbsp;'error') | Unsubscribes from **error** events of the TLS Socket connection.|
| off(type:&nbsp;'message') | Unsubscribes from **message** events of the TLS Socket connection.|
| on(type:&nbsp;'close') | Subscribes to **close** events of the TLS Socket connection.|
| on(type:&nbsp;'error') | Subscribes to **error** events of the TLS Socket connection.|
| on(type:&nbsp;'message') | Subscribes to **message** events of the TLS Socket connection.|
| send() | Sends data.|
| setExtraOptions() | Sets other properties of the TLS Socket connection.|
## How to Develop
## Transmitting Data over TCP/UDP Socket Connections
The implementation is similar for UDPSocket and TCPSocket. The following uses the TCPSocket as an example.
The implementation is similar for UDP Socket and TCP Socket connections. The following uses data transmission over a TCP Socket connection as an example.
1. Import the required Socket module.
1. Import the required **socket** module.
2. Create a **TCPSocket** object.
3. (Optional) Enable listening for TCPSocket events.
3. (Optional) Subscribe to TCP Socket connection events.
4. Bind the IP address and port number. The port number can be specified or randomly allocated by the system.
......@@ -48,15 +84,15 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
6. Send data.
7. Enable the TCPSocket connection to be automatically closed after use.
7. Enable the TCP Socket connection to be automatically closed after use.
```js
import socket from '@ohos.net.socket'
// Create a TCPSocket object.
let tcp = socket.constructTCPSocketInstance();
// Enable listening for TCPSocket events.
// Subscribe to TCP Socket connection events.
tcp.on('message', value => {
console.log("on message")
let buffer = value.message
......@@ -73,7 +109,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
tcp.on('close', () => {
console.log("on close")
});
// Bind the local IP address and port number.
let bindAddress = {
address: '192.168.xx.xx',
......@@ -86,6 +122,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
return;
}
console.log('bind success');
// Set up a connection to the specified IP address and port number.
let connectAddress = {
address: '192.168.xx.xx',
......@@ -100,6 +137,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
return;
}
console.log('connect success');
// Send data.
tcp.send({
data: 'Hello, server!'
......@@ -112,7 +150,8 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
})
});
});
// Enable the TCPSocket connection to be automatically closed after use. Then, disable listening for TCPSocket events.
// Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events.
setTimeout(() => {
tcp.close((err) => {
console.log('close socket.')
......@@ -122,3 +161,167 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
tcp.off('close');
}, 30 * 1000);
```
## Implementing Encrypted Data Transmission over TLS Socket Connections
### How to Develop
TLS Socket connection process on the client:
1. Import the required **socket** module.
2. Bind the IP address and port number of the server.
3. For two-way authentication, upload the client CA certificate and digital certificate. For one-way authentication, upload the client CA certificate.
4. Create a **TLSSocket** object.
5. (Optional) Subscribe to TLS Socket connection events.
6. Send data.
7. Enable the TLS Socket connection to be automatically closed after use.
```js
import socket from '@ohos.net.socket'
// Create a TLS Socket connection (for two-way authentication).
let tlsTwoWay = socket.constructTLSSocketInstance();
// Subscribe to TLS Socket connection events.
tcp.on('message', value => {
console.log("on message")
let buffer = value.message
let dataView = new DataView(buffer)
let str = ""
for (let i = 0; i < dataView.byteLength; ++i) {
str += String.fromCharCode(dataView.getUint8(i))
}
console.log("on connect received:" + str)
});
tcp.on('connect', () => {
console.log("on connect")
});
tcp.on('close', () => {
console.log("on close")
});
// Bind the local IP address and port number.
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
// Set the communication parameters.
let options = {
ALPNProtocols: ["spdy/1", "http/1.1"],
// Set up a connection to the specified IP address and port number.
address: {
address: "192.168.xx.xxx",
port: xxxx, // Port
family: 1,
},
// Set the parameters used for authentication during communication.
secureOptions: {
key: "xxxx", // Key
cert: "xxxx", // Digital certificate
ca: ["xxxx"], // CA certificate
passwd: "xxxx", // Password for generating the key
protocols: [socket.Protocol.TLSv12], // Communication protocol
useRemoteCipherPrefer: true, // Whether to preferentially use the peer cipher suite
signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", // Signature algorithm
cipherSuite: "AES256-SHA256", // Cipher suite
},
};
// Set up a connection.
tlsTwoWay.connect(options, (err, data) => {
console.error(err);
console.log(data);
});
// Enable the TLS Socket connection to be automatically closed after use. Then, disable listening for TLS Socket connection events.
tls.close((err) => {
if (err) {
console.log("close callback error = " + err);
} else {
console.log("close success");
}
tls.off('message');
tls.off('connect');
tls.off('close');
});
// Create a TLS Socket connection (for one-way authentication).
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
// Subscribe to TLS Socket connection events.
tcp.on('message', value => {
console.log("on message")
let buffer = value.message
let dataView = new DataView(buffer)
let str = ""
for (let i = 0;i < dataView.byteLength; ++i) {
str += String.fromCharCode(dataView.getUint8(i))
}
console.log("on connect received:" + str)
});
tcp.on('connect', () => {
console.log("on connect")
});
tcp.on('close', () => {
console.log("on close")
});
// Bind the local IP address and port number.
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
// Set the communication parameters.
let oneWayOptions = {
address: {
address: "192.168.xxx.xxx",
port: xxxx,
family: 1,
},
secureOptions: {
ca: ["xxxx","xxxx"], // CA certificate
cipherSuite: "AES256-SHA256", // Cipher suite
},
};
// Set up a connection.
tlsOneWay.connect(oneWayOptions, (err, data) => {
console.error(err);
console.log(data);
});
// Enable the TLS Socket connection to be automatically closed after use. Then, disable listening for TLS Socket connection events.
tls.close((err) => {
if (err) {
console.log("close callback error = " + err);
} else {
console.log("close success");
}
tls.off('message');
tls.off('connect');
tls.off('close');
});
```
## Samples
The following samples are provided to help you better understand how to develop Socket connection features:
- [`Socket`: Socket Connection (ArkTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Network/Socket)
- [UDP Socket (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/UdpDemoOH)
- [TCP Socket (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/TcpSocketDemo)
此差异已折叠。
# @ohos.net.webSocket (WebSocket Connection)
# # @ohos.net.webSocket (WebSocket Connection)
The **webSocket** module implements WebSocket connection management and operation.
> **NOTE**<br>
> 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.
> **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](#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.
......@@ -17,7 +16,7 @@ If an error occurs in any of the preceding processes, the client will receive a
import webSocket from '@ohos.net.webSocket';
```
## Complete Example
## Examples
```js
import webSocket from '@ohos.net.webSocket';
......@@ -37,7 +36,7 @@ ws.on('open', (err, value) => {
});
ws.on('message', (err, value) => {
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.
// 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, value) => {
if (!err) {
......@@ -49,7 +48,7 @@ ws.on('message', (err, value) => {
}
});
ws.on('close', (err, value) => {
console.log("on close, code is " + value['code'] + ", reason is " + value['reason']);
console.log("on close, code is " + value.code + ", reason is " + value.reason);
});
ws.on('error', (err) => {
console.log("on error, error:" + JSON.stringify(err));
......@@ -71,7 +70,7 @@ Creates a WebSocket connection. You can use this API to create or close a WebSoc
**System capability**: SystemCapability.Communication.NetStack
**Return Value**
**Return value**
| Type | Description |
| :---------------------------------- | :----------------------------------------------------------- |
......@@ -94,7 +93,7 @@ connect\(url: string, callback: AsyncCallback<boolean\>\): void
Initiates a WebSocket request to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
......@@ -105,6 +104,12 @@ Initiates a WebSocket request to establish a WebSocket connection to a given URL
| url | string | Yes | URL for establishing a WebSocket connection.|
| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example**
......@@ -127,7 +132,7 @@ connect\(url: string, options: WebSocketRequestOptions, callback: AsyncCallback<
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.
**Required permission**: ohos.permission.INTERNET
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
......@@ -139,6 +144,12 @@ Initiates a WebSocket request carrying specified options to establish a WebSocke
| options | WebSocketRequestOptions | Yes | Request options. For details, see [WebSocketRequestOptions](#websocketrequestoptions).|
| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example**
......@@ -166,7 +177,7 @@ connect\(url: string, options?: WebSocketRequestOptions\): Promise<boolean\>
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.
**Required permission**: ohos.permission.INTERNET
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
......@@ -177,12 +188,19 @@ Initiates a WebSocket request carrying specified options to establish a WebSocke
| url | string | Yes | URL for establishing a WebSocket connection. |
| options | WebSocketRequestOptions | No | Request options. For details, see [WebSocketRequestOptions](#websocketrequestoptions).|
**Return Value**
**Return value**
| Type | Description |
| :----------------- | :-------------------------------- |
| Promise\<boolean\> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example**
```js
......@@ -203,7 +221,7 @@ send\(data: string | ArrayBuffer, callback: AsyncCallback<boolean\>\): void
Sends data through a WebSocket connection. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
......@@ -214,6 +232,13 @@ Sends data through a WebSocket connection. This API uses an asynchronous callbac
| data | string \| ArrayBuffer <sup>8+</sup> | Yes | Data to send.|
| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example**
```js
......@@ -237,7 +262,7 @@ send\(data: string | ArrayBuffer\): Promise<boolean\>
Sends data through a WebSocket connection. This API uses a promise to return the result.
**Required permission**: ohos.permission.INTERNET
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
......@@ -247,12 +272,19 @@ Sends data through a WebSocket connection. This API uses a promise to return the
| ------ | ------ | ---- | ------------ |
| data | string \| ArrayBuffer <sup>8+</sup> | Yes | Data to send.|
**Return Value**
**Return value**
| Type | Description |
| :----------------- | :-------------------------------- |
| Promise\<boolean\> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example**
```js
......@@ -275,7 +307,7 @@ close\(callback: AsyncCallback<boolean\>\): void
Closes a WebSocket connection. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
......@@ -285,6 +317,13 @@ Closes a WebSocket connection. This API uses an asynchronous callback to return
| -------- | ------------------------ | ---- | ---------- |
| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example**
```js
......@@ -306,7 +345,7 @@ close\(options: WebSocketCloseOptions, callback: AsyncCallback<boolean\>\): void
Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.INTERNET
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
......@@ -317,6 +356,13 @@ Closes a WebSocket connection carrying specified options such as **code** and **
| options | WebSocketCloseOptions | Yes | Request options. For details, see [WebSocketCloseOptions](#websocketcloseoptions).|
| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example**
```js
......@@ -341,7 +387,7 @@ close\(options?: WebSocketCloseOptions\): Promise<boolean\>
Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses a promise to return the result.
**Required permission**: ohos.permission.INTERNET
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
......@@ -351,12 +397,19 @@ Closes a WebSocket connection carrying specified options such as **code** and **
| ------- | --------------------- | ---- | ----------------------------------------------------- |
| options | WebSocketCloseOptions | No | Request options. For details, see [WebSocketCloseOptions](#websocketcloseoptions).|
**Return Value**
**Return value**
| Type | Description |
| :----------------- | :-------------------------------- |
| Promise\<boolean\> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | ----------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
**Example**
```js
......@@ -406,7 +459,7 @@ off\(type: 'open', callback?: AsyncCallback<Object\>\): void
Disables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>**NOTE**
>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.
**System capability**: SystemCapability.Communication.NetStack
......@@ -437,7 +490,7 @@ on\(type: 'message', callback: AsyncCallback<string | ArrayBuffer\>\): void
Enables 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.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>**NOTE**
>The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\).
**System capability**: SystemCapability.Communication.NetStack
......@@ -449,7 +502,6 @@ Enables listening for the **message** events of a WebSocket connection. This API
| type | string | Yes | Event type.<br />**message**: event indicating that a message has been received from the server.|
| callback | AsyncCallback\<string \| ArrayBuffer <sup>8+</sup>\> | Yes | Callback used to return the result. |
**Example**
```js
......@@ -466,7 +518,7 @@ off\(type: 'message', callback?: AsyncCallback<string | ArrayBuffer\>\): void
Disables 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.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>**NOTE**
>The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\).
>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.
......@@ -507,7 +559,7 @@ Enables listening for the **close** events of a WebSocket connection. This API u
```js
let ws = webSocket.createWebSocket();
ws.on('close', (err, value) => {
console.log("on close, code is " + value['code'] + ", reason is " + value['reason']);
console.log("on close, code is " + value.code + ", reason is " + value.reason);
});
```
......@@ -518,7 +570,7 @@ off\(type: 'close', callback?: AsyncCallback<\{ code: number, reason: string \}\
Disables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>**NOTE**
>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.
**System capability**: SystemCapability.Communication.NetStack
......@@ -530,7 +582,6 @@ Disables listening for the **close** events of a WebSocket connection. This API
| type | string | Yes | Event type. <br />**close**: event indicating that a WebSocket connection has been closed.|
| callback | AsyncCallback<{ code: number, reason: string }> | No | Callback used to return the result. |
**Example**
```js
......@@ -554,7 +605,6 @@ Enables listening for the **error** events of a WebSocket connection. This API u
| type | string | Yes | Event type.<br />**error**: event indicating the WebSocket connection has encountered an error.|
| callback | ErrorCallback | Yes | Callback used to return the result. |
**Example**
```js
......@@ -571,7 +621,7 @@ off\(type: 'error', callback?: ErrorCallback\): void
Disables listening for the **error** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>**NOTE**
>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.
**System capability**: SystemCapability.Communication.NetStack
......@@ -621,8 +671,8 @@ You can customize the result codes sent to the server. The result codes in the f
| Value | Description |
| :-------- | :----------------- |
| 1000 | Normally closed |
| 1001 | Connection closed by the server |
| 1002 | Incorrect protocol |
| 1003 | Data unable to be processed|
| 1004~1015 | Reserved |
| 1000 | Normally closed. |
| 1001 | Connection closed by the server. |
| 1002 | Incorrect protocol. |
| 1003 | Data unable to be processed.|
| 1004~1015 | Reserved. |
......@@ -47,6 +47,8 @@
- [File Management Error Codes](errorcode-filemanagement.md)
- Network Management
- [Upload and Download Error Codes](errorcode-request.md)
- [HTTP Error Codes](errorcode-http.md)
- [Socket Error Codes](errorcode-socket.md)
- Connectivity
- [NFC Error Codes](errorcode-nfc.md)
- [RPC Error Codes](errorcode-rpc.md)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册