一、概述
通过本指南,您可以掌握HarmonyOS Network Kit的核心功能和最佳实践。Network Kit提供了完整的网络通信解决方案,支持HTTP、WebSocket、Socket等多种协议,满足各类应用的网络需求。合理使用这些能力,可以构建高性能、安全可靠的网络应用。
核心能力
| 功能模块 | 主要能力 | 应用场景 |
|---|---|---|
| HTTP请求 | GET/POST/PUT/DELETE等方法、流式传输、证书配置 | RESTful API调用、文件上传下载 |
| WebSocket | 全双工通信、心跳检测、客户端/服务端 | 实时聊天、游戏对战、实时数据推送 |
| TCP Socket | 面向连接的可靠传输、服务端监听 | 长连接通信、自定义协议 |
| UDP Socket | 无连接的快速传输、组播支持 | 视频直播、实时语音、局域网发现 |
| TLS Socket | 加密传输、双向认证、证书锁定 | 安全通信、金融支付 |
| LocalSocket | 进程间通信、无需网络 | 同设备进程通信、性能优化 |
二、HTTP网络请求
2.1 请求流程
sequenceDiagram
participant App as 应用
participant HTTP as HttpRequest
participant Server as 服务器
App->>HTTP: createHttp()
App->>HTTP: on('headersReceive')
App->>HTTP: request(url, options)
HTTP->>Server: 发送HTTP请求
Server-->>HTTP: 返回响应头
HTTP-->>App: headersReceive回调
Server-->>HTTP: 返回完整响应
HTTP-->>App: 响应数据
App->>HTTP: destroy()
2.2 基础HTTP请求
typescript
import { http } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
class HttpManager {
private static instance: HttpManager;
private constructor() {}
public static getInstance(): HttpManager {
if (!HttpManager.instance) {
HttpManager.instance = new HttpManager();
}
return HttpManager.instance;
}
/**
* 发送HTTP GET请求
*/
async get<T>(url: string, headers?: Record<string, string>): Promise<T> {
const httpRequest = http.createHttp();
try {
const response = await httpRequest.request(url, {
method: http.RequestMethod.GET,
header: headers || { 'Content-Type': 'application/json' },
expectDataType: http.HttpDataType.STRING,
connectTimeout: 60000,
readTimeout: 60000
});
if (response.responseCode === 200) {
return JSON.parse(response.result as string);
} else {
throw new Error(`HTTP Error: ${response.responseCode}`);
}
} finally {
httpRequest.destroy();
}
}
/**
* 发送HTTP POST请求
*/
async post<T>(url: string, data: Object, headers?: Record<string, string>): Promise<T> {
const httpRequest = http.createHttp();
try {
const response = await httpRequest.request(url, {
method: http.RequestMethod.POST,
header: headers || { 'Content-Type': 'application/json' },
extraData: JSON.stringify(data),
expectDataType: http.HttpDataType.STRING,
connectTimeout: 60000,
readTimeout: 60000
});
if (response.responseCode === 200) {
return JSON.parse(response.result as string);
} else {
throw new Error(`HTTP Error: ${response.responseCode}`);
}
} finally {
httpRequest.destroy();
}
}
/**
* 上传文件(multipart/form-data)
*/
async uploadFile(url: string, filePath: string, fileName: string): Promise<string> {
const httpRequest = http.createHttp();
try {
const response = await httpRequest.request(url, {
method: http.RequestMethod.POST,
header: { 'Content-Type': 'multipart/form-data' },
multiFormDataList: [
{
name: 'file',
contentType: 'application/octet-stream',
filePath: filePath,
remoteFileName: fileName
}
],
connectTimeout: 60000,
readTimeout: 300000 // 上传大文件需要更长超时时间
});
return response.result as string;
} finally {
httpRequest.destroy();
}
}
}
2.3 HTTP流式传输
适用于大文件下载场景,支持进度监听:
typescript
class HttpStreamDownloader {
private httpRequest: http.HttpRequest | null = null;
private receivedData: ArrayBuffer = new ArrayBuffer(0);
/**
* 下载文件并监听进度
*/
async downloadFile(
url: string,
onProgress: (received: number, total: number) => void
): Promise<ArrayBuffer> {
this.httpRequest = http.createHttp();
this.receivedData = new ArrayBuffer(0);
return new Promise((resolve, reject) => {
// 订阅数据接收事件
this.httpRequest!.on('dataReceive', (data: ArrayBuffer) => {
const newBuffer = new ArrayBuffer(this.receivedData.byteLength + data.byteLength);
const newView = new Uint8Array(newBuffer);
newView.set(new Uint8Array(this.receivedData));
newView.set(new Uint8Array(data), this.receivedData.byteLength);
this.receivedData = newBuffer;
});
// 订阅下载进度事件
this.httpRequest!.on('dataReceiveProgress', (progress: http.DataReceiveProgressInfo) => {
onProgress(progress.receiveSize, progress.totalSize);
});
// 订阅数据接收完成事件
this.httpRequest!.on('dataEnd', () => {
resolve(this.receivedData);
this.cleanup();
});
// 发起流式请求
this.httpRequest!.requestInStream(url, {
method: http.RequestMethod.GET,
readTimeout: 600000 // 大文件需要更长超时
}).catch((err: BusinessError) => {
reject(err);
this.cleanup();
});
});
}
/**
* 取消下载
*/
cancel(): void {
this.cleanup();
}
private cleanup(): void {
if (this.httpRequest) {
this.httpRequest.off('dataReceive');
this.httpRequest.off('dataReceiveProgress');
this.httpRequest.off('dataEnd');
this.httpRequest.destroy();
this.httpRequest = null;
}
}
}
三、WebSocket通信
3.1 WebSocket架构
graph TB
A[应用层] --> B[WebSocket客户端]
A --> C[WebSocket服务端-仅智慧屏]
B --> D[createWebSocket]
B --> E[connect建立连接]
B --> F[send发送消息]
B --> G[close关闭连接]
C --> H[createWebSocketServer]
C --> I[start启动服务]
C --> J[监听客户端连接]
C --> K[stop停止服务]
3.2 WebSocket客户端
typescript
import { webSocket } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
class WebSocketClient {
private ws: webSocket.WebSocket;
private reconnectTimer: number | null = null;
private reconnectAttempts = 0;
private maxReconnectAttempts = 5;
constructor(private url: string) {
this.ws = webSocket.createWebSocket();
this.setupEventHandlers();
}
private setupEventHandlers(): void {
// 连接打开事件
this.ws.on('open', (err: BusinessError, value: Object) => {
if (err) {
console.error('WebSocket连接失败:', JSON.stringify(err));
return;
}
console.info('WebSocket连接成功');
this.reconnectAttempts = 0;
});
// 接收消息事件
this.ws.on('message', (err: BusinessError, value: string | ArrayBuffer) => {
if (err) {
console.error('接收消息失败:', JSON.stringify(err));
return;
}
if (typeof value === 'string') {
console.info('收到文本消息:', value);
this.handleMessage(value);
} else {
console.info('收到二进制消息');
this.handleBinaryMessage(value);
}
});
// 连接关闭事件
this.ws.on('close', (err: BusinessError, value: webSocket.CloseResult) => {
console.info(`WebSocket关闭 code=${value.code} reason=${value.reason}`);
this.attemptReconnect();
});
// 错误事件
this.ws.on('error', (err: BusinessError) => {
console.error('WebSocket错误:', JSON.stringify(err));
});
}
/**
* 连接到WebSocket服务器
*/
connect(): Promise<void> {
return new Promise((resolve, reject) => {
this.ws.connect(this.url, (err: BusinessError, value: boolean) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
/**
* 发送文本消息
*/
sendText(message: string): Promise<void> {
return new Promise((resolve, reject) => {
this.ws.send(message, (err: BusinessError, value: boolean) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
/**
* 发送二进制消息
*/
sendBinary(data: ArrayBuffer): Promise<void> {
return new Promise((resolve, reject) => {
this.ws.send(data, (err: BusinessError, value: boolean) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
/**
* 关闭连接
*/
close(): Promise<void> {
if (this.reconnectTimer !== null) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
return new Promise((resolve, reject) => {
this.ws.close((err: BusinessError, value: boolean) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
/**
* 自动重连
*/
private attemptReconnect(): void {
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
console.error('达到最大重连次数,停止重连');
return;
}
const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000);
this.reconnectAttempts++;
console.info(`${delay}ms后尝试第${this.reconnectAttempts}次重连`);
this.reconnectTimer = setTimeout(() => {
this.connect().catch(err => {
console.error('重连失败:', err);
});
}, delay);
}
private handleMessage(message: string): void {
// 业务逻辑处理
}
private handleBinaryMessage(data: ArrayBuffer): void {
// 二进制数据处理
}
}
四、Socket通信
4.1 TCP Socket客户端
typescript
import { socket } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
class TCPSocketClient {
private tcp: socket.TCPSocket;
private connected = false;
constructor() {
this.tcp = socket.constructTCPSocketInstance();
this.setupEventHandlers();
}
private setupEventHandlers(): void {
// 连接建立事件
this.tcp.on('connect', () => {
console.info('TCP连接已建立');
this.connected = true;
});
// 接收消息事件
this.tcp.on('message', (value: socket.SocketMessageInfo) => {
const buffer = value.message;
const dataView = new DataView(buffer);
let str = '';
for (let i = 0; i < dataView.byteLength; i++) {
str += String.fromCharCode(dataView.getUint8(i));
}
console.info('收到消息:', str);
});
// 连接关闭事件
this.tcp.on('close', () => {
console.info('TCP连接已关闭');
this.connected = false;
});
}
/**
* 连接到服务器
*/
async connect(host: string, port: number): Promise<void> {
// 绑定本地地址(可选,端口由系统分配)
const localAddr: socket.NetAddress = {
address: '0.0.0.0',
port: 0
};
await new Promise<void>((resolve, reject) => {
this.tcp.bind(localAddr, (err: BusinessError) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
// 连接到服务器
const remoteAddr: socket.NetAddress = {
address: host,
port: port
};
const connectOptions: socket.TCPConnectOptions = {
address: remoteAddr,
timeout: 6000
};
await this.tcp.connect(connectOptions);
}
/**
* 发送数据
*/
async send(data: string): Promise<void> {
if (!this.connected) {
throw new Error('TCP未连接');
}
const sendOptions: socket.TCPSendOptions = {
data: data
};
await this.tcp.send(sendOptions);
}
/**
* 关闭连接
*/
async close(): Promise<void> {
await this.tcp.close();
this.tcp.off('message');
this.tcp.off('connect');
this.tcp.off('close');
}
}
4.2 TCP Socket服务端
typescript
class TCPSocketServer {
private server: socket.TCPSocketServer;
private clients: socket.TCPSocketConnection[] = [];
constructor() {
this.server = socket.constructTCPSocketServerInstance();
this.setupEventHandlers();
}
private setupEventHandlers(): void {
// 客户端连接事件
this.server.on('connect', (client: socket.TCPSocketConnection) => {
console.info('新客户端连接');
this.clients.push(client);
// 监听客户端消息
client.on('message', (value: socket.SocketMessageInfo) => {
const buffer = value.message;
const dataView = new DataView(buffer);
let message = '';
for (let i = 0; i < dataView.byteLength; i++) {
message += String.fromCharCode(dataView.getUint8(i));
}
console.info('收到客户端消息:', message);
// 广播给所有客户端
this.broadcast(message, client);
});
// 客户端关闭事件
client.on('close', () => {
const index = this.clients.indexOf(client);
if (index > -1) {
this.clients.splice(index, 1);
}
console.info('客户端断开,当前连接数:', this.clients.length);
});
});
}
/**
* 启动服务器
*/
async listen(port: number): Promise<void> {
const address: socket.NetAddress = {
address: '0.0.0.0',
port: port
};
await this.server.listen(address);
console.info(`TCP服务器监听端口: ${port}`);
}
/**
* 广播消息给所有客户端
*/
private async broadcast(message: string, sender?: socket.TCPSocketConnection): Promise<void> {
const sendOptions: socket.TCPSendOptions = {
data: message
};
for (const client of this.clients) {
if (client !== sender) {
try {
await client.send(sendOptions);
} catch (err) {
console.error('发送失败:', err);
}
}
}
}
/**
* 停止服务器
*/
stop(): void {
// 关闭所有客户端连接
for (const client of this.clients) {
client.close();
}
this.clients = [];
this.server.off('connect');
}
}
4.3 TLS Socket加密通信
typescript
class TLSSocketClient {
private tls: socket.TLSSocket;
constructor() {
this.tls = socket.constructTLSSocketInstance();
this.setupEventHandlers();
}
private setupEventHandlers(): void {
this.tls.on('connect', () => {
console.info('TLS连接建立');
});
this.tls.on('message', (value: socket.SocketMessageInfo) => {
// 处理加密消息
});
this.tls.on('close', () => {
console.info('TLS连接关闭');
});
}
/**
* 单向认证连接(仅验证服务器证书)
*/
async connectOneWay(host: string, port: number, caPath: string): Promise<void> {
const localAddr: socket.NetAddress = {
address: '0.0.0.0',
port: 0
};
await new Promise<void>((resolve, reject) => {
this.tls.bind(localAddr, (err: BusinessError) => {
if (err) reject(err);
else resolve();
});
});
const remoteAddr: socket.NetAddress = {
address: host,
port: port
};
const secureOptions: socket.TLSSecureOptions = {
ca: [caPath], // CA证书路径
cipherSuite: 'AES256-SHA256'
};
const connectOptions: socket.TLSConnectOptions = {
address: remoteAddr,
secureOptions: secureOptions
};
await this.tls.connect(connectOptions);
}
/**
* 双向认证连接(同时验证客户端和服务器证书)
*/
async connectTwoWay(
host: string,
port: number,
caPath: string,
certPath: string,
keyPath: string,
password: string
): Promise<void> {
const localAddr: socket.NetAddress = {
address: '0.0.0.0',
port: 0
};
await new Promise<void>((resolve, reject) => {
this.tls.bind(localAddr, (err: BusinessError) => {
if (err) reject(err);
else resolve();
});
});
const remoteAddr: socket.NetAddress = {
address: host,
port: port
};
const secureOptions: socket.TLSSecureOptions = {
ca: [caPath],
cert: certPath, // 客户端证书
key: keyPath, // 客户端私钥
password: password, // 私钥密码
protocols: [socket.Protocol.TLSv12],
cipherSuite: 'AES256-SHA256'
};
const connectOptions: socket.TLSConnectOptions = {
address: remoteAddr,
secureOptions: secureOptions
};
await this.tls.connect(connectOptions);
}
/**
* 发送加密数据
*/
async send(data: string): Promise<void> {
await this.tls.send(data);
}
/**
* 关闭连接
*/
async close(): Promise<void> {
await this.tls.close();
this.tls.off('message');
this.tls.off('connect');
this.tls.off('close');
}
}
五、完整示例:网络管理器应用
创建一个统一的网络管理器,整合所有网络能力:
typescript
import { http } from '@kit.NetworkKit';
import { webSocket } from '@kit.NetworkKit';
import { socket } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
/**
* 网络管理器单例
*/
class NetworkManager {
private static instance: NetworkManager;
private wsClient: WebSocketClient | null = null;
private tcpClient: TCPSocketClient | null = null;
private constructor() {}
public static getInstance(): NetworkManager {
if (!NetworkManager.instance) {
NetworkManager.instance = new NetworkManager();
}
return NetworkManager.instance;
}
/**
* HTTP GET请求
*/
async httpGet<T>(url: string): Promise<T> {
const httpRequest = http.createHttp();
try {
const response = await httpRequest.request(url, {
method: http.RequestMethod.GET,
header: { 'Content-Type': 'application/json' },
expectDataType: http.HttpDataType.STRING,
connectTimeout: 60000,
readTimeout: 60000
});
if (response.responseCode === 200) {
return JSON.parse(response.result as string);
} else {
throw new Error(`HTTP ${response.responseCode}`);
}
} finally {
httpRequest.destroy();
}
}
/**
* HTTP POST请求
*/
async httpPost<T>(url: string, data: Object): Promise<T> {
const httpRequest = http.createHttp();
try {
const response = await httpRequest.request(url, {
method: http.RequestMethod.POST,
header: { 'Content-Type': 'application/json' },
extraData: JSON.stringify(data),
expectDataType: http.HttpDataType.STRING,
connectTimeout: 60000,
readTimeout: 60000
});
if (response.responseCode === 200) {
return JSON.parse(response.result as string);
} else {
throw new Error(`HTTP ${response.responseCode}`);
}
} finally {
httpRequest.destroy();
}
}
/**
* 下载文件并显示进度
*/
async downloadFile(
url: string,
onProgress: (received: number, total: number) => void
): Promise<ArrayBuffer> {
const downloader = new HttpStreamDownloader();
return await downloader.downloadFile(url, onProgress);
}
/**
* 连接WebSocket
*/
async connectWebSocket(url: string): Promise<WebSocketClient> {
if (this.wsClient) {
await this.wsClient.close();
}
this.wsClient = new WebSocketClient(url);
await this.wsClient.connect();
return this.wsClient;
}
/**
* 获取WebSocket客户端
*/
getWebSocketClient(): WebSocketClient | null {
return this.wsClient;
}
/**
* 连接TCP Socket
*/
async connectTCPSocket(host: string, port: number): Promise<TCPSocketClient> {
if (this.tcpClient) {
await this.tcpClient.close();
}
this.tcpClient = new TCPSocketClient();
await this.tcpClient.connect(host, port);
return this.tcpClient;
}
/**
* 获取TCP Socket客户端
*/
getTCPSocketClient(): TCPSocketClient | null {
return this.tcpClient;
}
/**
* 清理所有连接
*/
async cleanup(): Promise<void> {
if (this.wsClient) {
await this.wsClient.close();
this.wsClient = null;
}
if (this.tcpClient) {
await this.tcpClient.close();
this.tcpClient = null;
}
}
}
export default NetworkManager;
使用示例页面
typescript
import { BusinessError } from '@kit.BasicServicesKit';
import NetworkManager from './NetworkManager';
@Entry
@Component
struct NetworkTestPage {
@State message: string = '网络测试';
@State httpResult: string = '';
@State downloadProgress: string = '0%';
@State wsStatus: string = '未连接';
@State tcpStatus: string = '未连接';
private networkManager = NetworkManager.getInstance();
build() {
Column({ space: 20 }) {
Text(this.message)
.fontSize(24)
.fontWeight(FontWeight.Bold)
// HTTP测试区
Text('HTTP请求测试')
.fontSize(18)
.fontWeight(FontWeight.Medium)
Button('GET请求')
.onClick(() => this.testHttpGet())
Button('POST请求')
.onClick(() => this.testHttpPost())
Button('下载文件')
.onClick(() => this.testDownload())
Text(this.httpResult)
.fontSize(14)
Text(`下载进度: ${this.downloadProgress}`)
.fontSize(14)
Divider()
// WebSocket测试区
Text('WebSocket测试')
.fontSize(18)
.fontWeight(FontWeight.Medium)
Text(`状态: ${this.wsStatus}`)
.fontSize(14)
Button('连接WebSocket')
.onClick(() => this.testWebSocket())
Button('发送WebSocket消息')
.onClick(() => this.sendWebSocketMessage())
Divider()
// TCP Socket测试区
Text('TCP Socket测试')
.fontSize(18)
.fontWeight(FontWeight.Medium)
Text(`状态: ${this.tcpStatus}`)
.fontSize(14)
Button('连接TCP')
.onClick(() => this.testTCPSocket())
Button('发送TCP消息')
.onClick(() => this.sendTCPMessage())
}
.width('100%')
.height('100%')
.padding(20)
}
/**
* 测试HTTP GET请求
*/
async testHttpGet(): Promise<void> {
try {
const result = await this.networkManager.httpGet('https://api.example.com/data');
this.httpResult = JSON.stringify(result);
} catch (err) {
this.httpResult = `请求失败: ${err}`;
}
}
/**
* 测试HTTP POST请求
*/
async testHttpPost(): Promise<void> {
try {
const data = { name: 'test', value: 123 };
const result = await this.networkManager.httpPost('https://api.example.com/submit', data);
this.httpResult = JSON.stringify(result);
} catch (err) {
this.httpResult = `请求失败: ${err}`;
}
}
/**
* 测试文件下载
*/
async testDownload(): Promise<void> {
try {
const data = await this.networkManager.downloadFile(
'https://example.com/file.zip',
(received, total) => {
const percent = Math.floor((received / total) * 100);
this.downloadProgress = `${percent}%`;
}
);
this.httpResult = `下载完成,大小: ${data.byteLength} 字节`;
this.downloadProgress = '100%';
} catch (err) {
this.httpResult = `下载失败: ${err}`;
}
}
/**
* 测试WebSocket连接
*/
async testWebSocket(): Promise<void> {
try {
await this.networkManager.connectWebSocket('ws://example.com:8080');
this.wsStatus = '已连接';
} catch (err) {
this.wsStatus = `连接失败: ${err}`;
}
}
/**
* 发送WebSocket消息
*/
async sendWebSocketMessage(): Promise<void> {
const client = this.networkManager.getWebSocketClient();
if (!client) {
this.wsStatus = '未连接';
return;
}
try {
await client.sendText('Hello WebSocket!');
this.wsStatus = '消息已发送';
} catch (err) {
this.wsStatus = `发送失败: ${err}`;
}
}
/**
* 测试TCP Socket连接
*/
async testTCPSocket(): Promise<void> {
try {
await this.networkManager.connectTCPSocket('192.168.1.100', 8888);
this.tcpStatus = '已连接';
} catch (err) {
this.tcpStatus = `连接失败: ${err}`;
}
}
/**
* 发送TCP消息
*/
async sendTCPMessage(): Promise<void> {
const client = this.networkManager.getTCPSocketClient();
if (!client) {
this.tcpStatus = '未连接';
return;
}
try {
await client.send('Hello TCP!');
this.tcpStatus = '消息已发送';
} catch (err) {
this.tcpStatus = `发送失败: ${err}`;
}
}
aboutToDisappear(): void {
// 页面销毁时清理连接
this.networkManager.cleanup();
}
}
六、最佳实践
6.1 网络请求优化
- 连接复用: HTTP/2和HTTP/3支持连接复用,减少握手开销
- 超时设置: 根据业务场景合理设置connectTimeout和readTimeout
- 资源释放: 及时调用destroy()释放HttpRequest对象
- 缓存策略: 合理使用usingCache参数,减少重复请求
6.2 错误处理
typescript
async function robustHttpRequest<T>(url: string, retries: number = 3): Promise<T> {
let lastError: Error | null = null;
for (let i = 0; i < retries; i++) {
try {
const result = await NetworkManager.getInstance().httpGet<T>(url);
return result;
} catch (err) {
lastError = err as Error;
console.error(`请求失败,第${i + 1}次重试:`, err);
// 等待一段时间后重试
await new Promise(resolve => setTimeout(resolve, 1000 * Math.pow(2, i)));
}
}
throw lastError || new Error('请求失败');
}
6.3 证书安全配置
在src/main/resources/base/profile/network_config.json配置证书锁定:
json
{
"network-security-config": {
"domain-config": [
{
"domains": [
{
"include-subdomains": true,
"name": "api.example.com"
}
],
"pin-set": {
"expiration": "2025-12-31",
"pin": [
{
"digest-algorithm": "sha256",
"digest": "base64encodedpinvalue"
}
]
}
}
]
}
}
6.4 性能监控
typescript
class NetworkPerformanceMonitor {
static async measureRequestTime(url: string): Promise<number> {
const startTime = Date.now();
try {
await NetworkManager.getInstance().httpGet(url);
return Date.now() - startTime;
} catch (err) {
console.error('请求失败:', err);
return -1;
}
}
static async checkNetworkQuality(): Promise<string> {
const testUrl = 'https://www.example.com';
const responseTime = await this.measureRequestTime(testUrl);
if (responseTime < 0) return '网络异常';
if (responseTime < 100) return '网络优秀';
if (responseTime < 300) return '网络良好';
if (responseTime < 1000) return '网络一般';
return '网络较差';
}
}
七、常见问题
Q1: 应用退到后台后Socket断开怎么办?
A: 应用退后台后Socket可能断开,需要在重回前台时检测并重连:
typescript
onPageShow(): void {
// 检查连接状态
const client = this.networkManager.getTCPSocketClient();
if (client && !client.isConnected()) {
// 重新连接
this.reconnectSocket();
}
}
Q2: 如何处理大文件上传?
A: 使用multipart/form-data格式,设置更长的超时时间:
typescript
async uploadLargeFile(filePath: string): Promise<void> {
const httpRequest = http.createHttp();
await httpRequest.request(url, {
method: http.RequestMethod.POST,
header: { 'Content-Type': 'multipart/form-data' },
multiFormDataList: [{
name: 'file',
contentType: 'application/octet-stream',
filePath: filePath,
remoteFileName: 'large_file.zip'
}],
readTimeout: 600000, // 10分钟
connectTimeout: 60000
});
}
Q3: WebSocket如何实现心跳保活?
A: HarmonyOS的WebSocket已内置心跳机制,每30秒自动发送Ping帧,60秒无响应会断开连接。开发者无需额外实现。