鸿蒙笔记--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 权限

本地测试如下:

相关推荐
一隅论数智11 小时前
OWL(Web Ontology Language)介绍与使用举例(二)
大数据·经验分享·笔记·学习·自然语言处理·学习方法·政务
xq952713 小时前
ArkTS Component Generator 插件横空出世
harmonyos
Fate_I_C14 小时前
Capacitor 插件鸿蒙化实战:@capacitor/device 从安装到模拟器验证全记录
华为·harmonyos
sunoo-22915 小时前
【嵌入式Linux驱动学习】Day1-Day2 全流程梳理:环境搭建→U-Boot→内核→根文件系统→驱动基础
linux·运维·驱动开发·笔记·学习·阿里云·恩智浦
by2099916 小时前
list:迭代器与资源管理实现的综合叙述(下)
数据结构·c++·笔记·list
wdfk_prog16 小时前
LWIP教程 03:从 `low_level_input()` 到 `pbuf_free()`——`pbuf` 的数据视图、Chain 与引用计数
运维·网络·笔记·学习
yi01117 小时前
Leetcode 49 用 “身份证‘‘巧解
人工智能·笔记·python·算法·leetcode·哈希表
ouynagda17 小时前
嵌入式Linux i.MX6ULL系统移植学习笔记
linux·笔记·学习
yi01117 小时前
DAY22: LeetCode 733:图像渲染——从二维网格开始理解 DFS 和 BFS
数据结构·笔记·python·算法·leetcode·深度优先·宽度优先