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

相关推荐
Industio_触觉智能7 小时前
用鸿蒙开发鸿蒙!DevEco三件套已支持鸿蒙PC|触觉智能鸿蒙南向嵌入式厂家
华为·harmonyos·鸿蒙·鸿蒙系统·开发板·openharmony·开源鸿蒙
威哥爱编程13 小时前
HarmonyOS 7 Agent 开发实战 08:结构化输出解析
agent·harmonyos
威哥爱编程14 小时前
HarmonyOS 7 Agent 开发实战 09:Agent 测试评测集
agent·harmonyos
Eyfcom18 小时前
〖深度〗鸿蒙 ArkTS 移动应用开发经验:从 TypeScript 心智模型到声明式运行时的六层认知重构
typescript·移动开发·harmonyos·arkts
程序猿追19 小时前
把一份背包数据装进 NBT:KNBT 在鸿蒙上的标签与压缩实验
华为·harmonyos
行走的小派21 小时前
Harmony文件管理子系统实践:纯文本编辑器的大文件加载与编码处理
harmonyos·香橙派·应用开发
hqzing1 天前
在鸿蒙 PC 上使用 apt 安装 Debian 软件包(非虚拟机、非容器)
华为·debian·harmonyos
Marco_Marco1351 天前
定位SDK接入实战:Android/iOS/鸿蒙三端怎么选、怎么接
android·ios·harmonyos
梦想不只是梦与想1 天前
鸿蒙应用:区分真机和模拟器
harmonyos·deviceinfo·productmodel