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

相关推荐
结网的兔子15 分钟前
【前端开发】Web端迁移至 uni-app 及鸿蒙扩展方案对比
前端·uni-app·harmonyos
落叶飘飘s24 分钟前
餐饮服务与软件创新的融合:解析海底捞 APP 的 Flutter 鸿蒙开发之路
flutter·华为·harmonyos
qizayaoshuap2 小时前
# HarmonyOS ArkTS 滑动删除列表实战(三):交互式列表增删操作
华为·harmonyos
GitCode官方3 小时前
openPangu-2.0-Pro 模型及技术报告正式开源上线 AtomGit AI
人工智能·华为·开源·harmonyos·atomgit
想你依然心痛5 小时前
HarmonyOS 5.0智慧农业开发实战:构建分布式农业物联网与区块链农产品溯源系统
人工智能·分布式·物联网·区块链·智慧农业·harmonyos·开发实战
想你依然心痛18 小时前
ArkTS 布局系统概述——从线性到网格,掌握声明式 UI 的骨架艺术
harmonyos·arkts·flex弹性布局·声明式布局·grid网格布局·响应式适配·布局性能优化
程序员黑豆21 小时前
鸿蒙应用开发:@Computed 装饰器详解与实战
前端·harmonyos
ldsweet1 天前
HarmonyOS NEXT 音频播放器开发:AVPlayer 封装、播放列表与后台播放实战
华为·音视频·harmonyos
qizayaoshuap1 天前
# 44号应用:标签管理 — Flex 流式标签与交互状态设计
华为·harmonyos
哎呦喂我去去去1 天前
HarmonyOS SDK助力讯飞听见App能力建设
华为·harmonyos