鸿蒙笔记--Socket

这一节主要了解鸿蒙Socket通信,在鸿蒙系统中,Socket TCP通讯是一种常用的网络通信方式,它提供了可靠的、面向连接的数据传输服务。它主要用到@ohos.net.socket这个库;

TypeScript 复制代码
constructTCPSocketInstance:创建一个 TCPSocket;
connect:连接目标服务器;
bind:绑定端口;
send:发送数据;
close:关闭连接;
on:打开对应事件的监听;
off:关闭对应事件的监听;

栗子:

TypeScript 复制代码
export default class SocketUtils  {

  public static connect(host: string, mPort: number,data:string) {
     let socketTcp = socket.constructTCPSocketInstance();
     let localAddress = {
       address: host,
       family: 1,
       port: mPort
     }
     let tcpOptions = {
        address:localAddress,
        timeout:15000
     }
     console.log("connect >>>> tcpOptions:"+JSON.stringify(tcpOptions));

     let promise = socketTcp.connect(tcpOptions)
     promise.then(() => {
       console.log(" connect >>>> ok ");
       sendSocketData(socketTcp,data)
     }).catch(err => {
       console.log(" connect >>>> err:"+JSON.stringify(err));
     })

  }
}

function sendSocketData(socketTcp: socket.TCPSocket, data: string) {
  let options ={
    data:JSON.stringify(data)
  }
  socketTcp.send(options,(err,data) => {
    if(err) {
      console.log(" sendSocketData >>>> err:"+JSON.stringify(err));
    } else {
      console.log(" sendSocketData >>>> success data :"+JSON.stringify(data));
    }
  })

  socketTcp.on("message",(message)=> {
    const content = StringUtils.arrayBuffer2String(message.message)
    console.log(" sendSocketData >>>> message content:"+content);
  })
}

import util from '@ohos.util';
class StringUtils {
  string2Uint8Array1(value: string): Uint8Array {
    if (!value) return null;
    //
    let textEncoder = new util.TextEncoder();
    //获取点流并发出 UTF-8 字节流 TextEncoder 的所有实例仅支持 UTF-8 编码
    return textEncoder.encodeInto(value)
  }
  uint8Array2String(input: Uint8Array) {
    let textDecoder = util.TextDecoder.create("utf-8", { ignoreBOM: true })
    return textDecoder.decodeWithStream(input, { stream: false });
  }

  arrayBuffer2String(input: ArrayBuffer) {
    return this.uint8Array2String(new Uint8Array(input))
  }
}
export default new StringUtils()

注:发起 http 网络请求需要申请 ohos.permission.INTERNET 权限

本地测试如下:

相关推荐
就叫飞六吧1 天前
Java “跨平台”指的是(.class 字节码)跨平台,而不是指 JVM 这个软件本身跨平台
服务器·笔记
lowhot1 天前
C语言UI框架
c语言·开发语言·笔记·ui
sunfove1 天前
数理物理方法笔记:微分算子与拉普拉斯算子介绍
笔记
老骥伏枥_H1 天前
信息系统项目管理师_第十七章 项目绩效域(中)
笔记
EchoL、1 天前
Diffusers库安装
笔记
googleccsdn1 天前
ENSP Pro Lab笔记:配置BGP EVPN VXLAN双栈(1)
网络·笔记
baobao熊1 天前
【Harmony OS 6】IBest-ORM库使用详解(一)
华为·harmonyos
admin838374841_1 天前
部署若依分离版本
笔记
墨&白.1 天前
机器学习速成笔记week9:决策树ID3、C4.5和CART的底层逻辑
笔记·决策树·机器学习
lally.1 天前
传统漏洞的演变
笔记·安全架构