网络管理模块是HarmonyOS应用开发中不可或缺的一部分,它负责处理与网络相关的任务,如HTTP数据请求、WebSocket连接和Socket连接。本文将详细介绍如何使用OHOS平台提供的网络管理模块来实现这些功能和代码示例。

HTTP数据请求

权限申请

在开始之前,确保你的应用已经申请了ohos.permission.INTERNETohos.permission.SET_NETWORK_INFO 权限,这将允许应用进行网络通信。

接口说明

HTTP数据请求主要由http模块提供,包括创建请求、发起请求、订阅响应头事件等。

HarmonyOS入门之网络管理模块_HTTP

开发步骤
  1. 导入http模块
import http from '@ohos.net.http';
  • 1.
  1. 创建HTTP请求对象
let httpRequest = http.createHttp();
  • 1.
  1. 订阅HTTP响应头事件
httpRequest.on('headersReceive', (header) => {
    console.info('header: ' + JSON.stringify(header));
});
  • 1.
  • 2.
  • 3.
  1. 发起HTTP请求
httpRequest.request("EXAMPLE_URL", {
    method: http.RequestMethod.POST,
    header: { 'Content-Type': 'application/json' },
    extraData: { "data": "data to send" },
    expectDataType: http.HttpDataType.STRING,
    usingCache: true,
    priority: 1,
    connectTimeout: 60000,
    readTimeout: 60000,
    usingProtocol: http.HttpProtocol.HTTP1_1,
}, (err, data) => {
    if (!err) {
        console.info('Result:' + JSON.stringify(data.result));
        console.info('code:' + JSON.stringify(data.responseCode));
        console.info('header:' + JSON.stringify(data.header));
        console.info('cookies:' + JSON.stringify(data.cookies));
    } else {
        console.info('error:' + JSON.stringify(err));
        httpRequest.off('headersReceive');
        httpRequest.destroy();
    }
});
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.

WebSocket连接

权限申请

同样地,使用WebSocket功能也需要ohos.permission.INTERNET权限。

接口说明

WebSocket连接由webSocket模块提供,包括创建连接、订阅事件、发送与接收数据等。

HarmonyOS入门之网络管理模块_WebSocket_02

开发步骤
  1. 导入webSocket模块
import webSocket from '@ohos.net.webSocket';
  • 1.
  1. 创建WebSocket连接
let ws = webSocket.createWebSocket();
  • 1.
  1. 订阅事件
ws.on('open', (err, value) => {
    console.log("on open, status:" + JSON.stringify(value));
});
  • 1.
  • 2.
  • 3.
  1. 连接到服务器
ws.connect(defaultIpAddress, (err, value) => {
    if (!err) {
        console.log("Connected successfully");
    } else {
        console.log("Connection failed. Err:" + JSON.stringify(err));
    }
});
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  1. 发送与接收数据
ws.send("Hello, server!", (err, value) => {
    if (!err) {
        console.log("Message sent successfully");
    } else {
        console.log("Failed to send the message. Err:" + JSON.stringify(err));
    }
});
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  1. 关闭连接
ws.close((err, value) => {
    if (!err) {
        console.log("Connection closed successfully");
    } else {
        console.log("Failed to close the connection. Err: " + JSON.stringify(err));
    }
});
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

Socket连接:TCP、UDP与TLS

基本概念
  • Socket:是网络通信的端点,允许进程间双向通信。
  • TCP:面向连接、可靠的字节流传输层协议。
  • UDP:无连接的、面向消息的传输层协议。
  • TLS:为网络通信提供安全性与数据完整性的协议。
应用场景

OHOS平台支持通过TCP/UDP Socket进行数据传输以及利用TLS Socket进行加密通信。

TCP/UDP Socket通信

HarmonyOS入门之网络管理模块_TCP_03

TCP和UDP的Socket通信流程相似,下面以TCP为例展示如何使用OHOS的socket模块进行通信。

1import socket from '@ohos.net.socket';
2
3let tcp = socket.constructTCPSocketInstance();
4
5tcp.on('message', value => {
6  console.log("on message")
7  // Process received data
8});
9tcp.on('connect', () => {
10  console.log("on connect")
11});
12tcp.on('close', () => {
13  console.log("on close")
14});
15
16let bindAddress = {
17  address: '192.168.xx.xx',
18  port: 1234,
19  family: 1
20};
21tcp.bind(bindAddress, err => {
22  if (!err) {
23    console.log('bind success');
24    let connectAddress = {
25      address: '192.168.xx.xx',
26      port: 5678,
27      family: 1
28    };
29    tcp.connect({
30      address: connectAddress, timeout: 6000
31    }, err => {
32      if (!err) {
33        console.log('connect success');
34        tcp.send({
35          data: 'Hello, server!'
36        }, err => {
37          if (!err) {
38            console.log('send success');
39          }
40        });
41      }
42    });
43  }
44});
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
TLS Socket加密数据传输

HarmonyOS入门之网络管理模块_HTTP_04

TLS Socket通信在TCP基础上增加了加密层,保证数据传输的安全性。下面展示了一个双向认证的TLS Socket通信流程。

1import socket from '@ohos.net.socket';
2
3let tlsTwoWay: socket.TLSSocket = socket.constructTLSSocketInstance();
4
5let options = {
6  ALPNProtocols: ["spdy/1", "http/1.1"],
7  address: {
8    address: "192.168.xx.xxx",
9    port: xxxx,
10    family: 1,
11  },
12  secureOptions: {
13    key: "xxxx",
14    cert: "xxxx",
15    ca: ["xxxx"],
16    passwd: "xxxx",
17    protocols: [socket.Protocol.TLSv12],
18    useRemoteCipherPrefer: true,
19    signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",
20    cipherSuite: "AES256-SHA256",
21  },
22};
23
24tlsTwoWay.bind({ address: '192.168.xxx.xxx', port: xxxx, family: 1 }, err => {
25  if (!err) {
26    console.log('bind success');
27    // Subscribe to events and establish connection
28  }
29});
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.

确保在使用TLS Socket时正确配置了加密参数,如证书、密码套件等,以实现安全的网络通信。

为了保证应用的安全性和稳定性,务必在请求完成后释放资源,例如调用httpRequest.destroy()ws.close()tcp/tls.close()来关闭连接。同时,处理好异常情况,确保应用能够优雅地应对网络问题。