54.HarmonyOS鸿蒙系统 App(ArkTS)tcp socket套接字网络连接收发测试

news/2024/5/19 1:51:24

工程代码icon-default.png?t=N7T8https://download.csdn.net/download/txwtech/89258409?spm=1001.2014.3001.5501

54.HarmonyOS鸿蒙系统 App(ArkTS)tcp socket套接字网络连接收发测试

import socket from '@ohos.net.socket';
import process from '@ohos.process';
import wifiManager from '@ohos.wifiManager';import common from '@ohos.app.ability.common';
import StringUtils from './uint8array2string';
import StringUtils2 from '../http2/uint8array2string_test'let tcp = socket.constructTCPSocketInstance();//let ipAddress = wifiManager.getIpInfo().ipAddress; //真机测试
//let local_ip2 = (ipAddress>>24 &0xFF)+"."+(ipAddress>>16 &0xFF)+"."+(ipAddress>>8 &0xFF)+"."
//+(ipAddress &0xFF) //真机测试
let local_ip2 = '10.0.2.16' //用于模拟器,真机则屏蔽此处
let tcp_on_msg = ''@Entry
@Component
struct Index {@State message: string = 'Hello World'@State local_ip:string = local_ip2@State local_port:number =6666@State ip_addr:string ='192.168.10.104'@State port:number =8080@State send_msg:string ='send content'@State recv_msg:string =''build() {Column() {Row(){Text(' ')}Row(){Text('TCP socket测试连接').fontSize(38).fontColor(Color.White).backgroundColor(Color.Blue)}Row(){Text('本机IP:').fontSize(28).backgroundColor(Color.Green)TextInput({text:`${this.local_ip}`}).fontSize(28).width(280).backgroundColor(Color.Transparent).onChange((value:string)=>{this.local_ip = value})}Row(){Text('端口:').fontSize(28).backgroundColor(Color.Green)TextInput({text:`${this.local_port}`}).fontSize(28).width(280).backgroundColor(Color.Transparent).onChange((value:string)=>{this.local_port = parseInt(value, 10); //字符转数字})}Row(){Text('服务器IP:').fontSize(28).backgroundColor(Color.Green)TextInput({text:`${this.ip_addr}`}).fontSize(28).width(280).backgroundColor(Color.Transparent).onChange((value:string)=>{this.ip_addr = value})}Row(){Text('端口:').fontSize(28).backgroundColor(Color.Green)TextInput({text:`${this.port}`}).fontSize(28).width(280).backgroundColor(Color.Transparent).onChange((value:string)=>{this.port = parseInt(value, 10); //字符转数字})}Row(){Text('发送:').fontSize(28)}.align(Alignment.Start)Row(){TextArea({text:`${this.send_msg}`}).fontSize(28).height(100).onChange((value:string)=>{this.send_msg = value})}Row(){Text('接收:').fontSize(28)}.align(Alignment.Start)Row(){TextArea({text:`${this.recv_msg}`}).fontSize(28) //文本自动换行.height(200).onChange((value:string)=>{this.recv_msg = value})}Row(){Button('连接').width(100).fontSize(28).onClick(() => {// 绑定IP地址和端口。//连接服务器,必须首先绑定本机IPlet bindAddress = {address: this.local_ip,port: this.local_port, // 绑定端口,如1234family: 1};tcp.bind(bindAddress, err => {if (err) {console.log('bind fail_local');this.recv_msg = 'connect fail_local,IP:'+this.local_ipreturn;}console.log('bind success_local');this.recv_msg = 'connect fail_local,IP:'+this.local_ip})let connectAddress = {address: this.ip_addr,port: this.port, // 连接端口,如5678family: 1};tcp.connect({address: connectAddress, timeout: 3000},err=>{if (err) {console.log('connect fail_remote');this.recv_msg = 'connect fail_remote,IP:'+this.ip_addrreturn;}console.log('connect success');this.recv_msg = 'connect success_remote,IP:'+this.ip_addr})tcp.on('message', value => {console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo)this.recv_msg = this.recv_msg+StringUtils.arrayBuffer2String(value.message);});})Button('______').onClick((event: ClickEvent) => {})Button('发送').width(100).fontSize(28).onClick((event: ClickEvent) => {tcp.send({data: this.send_msg}, err => {if (err) {console.log('send fail');this.recv_msg='send fail_remote'return;}console.log('send success');this.recv_msg='send success_remote';})})}Row(){Button('退出').width(100).fontSize(28).onClick((event: ClickEvent) => {tcp.close();const context = getContext(this) as common.UIAbilityContext;context.terminateSelf();let applicationContext = context.getApplicationContext();// applicationContext.killProcessesBySelf().// then((data)=>// {console.log('The process running information is:'+ JSON.stringify(data));})//   .catch((error)=>{console.error('error:'+ JSON.stringify(error));})// process.kill(0, process.pid)// process.exit(0)})}}.width('100%').padding(20) //边距.backgroundColor(Color.Gray)}
}

配置权限:

arkts获取真机本机IP:

连接远程服务器,tcp/ip,必须绑定本机IP

import StringUtils from './uint8array2string';

uint8array2string.ts

import util from '@ohos.util';class StringUtils {/*** string转Uint8Array* @param value* @returns*/string2Uint8Array1(value: string): Uint8Array {if (!value) return null;//let textEncoder = new util.TextEncoder();//获取点流并发出 UTF-8 字节流 TextEncoder 的所有实例仅支持 UTF-8 编码return textEncoder.encodeInto(value)}/*** string转Uint8Array* @param value 包含要编码的文本的源字符串* @param dest 存储编码结果的Uint8Array对象实例* @returns 它返回一个包含读取和写入的两个属性的对象*/string2Uint8Array2(value: string, dest: Uint8Array) {if (!value) return null;if (!dest) dest = new Uint8Array(value.length);let textEncoder = new util.TextEncoder();//read:它是一个数值,指定转换为 UTF-8 的字符串字符数。如果 uint8Array 没有足够的空间,这可能小于 src.length(length of source 字符串)。//dest:也是一个数值,指定存储在目标 Uint8Array 对象 Array 中的 UTF-8 unicode 的数量。它总是等于阅读。textEncoder.encodeIntoUint8Array(value, dest)// let result = textEncoder.encodeIntoUint8Array(value, dest)// result.read// result.written}/*** Uint8Array 转  String* @param input*/uint8Array2String(input: Uint8Array) {let textDecoder = util.TextDecoder.create("utf-8", { ignoreBOM: true })return textDecoder.decodeWithStream(input, { stream: false });}/*** ArrayBuffer 转  String* @param input* @returns*/arrayBuffer2String(input: ArrayBuffer) {return this.uint8Array2String(new Uint8Array(input))}
}export default new StringUtils()


http://www.mrgr.cn/p/40455108

相关文章

2. 基础配置

1. 配置文件格式 1.1 配置文件自动提示功能消失解决方案 ​​ 1.2 SpringBoot配置文件加载顺序(了解) application.properties > application.yml > application.yaml 1.3 注意事项 SpringBoot核心配置文件名为application SpringBoot内置属性过多,且所有属性集中…

Qt/C++音视频开发72-倍速推流/音视频同步倍速推流/不改变帧率和采样率/低倍速和高倍速

一、前言 最近多了个新需求,需要倍速推流,推流界的扛把子obs也有倍速推流功能,最高支持到两倍速。这里所说的倍速,当然只限定在文件,只有文件才可能有倍速功能,因为也只有文件才能倍速解码播放。实时视频流是不可能倍速的,因为没有时长,有时长的才可以按照播放进度来。…

Excel求解器使用教程

添加规则求解加载项创建excel文件,点击文件点击选项选择加载项->规则求解加载项->转到选择规则求解加载项->确定求解器所在位置---数据->规划求解在excel文档中填写相关的计算公式,用来求解点击规则求解,填写对应的目标,可变单元和约束,选择求解方法来求解通过…

虚拟机创建教程

虚拟机创建 创建虚拟机的时候,选择自定义,自己来创建虚拟机在虚拟机中,选择创建16.2.X版本的虚拟机,兼容性比较好在创建虚拟机的操作系统时,选择稍后安装操作系统,实测中如果选择其他的在安装过程中会跳过系统安装的部分阶段选择对应的系统和版本选择名称和安装位置,个人…

union 和union all 使用区别

union 和union all 把 查询user表前5条数据查询user表数据从第7条数据开始,查询两条 通过union来把两个sql中的数据合并到一张表中,只查询出一条数据,会把重复的数据去掉 通过union all查询 出现出了两条数据,不会去重

安全再升级,亚信安慧AntDB数据库与亚信安全二次牵手完成兼容性互认证

日前,湖南亚信安慧科技有限公司(简称:亚信安慧)的产品与亚信科技(成都)有限公司(简称:亚信安全)再次携手,完成亚信安慧AntDB数据库与亚信安全IPoE接入认证系统…

YOLO系列改进,自研模块助力涨点

目录 一、原理 二、代码 三、添加到YOLOv5中 一、原理 论文地址:

TypeError: Cannot read properties of undefined (reading trim)

运行时提示:TypeError: Cannot read properties of undefined (reading trim) 问题排查: 1、确认trim()属性是否存在,这个是js 去除字符串左右空格,属性是存在的 2、确认this.form.proxy_url是否存在 3、确认确认this.form.proxy_url的值是否为undefined和null 通过排查和打…

vue2 项目执行npm run serve 启动项目卡在24%一直不动

vue模板中添加了信息,应这样写:<div>接口管理</div>

使用Neo4j和Langchain创建知识图谱

使用Neo4j和Langchain创建知识图谱 知识图谱是组织和整合信息的强大工具。通过使用实体作为节点和关系作为边缘&#xff0c;它们提供了一种系统的知识表示方法。这种有条理的表示有利于简化查询、分析和推理&#xff0c;使知识图在搜索引擎、推荐系统、自然语言处理和人工智能…

富文本编辑器 iOS

https://gitee.com/klkxxy/WGEditor-mobile#wgeditor-mobile 采用iOS系统浏览器做的一款富文本编辑器工具。 原理就是使用WKWebView加载一个本地的一个html文件&#xff0c;从而达到编辑器功能的效果&#xff01; 由于浏览器的一些特性等&#xff0c;富文本编辑器手机端很难做…

深入理解网络原理3----TCP核心特性介绍(上)【面试高频考点】

文章目录 前言TCP协议段格式一、确认应答【保证可靠性传输的机制】二、超时重传【保证可靠性传输的机制】三、连接管理机制【保证可靠性传输的机制】3.1建立连接&#xff08;TCP三次握手&#xff09;---经典面试题3.2断开连接&#xff08;四次挥手&#xff09;3.3TCP状态转换 四…

FSNotes for Mac v6.7.1中文激活:轻量级笔记管理工具

FSNotes for Mac&#xff0c;一款专为Mac用户打造的轻量级笔记管理工具&#xff0c;让您的笔记管理变得简单而高效。 FSNotes for Mac v6.7.1中文激活版下载 它采用Markdown文件格式&#xff0c;让您轻松创建和编辑富文本笔记&#xff0c;无需担心格式问题。同时&#xff0c;FS…

关于google search console工具提交sitemap.xml无法抓取的问题解决办法

其实这个问题很好解决。 第一种情况&#xff1a;利用工具为我们的网站自动生成静态的sitemap.xml文件。这种可以检查下是否完整&#xff0c;然后上传到根目录下去&#xff0c;再去google search console提交我们的网站地图。 第二种情况&#xff1a;同样利用工具自动生成动态s…

博客园数据备份相关

OpenAPI文档 文档地址,使用前必须先申请权限,应用介绍要详细点。这种方式支持随笔和文章,不支持笔记。 管理后台备份只能在工作日18:00之后、8点之前或周六、周日进行操作,每天只允许备份一次。这种方式仅支持随笔。 使用爬虫 使用接口来模拟网页版的操作,使用 Jsoup 库来…

arduino uno+LCD12864(ST7735S)+蓝牙模块实现贪吃蛇

1.前言: 1.1本实验实现的贪吃蛇能穿越边界,结束游戏的唯一条件是贪吃蛇到达指定长度 1.2本实验所用LCD可能不是LCD12864,LCD12864所用库为u8glib,笔者在词库中并没有找到型号为ST77355的初始化函数,而是在ucglib中找到,其方法为 Ucglib_ST7735_18x128x160_SWSPI ucg(/*sc…

three.js入门指南

WebGL和Three.js的概念 什么是WebGL WebGL是基于OpenGL ES 2.0的Web标准&#xff0c;可以通过HTML5 Canvas元素作为DOM接口访问。 也就是WebGL是作为OpenGL的网页端入口。它作为一个底层标准&#xff0c;然后我们可以通过JavaScript代码&#xff0c;在网页上实现三维图形的渲…

3031087 -“无数据”:物料不显示在 MRP 应用中

症状 使用其中一个 MRP 应用&#xff08;监控物料覆盖范围、管理物料覆盖范围、监控外部需求等&#xff09;时无法找到物料。 用户在搜索过滤器时会收到错误消息“无数据”。 “本 KBA 中的图像/数据来自 SAP 内部系统、示例数据或演示系统。任何与真实数据相似的都是完全巧…

.NET 8 的openEuler 容器镜像

目前.NET 8的容器镜像已经支持openEuler,以openEuler为基础镜像的应用镜像:dotnet-deps、dotnet-runtime 和 dotnet-aspnet。基础镜像简介这里存放着由openEuler官方提供的容器镜像,包含openEuler基础镜像、应用镜像。在这里,你可以参考对应镜像的介绍,部署你需要的镜像容…