未验证 提交 d06423be 编写于 作者: O openharmony_ci 提交者: Gitee

!4848 网络管理+电话服务指南

Merge pull request !4848 from zengyawen/OpenHarmony-3.1-Release
......@@ -28,6 +28,7 @@
- [Security](security/Readme-EN.md)
- [Connectivity](connectivity/Readme-EN.md)
- [Data Management](database/Readme-EN.md)
- [Telephony](telephony/Readme-EN.md)
- [Agent-Powered Scheduled Reminders](background-agent-scheduled-reminder/Readme-EN.md)
- [Background Task Management](background-task-management/Readme-EN.md)
- [Work Scheduler](work-scheduler/Readme-EN.md)
......
# Connectivity
- IPC & RPC
- [IPC & RPC Overview](ipc-rpc-overview.md)
- [IPC & RPC Development](ipc-rpc-development-guideline.md)
- [Subscribing to State Changes of a Remote Object](subscribe-remote-state.md)
- Network Management
- [Network Management Overview](net-mgmt-overview.md)
- [HTTP Data Request](http-request.md)
- [WebSocket Connection](websocket-connection.md)
- [Socket Connection](socket-connection.md)
- IPC & RPC
- [IPC & RPC Overview](ipc-rpc-overview.md)
- [IPC & RPC Development](ipc-rpc-development-guideline.md)
- [Subscribing to State Changes of a Remote Object](subscribe-remote-state.md)
# HTTP Data Request
## Use Cases
An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**.
## Available APIs
The HTTP request function is mainly implemented by the HTTP module.
To use related APIs, you must declare the **ohos.permission.INTERNET** permission.
The following table describes the related APIs.
| API | Description |
| ----------------------------------------- | --------------------------------------------------------- |
| createHttp() | Creates an HTTP request. |
| request() | Initiates an HTTP request to a given URL. |
| destroy() | Destroys an HTTP request. |
| on(type: 'headersReceive') | Registers an observer for HTTP Response Header events. |
| off(type: 'headersReceive') | Unregisters the observer for HTTP Response Header events. |
## How to Develop
1. Import the required HTTP module.
2. Create an **HttpRequest** object.
3. (Optional) Listen for HTTP Response Header events.
4. Initiate an HTTP request to a given URL.
5. (Optional) Process the HTTP Response Header event and the return result of the HTTP request.
```js
import http from '@ohos.net.http';
// Each HttpRequest corresponds to an HttpRequestTask object and cannot be reused.
let httpRequest = http.createHttp();
// Subscribe to the HTTP response header, which is returned earlier than HttpRequest. You can subscribe to HTTP Response Header events based on service requirements.
// on('headerReceive', AsyncCallback) will be replaced by on('headersReceive', Callback) in API version 8. 8+
httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header));
});
httpRequest.request(
// Set the URL of the HTTP request. You need to define the URL. Set the parameters of the request in extraData.
"EXAMPLE_URL",
{
method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
// You can add the header field based on service requirements.
header: {
'Content-Type': 'application/json'
},
// This field is used to transfer data when the POST request is used.
extraData: {
"data": "data to send",
},
connectTimeout: 60000, // Optional. The default value is 60000, in ms.
readTimeout: 60000, // Optional. The default value is 60000, in ms.
}, (err, data) => {
if (!err) {
// data.result contains the HTTP response. Parse the response based on service requirements.
console.info('Result:' + data.result);
console.info('code:' + data.responseCode);
// data.header contains the HTTP response header. Parse the content based on service requirements.
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + data.cookies); // 8+
} else {
console.info('error:' + JSON.stringify(err));
// Call the destroy() method to release resources after the call is complete.
httpRequest.destroy();
}
}
);
```
## Samples
The following sample is provided to help you better understand how to develop the HTTP data request feature:
- [`Http`: HTTP Data Request (eTS) (API 8)](https://gitee.com/openharmony/app_samples/tree/master/Network/Http)
# Network Management Overview
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.
## Constraints
To use the functions of the network management module, you must obtain the permissions listed in the following table.
| 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. |
| ohos.permission.INTERNET | Allows an application to open network sockets to connect to the network.|
# Socket Connection
## Use Cases
Your application can transmit data through Socket connections. Currently, the TCP and UDP protocols are supported.
## Available APIs
The Socket connection function is mainly implemented by the Socket module. The following table describes the related APIs.
| API| Description |
| -------- | -------- |
| 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: 'message') | Enables listening for **message** events of the Socket connection. |
| off(type: 'message') | Disables listening for **message** events of the Socket connection. |
| on(type: 'close') | Enables listening for **close** events of the Socket connection. |
| off(type: 'close') | Disables listening for **close** events of the Socket connection. |
| on(type: 'error') | Enables listening for **error** events of the Socket connection. |
| off(type: 'error') | Disables listening for **error** events of the Socket connection. |
| on(type: 'listening') | Enables listening for **listening** events of the UDPSocket connection. |
| off(type: 'listening') | Disables listening for **listening** events of the UDPSocket connection. |
| on(type: 'connect') | Enables listening for **connect** events of the TCPSocket connection. |
| off(type: 'connect') | Disables listening for **connect** events of the TCPSocket connection. |
## How to Develop
The implementation is similar for UDPSocket and TCPSocket. The following uses the TCPSocket as an example.
1. Import the required Socket module.
2. Create a **TCPSocket** object.
3. (Optional) Enable listening for TCPSocket events.
4. Bind the IP address and port number. The port number can be specified or randomly allocated by the system.
5. Set up a connection to the specified IP address and port number.
6. Send data.
7. Enable the TCPSocket 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.
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 IP address and port number.
let bindAddress = {
address: '192.168.xx.xx',
port: 1234, // Bound port, for example, 1234.
family: 1
};
tcp.bind(bindAddress, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
// Set up a connection to the specified IP address and port number.
let connectAddress = {
address: '192.168.xx.xx',
port: 5678, // Connection port, for example, 5678.
family: 1
};
tcp.connect({
address: connectAddress, timeout: 6000
}, err => {
if (err) {
console.log('connect fail');
return;
}
console.log('connect success');
// Send data.
tcp.send({
data: 'Hello, server!'
}, err => {
if (err) {
console.log('send fail');
return;
}
console.log('send success');
})
});
});
// Enable the TCPSocket connection to be automatically closed after use. Then, disable listening for TCPSocket events.
setTimeout(() => {
tcp.close((err) => {
console.log('close socket.')
});
tcp.off('message');
tcp.off('connect');
tcp.off('close');
}, 30 * 1000);
```
## Samples
The following sample is provided to help you better understand how to develop the socket connection feature:
- [`Socket`: Socket Connection (eTS) (API 8)](https://gitee.com/openharmony/app_samples/tree/master/Network/Socket)
# WebSocket Connection
## Use Cases
You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the **createWebSocket** API to create a **WebSocket** object and then use the **connect** API to connect to the server. If the connection is successful, the client will receive a callback of the **open** event. Then, the client can communicate with the server using the **send** API. When the server sends a message to the client, the client will receive a callback of the **message** event. If the client no longer needs this connection, it can call the **close** API to disconnect from the server. Then, the client will receive a callback of the **close** event.
If an error occurs in any of the preceding processes, the client will receive a callback of the **error** event.
## Available APIs
The WebSocket connection function is mainly implemented by the WebSocket module. To use related APIs, you must declare the **ohos.permission.INTERNET** permission. The following table describes the related APIs.
| API | Description |
| -------- | -------- |
| createWebSocket() | Creates a WebSocket connection. |
| connect() | Establishes a WebSocket connection to a given URL. |
| send() | Sends data through the WebSocket connection. |
| close() | Closes a WebSocket connection. |
| on(type:&nbsp;'open') | Enables listening for **open** events of a WebSocket connection. |
| off(type:&nbsp;'open') | Disables listening for **open** events of a WebSocket connection. |
| on(type:&nbsp;'message') | Enables listening for **message** events of a WebSocket connection. |
| off(type:&nbsp;'message') | Disables listening for **message** events of a WebSocket connection. |
| on(type:&nbsp;'close') | Enables listening for **close** events of a WebSocket connection. |
| off(type:&nbsp;'close') | Disables listening for **close** events of a WebSocket connection. |
| on(type:&nbsp;'error') | Enables listening for **error** events of a WebSocket connection. |
| off(type:&nbsp;'error') | Disables listening for **error** events of a WebSocket connection. |
## How to Develop
1. Import the required WebSocket module.
2. Create a **WebSocket** object.
3. (Optional) Subscribe to WebSocket open, message, close, and error events.
4. Establish a WebSocket connection to a given URL.
5. Close the WebSocket connection if it is no longer needed.
```js
import webSocket from '@ohos.net.webSocket';
var defaultIpAddress = "ws://";
let ws = webSocket.createWebSocket();
ws.on('open', (err, value) => {
console.log("on open, status:" + JSON.stringify(value));
// When receiving the on('open') event, the client can use the send() API to communicate with the server.
ws.send("Hello, server!", (err, value) => {
if (!err) {
console.log("send success");
} else {
console.log("send fail, err:" + JSON.stringify(err));
}
});
});
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.
if (value === 'bye') {
ws.close((err, value) => {
if (!err) {
console.log("close success");
} else {
console.log("close fail, err is " + JSON.stringify(err));
}
});
}
});
ws.on('close', (err, value) => {
console.log("on close, code is " + value.code + ", reason is " + value.reason);
});
ws.on('error', (err) => {
console.log("on error, error:" + JSON.stringify(err));
});
ws.connect(defaultIpAddress, (err, value) => {
if (!err) {
console.log("connect success");
} else {
console.log("connect fail, err:" + JSON.stringify(err));
}
});
```
# Telephony
- [Telephony Service Overview](telephony-overview.md)
- [Redirecting to the Dial Screen](jumping-to-the-dial-screen.md)
- [Obtaining Current Cellular Network Signal Information](cellular-network-signal-info.md)
# Obtaining Current Cellular Network Signal Information
## Use Cases
Applications always need to obtain signal information of the registered cellular network to obtain the network quality. You can use this service to obtain the network signal information for the specified SIM card.
## Available APIs
The radio module provides you with APIs to obtain network signal information. The observer module provides APIs to register or unregister the observer for cellular network status changes. The following table describes the related APIs.
| Category| API| Description| Required Permission|
| -------- | -------- | -------- | -------- |
| Obtaining a **SignalInformation** object| radio.getSignalInformation​​() | Obtains the signal strength of the currently registered cellular network.| N/A|
| Registering the observer for signal information changes| observer.on('signalInfoChange') | Registers the observer for signal information changes.| N/A|
| Unregistering the observer for signal information changes| observer.off('signalInfoChange') | Unregisters the observer for signal information changes.| N/A|
## How to Develop
1. Import required modules.
2. Call the **getSignalInformation()** API to obtain the **SignalInformation** list.
3. Traverse the **SignalInformation** list to obtain the signal strength for each radio access technology (RAT) indicated by **signalType**.
4. (Optional) Register the observer for signal information changes.
```js
import radio from '@ohos.telephony.radio'
import observer from '@ohos.telephony.observer';
// Obtain the signal strength of the specified SIM card, for example, card 1.
let slotId = 0;
radio.getSignalInformation(slotId, (err, data) => {
if (!err) {
console.log("get signal information success.");
// Traverse the signal information list to obtain the signal strength for each RAT.
for (let j = 0; j < data.length; j++) {
console.log("type:" + data[j].signalType + ", level:" + data[j].signalLevel);
}
} else {
console.log("get signal information fail, err is:" + JSON.stringify(err));
}
});
// (Optional) Register the observer for signal information changes.
observer.on("signalInfoChange", (data) => {
console.log("signal info change, data is:" + JSON.stringify(data));
});
```
# Redirecting to the Dial Screen
You can use this service for your application to redirect users to the dial screen and display the dialed number. When the **makeCall** API is called, the phone or tablet will automatically display the dial screen. On this screen, the user can choose to make an audio or video call and specify the SIM card.
## Available APIs
The call module provides APIs for call management. The observer module provides APIs to register or unregister an observer for call service status changes. The following table describes the related APIs.
| Category| API| Description| Required Permission|
| -------- | -------- | -------- | -------- |
| Checking call capabilities| call.hasVoiceCapability() | Checks whether the voice call function is supported.| N/A|
| Redirecting to the dial screen| call.makeCall() | Enables redirection to the dial screen and display of the dialed number.| N/A|
| Registering the observer for call service status changes| observer.on('callStateChange') | Registers the observer for call service status changes.| ohos.permission.READ_CALL_LOG (required for obtaining phone numbers)|
| Unregistering the observer for call service status changes| observer.off('callStateChange') | Unregisters the observer for call service status changes.| N/A|
## How to Develop
1. Import required modules.
2. Invoke the **hasVoiceCapability()** API to check whether the call function is supported. If supported, go to step 3; otherwise, calls will be rejected.
3. Enable redirection to the dial screen and display of the dialed number.
4. (Optional) Register the observer for call service status changes.
```js
// Import the required modules.
import call from '@ohos.telephony.call';
import observer from '@ohos.telephony.observer';
// Check whether the voice call function is supported.
let isSupport = call.hasVoiceCapability();
if (!isSupport) {
console.log("not support voice capability, return.");
return;
}
// If the voice call function is supported, the user will be redirected to the dial screen and the dialed number is displayed.
call.makeCall("13xxxx", (err)=> {
if (!err) {
console.log("make call success.");
} else {
console.log("make call fail, err is:" + JSON.stringify(err));
}
});
// (Optional) Register the observer for call service status changes.
observer.on("callStateChange", (data) => {
console.log("call state change, data is:" + JSON.stringify(data));
});
```
# Telephony Service Overview
The Telephony subsystem provides a series of APIs for [making calls](../reference/apis/js-apis-call.md), [obtaining current cellular network signal information](../reference/apis/js-apis-telephony-data.md) and [managing SIM cards](../reference/apis/js-apis-sim.md).
Your application can call related APIs to obtain the name of the currently registered network, network service status, signal strength, and SIM card information. For details, see [Obtaining Current Cellular Network Signal Information](cellular-network-signal-info.md).
To make calls, your application needs to declare the **ohos.permission.PLACE_CALL** permission. It is recommended that the application use **makeCall()** to redirect users to the dial screen and display the dialed number. For details, see [Redirecting to the Dial Screen](jumping-to-the-dial-screen.md).
## Constraints
The accommodating device must be equipped with a modem and a SIM card capable of independent cellular communication.
......@@ -225,10 +225,19 @@
- [Access Control Overview](security/accesstoken-overview.md)
- [Access Control Development](security/accesstoken-guidelines.md)
- Connectivity
- Network Management
- [Network Management Overview](connectivity/net-mgmt-overview.md)
- [HTTP Data Request](connectivity/http-request.md)
- [WebSocket Connection](connectivity/websocket-connection.md)
- [Socket Connection](connectivity/socket-connection.md)
- IPC & RPC
- [IPC & RPC Overview](connectivity/ipc-rpc-overview.md)
- [IPC & RPC Development Guidelines](connectivity/ipc-rpc-development-guideline.md)
- [Subscribing to State Changes of a Remote Object](connectivity/subscribe-remote-state.md)
- Telephony
- [Telephony Service Overview](telephony/telephony-overview.md)
- [Redirecting to the Dial Screen](telephony/jumping-to-the-dial-screen.md)
- [Obtaining Current Cellular Network Signal Information](telephony/cellular-network-signal-info.md)
- Data Management
- Distributed Data Service
- [Distributed Data Service Overview](database/database-mdds-overview.md)
......
......@@ -28,6 +28,7 @@
- [安全](security/Readme-CN.md)
- [网络与连接](connectivity/Readme-CN.md)
- [数据管理](database/Readme-CN.md)
- [电话服务](telephony/Readme-CN.md)
- [后台代理提醒](background-agent-scheduled-reminder/Readme-CN.md)
- [后台任务管理](background-task-management/Readme-CN.md)
- [延迟任务调度](work-scheduler/Readme-CN.md)
......
# 网络与连接
- 网络管理
- [网络管理开发概述](net-mgmt-overview.md)
- [HTTP数据请求](http-request.md)
- [WebSocket连接](websocket-connection.md)
- [Socket连接](socket-connection.md)
- IPC与RPC通信
- [IPC与RPC通信概述](ipc-rpc-overview.md)
- [IPC与RPC通信开发指导](ipc-rpc-development-guideline.md)
......
# HTTP数据请求
## 场景介绍
应用通过HTTP发起一个数据请求,支持常见的GET、POST、OPTIONS、HEAD、PUT、DELETE、TRACE、CONNECT方法。
## 接口说明
HTTP数据请求功能主要由http模块提供。
使用该功能需要申请ohos.permission.INTERNET权限。
具体接口说明如下表。
| 接口名 | 功能描述 |
| ----------------------------------------- | ----------------------------------- |
| createHttp() | 创建一个http请求。 |
| request() | 根据URL地址,发起HTTP网络请求。 |
| destroy() | 中断请求任务。 |
| on(type: 'headersReceive') | 订阅HTTP Response Header 事件。 |
| off(type: 'headersReceive') | 取消订阅HTTP Response Header 事件。 |
## 开发步骤
1. import需要的http模块。
2. 创建一个HTTP请求,返回一个HttpRequest对象。
3. (可选)订阅HTTP响应头。
4. 根据URL地址,发起HTTP网络请求。
5. (可选)处理HTTP响应头和HTTP网络请求的返回结果。
```js
import http from '@ohos.net.http';
// 每一个httpRequest对应一个http请求任务,不可复用
let httpRequest = http.createHttp();
// 用于订阅http响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息
// 从API 8开始,使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+
httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header));
});
httpRequest.request(
// 填写http请求的url地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定
"EXAMPLE_URL",
{
method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET
// 开发者根据自身业务需要添加header字段
header: {
'Content-Type': 'application/json'
},
// 当使用POST请求时此字段用于传递内容
extraData: {
"data": "data to send",
},
connectTimeout: 60000, // 可选,默认为60s
readTimeout: 60000, // 可选,默认为60s
}, (err, data) => {
if (!err) {
// data.result为http响应内容,可根据业务需要进行解析
console.info('Result:' + data.result);
console.info('code:' + data.responseCode);
// data.header为http响应头,可根据业务需要进行解析
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + data.cookies); // 8+
} else {
console.info('error:' + JSON.stringify(err));
// 当该请求使用完毕时,调用destroy方法主动销毁。
httpRequest.destroy();
}
}
);
```
## 相关实例
针对HTTP数据请求,有以下相关实例可供参考:
- [`Http`:数据请求(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/Network/Http)
\ No newline at end of file
# 网络管理开发概述
网络管理模块主要提供以下功能:
- [HTTP数据请求](http-request.md):通过HTTP发起一个数据请求。
- [WebSocket连接](websocket-connection.md):使用WebSocket建立服务器与客户端的双向连接。
- [Socket连接](socket-connection.md):通过Socket进行数据传输。
## 约束与限制
使用网络管理模块的相关功能时,需要请求相应的权限。
| 权限名 | 说明 |
| -------------------------------- | -------------------------------------- |
| ohos.permission.GET_NETWORK_INFO | 获取网络连接信息。 |
| ohos.permission.SET_NETWORK_INFO | 修改网络连接状态。 |
| ohos.permission.INTERNET | 允许程序打开网络套接字,进行网络连接。 |
# Socket连接
## 场景介绍
应用通过Socket进行数据传输,支持TCP和UDP两种协议。
## 接口说明
Socket连接主要由socket模块提供。具体接口说明如下表。
| 接口名 | 功能描述 |
| -------- | -------- |
| constructUDPSocketInstance() | 创建一个UDPSocket对象。 |
| constructTCPSocketInstance() | 创建一个TCPSocket对象。 |
| bind() | 绑定IP地址和端口。 |
| send() | 发送数据。 |
| close() | 关闭连接。 |
| getState() | 获取Socket状态。 |
| connect() | 连接到指定的IP地址和端口(仅TCP支持) |
| getRemoteAddress() | 获取对端Socket地址(仅TCP支持,需要先调用connect方法) |
| on(type:&nbsp;'message') | 订阅Socket连接的接收消息事件。 |
| off(type:&nbsp;'message') | 取消订阅Socket连接的接收消息事件。 |
| on(type:&nbsp;'close') | 订阅Socket连接的关闭事件。 |
| off(type:&nbsp;'close') | 取消订阅Socket连接的关闭事件。 |
| on(type:&nbsp;'error') | 订阅Socket连接的Error事件。 |
| off(type:&nbsp;'error') | 取消订阅Socket连接的Error事件。 |
| on(type:&nbsp;'listening') | 订阅UDPSocket连接的数据包消息事件(仅UDP支持)。 |
| off(type:&nbsp;'listening') | 取消订阅UDPSocket连接的数据包消息事件(仅UDP支持)。 |
| on(type:&nbsp;'connect') | 订阅TCPSocket的连接事件(仅TCP支持)。 |
| off(type:&nbsp;'connect') | 取消订阅TCPSocket的连接事件(仅TCP支持)。 |
## 开发步骤
UDP与TCP流程大体类似,下面以TCP为例:
1. import需要的socket模块。
2. 创建一个TCPSocket连接,返回一个TCPSocket对象。
3. (可选)订阅TCPSocket相关的订阅事件。
4. 绑定IP地址和端口,端口可以指定或由系统随机分配。
5. 连接到指定的IP地址和端口。
6. 发送数据。
7. Socket连接使用完毕后,主动关闭。
```js
import socket from '@ohos.net.socket'
// 创建一个TCPSocket连接,返回一个TCPSocket对象。
let tcp = socket.constructTCPSocketInstance();
// 订阅TCPSocket相关的订阅事件
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")
});
// 绑定IP地址和端口。
let bindAddress = {
address: '192.168.xx.xx',
port: 1234, // 绑定端口,如1234
family: 1
};
tcp.bind(bindAddress, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
// 连接到指定的IP地址和端口。
let connectAddress = {
address: '192.168.xx.xx',
port: 5678, // 连接端口,如5678
family: 1
};
tcp.connect({
address: connectAddress, timeout: 6000
}, err => {
if (err) {
console.log('connect fail');
return;
}
console.log('connect success');
// 发送数据
tcp.send({
data: 'Hello, server!'
}, err => {
if (err) {
console.log('send fail');
return;
}
console.log('send success');
})
});
});
// 连接使用完毕后,主动关闭。取消相关事件的订阅。
setTimeout(() => {
tcp.close((err) => {
console.log('close socket.')
});
tcp.off('message');
tcp.off('connect');
tcp.off('close');
}, 30 * 1000);
```
## 相关实例
针对Socket连接开发,有以下相关实例可供参考:
- [`Socket`:Socket 连接(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/Network/Socket)
# WebSocket连接
## 场景介绍
使用WebSocket建立服务器与客户端的双向连接,需要先通过createWebSocket方法创建WebSocket对象,然后通过connect方法连接到服务器。当连接成功后,客户端会收到open事件的回调,之后客户端就可以通过send方法与服务器进行通信。当服务器发信息给客户端时,客户端会收到message事件的回调。当客户端不要此连接时,可以通过调用close方法主动断开连接,之后客户端会收到close事件的回调。
若在上述任一过程中发生错误,客户端会收到error事件的回调。
## 接口说明
WebSocket连接功能主要由webSocket模块提供。使用该功能需要申请ohos.permission.INTERNET权限。具体接口说明如下表。
| 接口名 | 功能描述 |
| -------- | -------- |
| createWebSocket() | 创建一个WebSocket连接。 |
| connect() | 根据URL地址,建立一个WebSocket连接。 |
| send() | 通过WebSocket连接发送数据。 |
| close() | 关闭WebSocket连接。 |
| on(type:&nbsp;'open') | 订阅WebSocket的打开事件。 |
| off(type:&nbsp;'open') | 取消订阅WebSocket的打开事件。 |
| on(type:&nbsp;'message') | 订阅WebSocket的接收到服务器消息事件。 |
| off(type:&nbsp;'message') | 取消订阅WebSocket的接收到服务器消息事件。 |
| on(type:&nbsp;'close') | 订阅WebSocket的关闭事件。 |
| off(type:&nbsp;'close') | 取消订阅WebSocket的关闭事件 |
| on(type:&nbsp;'error') | 订阅WebSocket的Error事件。 |
| off(type:&nbsp;'error') | 取消订阅WebSocket的Error事件。 |
## 开发步骤
1. import需要的webSocket模块。
2. 创建一个WebSocket连接,返回一个WebSocket对象。
3. (可选)订阅WebSocket的打开、消息、关闭、Error事件。
4. 根据URL地址,发起WebSocket连接。
5. 使用完WebSocket连接之后,主动断开连接。
```js
import webSocket from '@ohos.net.webSocket';
var defaultIpAddress = "ws://";
let ws = webSocket.createWebSocket();
ws.on('open', (err, value) => {
console.log("on open, status:" + JSON.stringify(value));
// 当收到on('open')事件时,可以通过send()方法与服务器进行通信
ws.send("Hello, server!", (err, value) => {
if (!err) {
console.log("send success");
} else {
console.log("send fail, err:" + JSON.stringify(err));
}
});
});
ws.on('message', (err, value) => {
console.log("on message, message:" + value);
// 当收到服务器的`bye`消息时(此消息字段仅为示意,具体字段需要与服务器协商),主动断开连接
if (value === 'bye') {
ws.close((err, value) => {
if (!err) {
console.log("close success");
} else {
console.log("close fail, err is " + JSON.stringify(err));
}
});
}
});
ws.on('close', (err, value) => {
console.log("on close, code is " + value.code + ", reason is " + value.reason);
});
ws.on('error', (err) => {
console.log("on error, error:" + JSON.stringify(err));
});
ws.connect(defaultIpAddress, (err, value) => {
if (!err) {
console.log("connect success");
} else {
console.log("connect fail, err:" + JSON.stringify(err));
}
});
```
# 电话服务
- [电话服务开发概述](telephony-overview.md)
- [跳转拨号界面](jumping-to-the-dial-screen.md)
- [获取当前蜂窝网络信号信息](cellular-network-signal-info.md)
# 获取当前蜂窝网络信号信息
## 场景介绍
应用通常需要获取用户所在蜂窝网络下信号信息,以便获取当前驻网质量。开发者可以通过本业务,获取到用户指定SIM卡当前所在网络下的信号信息。
## 接口说明
radio模块提供了获取当前网络信号信息的方法。observer模块为开发者提供蜂窝网络状态订阅和取消订阅功能。具体接口说明如下表。
| 功能分类 | 接口名 | 描述 | 所需权限 |
| -------- | -------- | -------- | -------- |
| 信号强度信息 | radio.getSignalInformation​​() | 获取当前注册蜂窝网络信号强度信息 | 无 |
| 订阅蜂窝网络信号变化 | observer.on('signalInfoChange') | 订阅蜂窝网络信号变化 | 无 |
| 取消订阅蜂窝网络信号变化 | observer.off('signalInfoChange') | 取消订阅蜂窝网络信号变化 | 无 |
## 开发步骤
1. import需要的模块。
2. 调用getSignalInformation()方法,返回所有SignalInformation列表。
3. 遍历SignalInformation数组,并分别根据不同的signalType得到不同制式的信号强度。
4. 订阅蜂窝网络信号变化(可选)。
```js
import radio from '@ohos.telephony.radio'
import observer from '@ohos.telephony.observer';
// 以获取卡1的信号强度为例
let slotId = 0;
radio.getSignalInformation(slotId, (err, data) => {
if (!err) {
console.log("get signal information success.");
// 遍历数组,输出不同网络制式下的信号强度
for (let j = 0; j < data.length; j++) {
console.log("type:" + data[j].signalType + ", level:" + data[j].signalLevel);
}
} else {
console.log("get signal information fail, err is:" + JSON.stringify(err));
}
});
// 订阅蜂窝网络信号变化(可选)
observer.on("signalInfoChange", (data) => {
console.log("signal info change, data is:" + JSON.stringify(data));
});
```
# 跳转拨号界面
当应用需要跳转到拨号界面,并显示拨号的号码时,使用本业务。当开发者调用makeCall接口时,设备会自动跳转到拨号界面。和正常拨打电话一样,用户可以选择音频或视频呼叫,卡1或卡2拨出。
## 接口说明
call模块为开发者提供呼叫管理功能。observer模块为开发者提供通话业务状态订阅和取消订阅功能。具体接口说明如下表。
| 功能分类 | 接口名 | 描述 | 所需权限 |
| -------- | -------- | -------- | -------- |
| 能力获取 | call.hasVoiceCapability() | 是否具有语音功能 | 无 |
| 跳转拨号界面 | call.makeCall() | 跳转到拨号界面,并显示拨号的号码 | 无 |
| 订阅通话业务状态变化 | observer.on('callStateChange') | 订阅通话业务状态变化 | ohos.permission.READ_CALL_LOG&nbsp;(获取通话号码需要该权限) |
| 取消订阅通话业务状态变化 | observer.off('callStateChange') | 取消订阅通话业务状态变化 | 无 |
## 开发步骤
1. import需要的模块。
2. 调用hasVoiceCapability()接口获取当前设备呼叫能力,如果支持继续下一步;如果不支持则无法发起呼叫。
3. 跳转到拨号界面,并显示拨号的号码。
4. (可选)订阅通话业务状态变化。
```js
// import需要的模块
import call from '@ohos.telephony.call';
import observer from '@ohos.telephony.observer';
// 调用查询能力接口
let isSupport = call.hasVoiceCapability();
if (!isSupport) {
console.log("not support voice capability, return.");
return;
}
// 如果设备支持呼叫能力,则继续跳转到拨号界面,并显示拨号的号码
call.makeCall("13xxxx", (err)=> {
if (!err) {
console.log("make call success.");
} else {
console.log("make call fail, err is:" + JSON.stringify(err));
}
});
// 订阅通话业务状态变化(可选)
observer.on("callStateChange", (data) => {
console.log("call state change, data is:" + JSON.stringify(data));
});
```
# 电话服务开发概述
电话服务系统提供了一系列的API用于[拨打电话](../reference/apis/js-apis-call.md)、获取[无线蜂窝网络](../reference/apis/js-apis-telephony-data.md)[SIM卡](../reference/apis/js-apis-sim.md)相关信息。
应用可以通过调用API来获取当前注册网络名称、网络服务状态、信号强度以及SIM卡的相关信息,具体可参考[获取当前蜂窝网络信号信息](cellular-network-signal-info.md)开发指导。
直接拨打电话需要系统权限ohos.permission.PLACE_CALL,建议应用使用makeCall(),跳转到拨号界面,并显示拨号的号码,具体可参考[跳转拨号界面](jumping-to-the-dial-screen.md)开发指导。
## 约束与限制
搭载设备需要支持以下硬件:
可以进行独立蜂窝通信的Modem以及SIM卡。
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册