鸿蒙原生应用开发-网络管理Socket连接(三)

应用通过TLS Socket进行加密数据传输

开发步骤

客户端TLS Socket流程:

1.import需要的socket模块。

2.绑定服务器IP和端口号。

3.双向认证上传客户端CA证书及数字证书;单向认证只上传CA证书,无需上传客户端证书。

4.创建一个TLSSocket连接,返回一个TLSSocket对象。

5.(可选)订阅TLSSocket相关的订阅事件。

6.发送数据。

7.TLSSocket连接使用完毕后,主动关闭。

复制代码
// 创建一个(双向认证)TLS Socket连接,返回一个TLS Socket对象。
import socket from '@ohos.net.socket';

let tlsTwoWay: socket.TLSSocket = socket.constructTLSSocketInstance();

// 设置通信过程中使用参数
let options = {
  ALPNProtocols: ["spdy/1", "http/1.1"],

  // 连接到指定的IP地址和端口。
  address: {
    address: "192.168.xx.xxx",
    port: xxxx, // 端口
    family: 1,
  },

  // 设置用于通信过程中完成校验的参数。
  secureOptions: {
    key: "xxxx",                            // 密钥
    cert: "xxxx",                           // 数字证书
    ca: ["xxxx"],                           // CA证书
    passwd: "xxxx",                         // 生成密钥时的密码
    protocols: [socket.Protocol.TLSv12],    // 通信协议
    useRemoteCipherPrefer: true,            // 是否优先使用对端密码套件
    signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256",    // 签名算法
    cipherSuite: "AES256-SHA256",           // 密码套件
  },
};

// 绑定本地IP地址和端口。
tlsTwoWay.bind({ address: '192.168.xxx.xxx', port: xxxx, family: 1 }, err => {
  if (err) {
    console.log('bind fail');
    return;
  }
  console.log('bind success');
  // 订阅TLS Socket相关的订阅事件
  tlsTwoWay.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)
  });
  tlsTwoWay.on('connect', () => {
    console.log("on connect")
  });
  tlsTwoWay.on('close', () => {
    console.log("on close")
  });

  // 建立连接
  tlsTwoWay.connect(options).then(() => {
    console.log('connect success');

    // 发送数据
    let sendBuf = 'client send to server...';
    tlsTwoWay.send(sendBuf).then(() => {
      console.log('client send ok');
    }).catch((err: Object) => {
      console.error('client send err: ' + JSON.stringify(err));
    })
  }).catch((err: Object) => {
    console.log('connect failed ' + JSON.stringify(err));
  });

  // 连接使用完毕后,主动关闭。取消相关事件的订阅。
  tlsTwoWay.close().then(() => {
    console.log('close success');
  }).catch((err: Object) => {
    console.log('close failed ' + JSON.stringify(err));
  });
  tlsTwoWay.off('message');
  tlsTwoWay.off('connect');
  tlsTwoWay.off('close');
});

本文参考引用HarmonyOS官方开发文档,基于API9。

相关推荐
shaodong11232 小时前
HarmonyOS NEXT 数据持久化三剑客:Preferences、RelationalStore 与 KVDB 选型实战
华为·harmonyos
richard_yuu2 小时前
鸿蒙从零搭建参赛项目|心晴驿站:开发环境配置、技术选型与项目规范落地
华为·harmonyos
shaodong11232 小时前
鸿蒙自定义弹窗(CustomDialog)的 8 种封装姿势
华为·harmonyos
xmdy58664 小时前
Flutter + 开源鸿蒙跨端实战|基于空间地理信息的**城市全域智慧泊车调度与多维运维管理平台** Day1 项目架构基座与工程化环境搭建
flutter·开源·harmonyos
KillerNoBlood4 小时前
2026移动端跨平台开发面经总结
android·算法·flutter·ios·移动开发·鸿蒙·kmp
枫叶丹45 小时前
【HarmonyOS 6.0】状态栏扩展新特性:点击状态栏图标展开二级菜单的场景动效详解
开发语言·华为·harmonyos
想你依然心痛6 小时前
HarmonyOS 6(API 23)实战:基于悬浮导航、沉浸光感与Face AR & Body AR的“灵犀筑境“——PC端沉浸式AR建筑空间评审系统
华为·ar·harmonyos·悬浮导航·沉浸光感
xmdy58666 小时前
Flutter+开源鸿蒙全域智慧泊车调度管理平台 Day4 订单全流程闭环+支付核验+会员权益+个人中心开发
flutter·开源·harmonyos
前端不太难6 小时前
鸿蒙 App 多端 UI 不一致的原因
ui·状态模式·harmonyos
unique_williams6 小时前
开源 | 我用 HarmonyOS + Spring Boot 写了一个全栈背单词 App,已上架 GitHub
springboot·鸿蒙