鸿蒙原生应用开发-网络管理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。

相关推荐
huang_xiaoen3 小时前
鸿蒙手机远程控制电脑哪个好用?2026鸿蒙远控软件横测推荐
华为·harmonyos·远程工作·远程工具·远程办公
爱写Bug的浮游1 天前
初识仓颉:5 分钟看懂核心语法
harmonyos·编程语言
程序猿追2 天前
鸿蒙 PC 的 Ionic 工单有两个错误,按下生成后光标该去哪儿
华为·harmonyos
KevinChaos2 天前
随手备忘录手记 04|HarmonyOS 7.0新特性实验:物品图鉴的加载逻辑
华为·harmonyos
Sirius_Ji2 天前
从硬解基座到字幕与滤镜链:ffmpeg-for-HarmonyOS v0.3.2
harmonyos
用户86194177207412 天前
uni-app 鸿蒙端提现点不动?我用 UTS 插件补上了微信"确认收款"
微信·harmonyos
码间留白2 天前
uni-app 鸿蒙端提现点不动?我用 UTS 插件补上了微信"确认收款"
uni-app·harmonyos·鸿蒙·uts插件·微信商家转账
GitCode官方3 天前
开源鸿蒙跨平台直播|AI 时代,用 cj-tauri 开发鸿蒙 PC 应用
人工智能·华为·harmonyos·atomgit
程序猿追3 天前
鸿蒙 PC 用 Tauri 做本地查找,怎样让慢请求给新请求让路
华为·状态模式·harmonyos
程序猿追3 天前
鸿蒙 PC 用 Ionic 做巡检目录,缩窄窗口后草稿还在吗
华为·harmonyos