HarmonyOS中的网络编程与Socket通信怎么实现?

HarmonyOS中的网络编程与Socket通信怎么实现?

阅读 663
1 个回答

目前HarmonyOS提供的网络库:https://gitee.com/openharmony-tpc/tpc_resource#%E7%BD%91%E7%B...
原生库模块当前提供有socket通信暂无其他使用的封装库,socket通信可参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides...
对于无法解析消息的情况,可参考以下代码示例:

import socket from ‘@ohos.net.socket’;
import { BusinessError } from ‘@ohos.base’;
import util from ‘@ohos.util’;
import { TAG } from ‘…/…/entryability/EntryAbility’;

class SocketInfo {
  message: ArrayBuffer = new ArrayBuffer(1);
  remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo;
}

// 同步序列号
let hasSync = false
let syncNo = new Uint8Array(4)
let mask = 0xb0100000

let textEncoder = new util.TextEncoder(‘utf-8’);
let textDecoder = util.TextDecoder.create(‘utf-8’, {
  fatal: true,
  ignoreBOM: true
});

function encode(message: string, c: number): ArrayBuffer {
// 版本信息
let version = new Uint8Array(1)
// 标记位
let flag = new Uint8Array(1)
// 命令码
let cmd = new Uint8Array(2)
// 消息长度
let len = new Uint8Array(4)
// 消息
let content = textEncoder.encodeInto(message)

version[0] = 1
flag[0] = 0
cmd[1] = c >> 8
cmd[0] 
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进