基础语法综合示例-比较全的教程,官方代码学习产出
·
/**
* 1. 文档注释:基础语法综合示例
* 适配鸿蒙 SDK 6.0 ArkTS
*/
// 接口定义
interface ListType {
length?: number
}
interface DataType {
list?: ListType
}
// 2. 变量定义:let(可变)/const(常量)
let userName: string = "鸿蒙开发者"; // 显式类型声明
const MAX_COUNT: number = 100; // 常量(推荐全大写)
let isLogin: boolean = false;
// 3. 鸿蒙特有数据类型:Resource(资源引用)
let titleText: Resource = $r('app.string.app_name'); // 引用 string.json 中的资源
//let bgColor: Resource = $r('app.color.primary_color'); // 引用 color.json 中的资源
// 4. 数据转换
let numStr: string = "123";
let num: number = Number(numStr); // 字符串转数字
let jsonStr: string = '{"name":"鸿蒙","version":"6.0"}';
let jsonObj: object = JSON.parse(jsonStr); // JSON 字符串转对象
let objStr: string = JSON.stringify(jsonObj); // 对象转 JSON 字符串
// 5. 算术运算符 + 6. 比较运算符 + 7. 逻辑运算符
let a: number = 10, b: number = 5;
let sum: number = a + b; // 算术运算
let isBigger: boolean = a > b; // 比较运算
let isOk: boolean = (a > 0) && (b < 10); // 逻辑运算
// 8. 位运算符(状态码处理示例)
const PERMISSION_READ: number = 0b0001; // 1
const PERMISSION_WRITE: number = 0b0010; // 2
let currentPerm: number = PERMISSION_READ | PERMISSION_WRITE; // 位或:0b0011
let hasRead: boolean = (currentPerm & PERMISSION_READ) !== 0; // 位与:判断是否有读权限
// 9. 赋值运算符
let count: number = 0;
count += 1; // 等价于 count = count + 1
// 10. 三元运算符(鸿蒙 UI 场景:根据状态显示不同文案)
let loginBtnText: string = isLogin ? "退出登录" : "请登录";
// 11. 空值处理运算符(避免空指针)
let data: DataType | null = { list: { length: 5 } };
let listLength: number = data?.list?.length ?? 0; // 可选链 + 空值合并
// 12. 类型断言(鸿蒙 API 响应数据处理)
let res: string = "鸿蒙 SDK 6.0";
let resStr: string = res;
@Entry
@Component
struct BasicSyntaxDemo {
build() {
Column() {
// 渲染展示
Text(`变量:${userName}`)
Text(`资源引用:${titleText}`)
Text(`算术运算:${a}+${b}=${sum}`)
Text(`权限判断:是否有读权限?${hasRead}`)
Text(`按钮文案:${loginBtnText}`)
Text(`空值处理:列表长度=${listLength}`)
}
.width('100%')
.padding(20)
}
}
import { ArrayList, HashMap, Queue } from '@kit.ArkTS'; // 导入鸿蒙标准数据结构
// 1. 原生数组(鸿蒙 List 组件渲染核心)
let fruitArray: string[] = ["苹果", "香蕉", "橙子"];
// 数组操作:添加、过滤、映射
fruitArray.push("葡萄");
let filterFruit = fruitArray.filter(item => item.includes("果")); // 过滤含「果」的元素
let upperFruit = fruitArray.map(item => item.toUpperCase()); // 转大写
// 2. 鸿蒙 ArrayList(动态列表,线程安全)
let fruitList: ArrayList<string> = new ArrayList();
fruitList.add("苹果");
fruitList.add("香蕉");
fruitList.removeByIndex(0); // 删除第一个元素
// 3. 鸿蒙 HashMap(键值对存储)
let userMap: HashMap<string, string> = new HashMap();
userMap.set("name", "鸿蒙");
userMap.set("version", "6.0");
// 4. 原生 Map
let configMap: Map<string, number> = new Map();
configMap.set("maxSize", 1024);
configMap.set("timeout", 5000);
// 5. 队列(鸿蒙任务队列场景)
let taskQueue: Queue<string> = new Queue();
taskQueue.add("任务1");
taskQueue.add("任务2");
let firstTask: string | undefined = taskQueue.pop(); // 出队:任务1
// 6. 元组(多返回值场景)
let result: [number, string] = [200, "请求成功"]; // 状态码 + 提示语
// 7. 枚举(UI 状态管理)
enum PageState {
Loading,
Success,
Fail
}
let currentState: PageState = PageState.Success;
@Entry
@Component
struct DataStructureDemo {
build() {
Column() {
Text(`ArrayList 长度:${fruitList.length}`)
Text(`HashMap 获取值:${userMap.get("name")}`)
Text(`队列首个任务:${firstTask}`)
Text(`页面状态:${PageState[currentState]}`) // 输出:Success
Text(`元组:状态码=${result[0]}, 信息=${result[1]}`)
// 鸿蒙 ForEach 渲染数组(核心场景)
ForEach(fruitArray, (item: string) => {
Text(item)
.fontSize(16)
.margin(5)
}, (item: string) => item)
}
.width('100%')
.padding(20)
}
}
@Entry
@Component
struct ControlFlowDemo {
@State score: number = 85;
@State pageCode: number = 200;
@State dataList: string[] = ["数据1", "数据2", "数据3"];
// 使用计算属性替代全局变量
get grade(): string {
if (this.score >= 90) {
return "优秀";
} else if (this.score >= 80) {
return "良好";
} else {
return "及格";
}
}
get pageMsg(): string {
switch (this.pageCode) {
case 200:
return "请求成功";
case 404:
return "资源不存在";
default:
return "未知错误";
}
}
get loopText(): string {
let result = "";
// for 循环遍历
for (let i = 0; i < this.dataList.length; i++) {
result += `${this.dataList[i]} `;
}
return result.trim();
}
get filteredText(): string {
let result = "";
for (let item of this.dataList) {
if (item === "数据2") {
continue;
}
if (item === "数据3") {
break;
}
result += item;
}
return result;
}
build() {
Column() {
// 1. if-else 分支(使用计算属性)
Text(`成绩等级:${this.grade}`)
// 2. switch-case(使用计算属性)
Text(`接口状态:${this.pageMsg}`)
// 3. for 循环结果
Text(`for 循环结果:${this.loopText}`)
// 4. 循环控制结果
Text(`循环控制结果:${this.filteredText}`)
// 5. 鸿蒙 UI 条件渲染
if (this.score >= 90) {
Text("恭喜,成绩优秀!")
.fontColor(Color.Green)
}
// 6. ForEach 列表渲染(正确用法)
ForEach(this.dataList, (item: string) => {
Text(item)
.fontSize(16)
.backgroundColor(Color.Grey)
.padding(5)
.margin(2)
}, (item: string) => item)
// 7. 动态数值显示
Text(`当前数值:${this.getCurrentNum()}`)
}
.width('100%')
.padding(20)
}
// 获取动态数值的方法
private getCurrentNum(): number {
let num = 0;
while (num < 3) {
num++;
}
return num;
}
}
@Entry
@Component
struct FunctionDemo {
@State count: number = 0;
@State asyncResult: string = ""; // 异步结果状态
// 1. 普通函数定义(移到组件外部或作为方法)
private add(a: number, b: number): number {
return a + b;
}
// 2. 函数参数:默认参数、可选参数、剩余参数
private getUserInfo(name: string, age?: number, ...hobbies: string[]): string {
let ageStr = age ?? "未知";
return `姓名:${name},年龄:${ageStr},爱好:${hobbies.join(",")}`;
}
// 3. 箭头函数作为方法
private multiply = (a: number, b: number): number => a * b;
// 4. 函数重载的 ArkTS 实现方式
private formatData(data: string): string;
private formatData(data: number): string;
private formatData(data: any): string {
if (typeof data === "string") {
return `字符串:${data}`;
} else {
return `数字:${data}`;
}
}
// 5. 异步函数:模拟鸿蒙 HTTP 请求
private async fetchData(): Promise<string> {
return new Promise((resolve) => {
setTimeout(() => {
resolve("异步请求成功(模拟鸿蒙网络请求)");
}, 1000);
});
}
// 异步任务执行方法
private async executeAsyncTask(): Promise<void> {
try {
const result = await this.fetchData();
this.asyncResult = result; // 更新状态触发重新渲染
} catch (error) {
this.asyncResult = "异步请求失败";
}
}
build() {
Column() {
// 1. 普通函数调用
Text(`普通函数:1+2=${this.add(1, 2)}`)
// 2. 函数参数调用
Text(this.getUserInfo("鸿蒙", 2, "开发", "学习"))
// 3. 箭头函数调用
Text(`箭头函数:3*4=${this.multiply(3, 4)}`)
// 4. 鸿蒙组件事件回调
Button("点击计数")
.onClick(() => {
this.count++; // 箭头函数正确绑定 this
})
Text(`计数:${this.count}`)
// 5. 异步函数调用
Button("执行异步任务")
.onClick(() => {
this.executeAsyncTask(); // 调用异步方法
})
// 异步结果显示
if (this.asyncResult) {
Text(`异步结果:${this.asyncResult}`)
.fontColor(Color.Blue)
}
// 6. 函数重载调用
Text(this.formatData("鸿蒙 SDK 6.0"))
Text(this.formatData(6))
// 7. 高阶函数示例(函数作为参数)
Button("高阶函数演示")
.onClick(() => {
this.processWithCallback((result: string) => {
this.asyncResult = `回调结果:${result}`;
});
})
}
.width('100%')
.padding(20)
}
// 高阶函数:接受回调函数作为参数
private processWithCallback(callback: (result: string) => void): void {
setTimeout(() => {
callback("数据处理完成");
}, 500);
}
}
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
@State pageCode: number = 200;
@State score: number = 85;
@State dataList: string[] = ["1", "2", "3", "4"];
// 使用@State变量替代计算属性,确保响应式更新
@State grade: string = "";
@State loopTextResult: string = "";
@State filteredTextResult: string = "";
aboutToAppear() {
// 在组件初始化时计算并设置值
this.calculateGrade();
this.calculateLoopText();
this.calculateFilteredText();
}
// 使用普通方法替代getter,确保正确执行
calculateGrade() {
if (this.score >= 90) {
this.grade = "A";
} else if (this.score > 80) {
this.grade = "B";
} else {
this.grade = "C";
}
}
calculateLoopText() {
let result = "";
for (let i = 0; i < this.dataList.length; i++) {
result += this.dataList[i];
}
this.loopTextResult = result;
}
calculateFilteredText() {
let result = "";
for (let item of this.dataList) {
if (item == "2") {
continue;
}
if (item == "3") {
break;
}
result += item;
}
this.filteredTextResult = result;
}
build() {
Column() {
// 显示计算结果,使用安全访问
Text(this.grade || "计算中...")
.fontSize(20)
.fontColor(Color.Black)
Text(`页面代码: ${this.pageCode}`)
.fontSize(16)
Text(`数组内容: ${this.dataList.join(", ")}`)
.fontSize(16)
Text(`__________________`)
.fontSize(14)
Text(this.loopTextResult || "循环文本计算中...")
.fontSize(18)
.fontColor(Color.Blue)
Text(this.filteredTextResult || "过滤文本计算中...")
.fontSize(18)
.fontColor(Color.Red)
if (this.score >= 60) {
Text("成绩合格 - great!")
.fontColor(Color.Green)
.fontSize(20)
}
// 显示数组元素
Text("数组元素详细显示:")
.fontSize(16)
.fontColor(Color.Gray)
ForEach(this.dataList, (item: string) => {
Text(`元素: ${item}`)
.fontSize(14)
.fontColor("#ffcf1f1f")
})
Text(`循环计数结果: ${this.getCurrentNum()}`)
.fontSize(16)
}
.padding(20)
.width('100%')
.height('100%')
}
getCurrentNum(): number {
let num = 0;
while (num < 3) {
num++;
}
return num;
}
}
/**
* 基础语法综合示例 - 修正版
* 适配鸿蒙 SDK 6.0 ArkTS
*/
@Entry
@Component
struct BasicSyntaxDemo {
// 2. 状态变量定义:使用 @State 装饰器
@State userName: string = "鸿蒙开发者";
@State isLogin: boolean = false;
@State count: number = 0;
@State a: number = 10;
@State b: number = 5;
// 常量定义(组件外部)
private readonly MAX_COUNT: number = 100;
private readonly PERMISSION_READ: number = 0b0001;
private readonly PERMISSION_WRITE: number = 0b0010;
// 计算属性:派生数据
private get sum(): number {
return this.a + this.b;
}
private get isBigger(): boolean {
return this.a > this.b;
}
private get isOk(): boolean {
return (this.a > 0) && (this.b < 10);
}
private get currentPerm(): number {
return this.PERMISSION_READ | this.PERMISSION_WRITE;
}
private get hasRead(): boolean {
return (this.currentPerm & this.PERMISSION_READ) !== 0;
}
private get loginBtnText(): string {
return this.isLogin ? "退出登录" : "请登录";
}
// 数据转换方法
private convertStringToNumber(numStr: string): number {
return Number(numStr) || 0;
}
private parseJson(jsonStr: string): any {
try {
return JSON.parse(jsonStr);
} catch {
return {};
}
}
private stringifyObject(obj: any): string {
return JSON.stringify(obj);
}
// 空值处理方法
private getSafeListLength(data: any): number {
return data?.list?.length ?? 0;
}
build() {
Column() {
// 变量展示
Text(`用户名:${this.userName}`)
.fontSize(18)
.fontWeight(FontWeight.Bold)
// 常量展示
Text(`最大计数:${this.MAX_COUNT}`)
// 算术运算结果
Text(`算术运算:${this.a} + ${this.b} = ${this.sum}`)
// 比较运算结果
Text(`比较运算:${this.a} > ${this.b} = ${this.isBigger}`)
// 逻辑运算结果
Text(`逻辑运算:(${this.a} > 0) && (${this.b} < 10) = ${this.isOk}`)
// 权限判断
Text(`权限判断:是否有读权限?${this.hasRead}`)
// 按钮文案(根据状态动态变化)
Text(`按钮文案:${this.loginBtnText}`)
// 数据转换示例
Text(`字符串转数字:"123" → ${this.convertStringToNumber("123")}`)
// JSON 处理示例
let jsonStr: string = '{"name":"鸿蒙","version":"6.0"}';
let jsonObj = this.parseJson(jsonStr);
Text(`JSON解析:${this.stringifyObject(jsonObj)}`)
// 空值处理
let data: any = null;
Text(`空值处理:列表长度 = ${this.getSafeListLength(data)}`)
// 类型断言示例
let res: any = "鸿蒙 SDK 6.0";
let resStr: string = res as string;
Text(`类型断言:${resStr}`)
// 交互组件演示状态变化
Button("切换登录状态")
.onClick(() => {
this.isLogin = !this.isLogin;
})
Button("增加数值A")
.onClick(() => {
this.a += 1;
})
Button("增加数值B")
.onClick(() => {
this.b += 1;
})
Button("增加计数")
.onClick(() => {
this.count += 1;
})
.margin({ top: 10 })
Text(`当前计数:${this.count}`)
}
.width('100%')
.padding(20)
}
}
/**
* 基础语法综合示例 - 修正版
* 适配鸿蒙 SDK 6.0 ArkTS
*/
// 定义JSON数据结构接口
interface JsonData {
name: string;
version: string;
}
// 定义列表数据结构接口
interface ListData {
list?: object[];
}
@Entry
@Component
struct BasicSyntaxDemo {
// 2. 状态变量定义:使用 @State 装饰器
@State userName: string = "鸿蒙开发者";
@State isLogin: boolean = false;
@State count: number = 0;
@State a: number = 10;
@State b: number = 5;
// 新增状态变量用于演示
@State jsonData: JsonData = { name: "鸿蒙", version: "6.0" };
@State nullData: ListData | null = null;
@State typeAssertedString: string = "鸿蒙 SDK 6.0";
// 常量定义(组件外部)
private readonly MAX_COUNT: number = 100;
private readonly PERMISSION_READ: number = 0b0001;
private readonly PERMISSION_WRITE: number = 0b0010;
// 计算属性:派生数据
private get sum(): number {
return this.a + this.b;
}
private get isBigger(): boolean {
return this.a > this.b;
}
private get isOk(): boolean {
return (this.a > 0) && (this.b < 10);
}
private get currentPerm(): number {
return this.PERMISSION_READ | this.PERMISSION_WRITE;
}
private get hasRead(): boolean {
return (this.currentPerm & this.PERMISSION_READ) !== 0;
}
private get loginBtnText(): string {
return this.isLogin ? "退出登录" : "请登录";
}
// 数据转换方法
private convertStringToNumber(numStr: string): number {
return Number(numStr) || 0;
}
private parseJson(jsonStr: string): JsonData {
try {
return JSON.parse(jsonStr) as JsonData;
} catch {
return { name: "", version: "" };
}
}
private stringifyObject(obj: JsonData): string {
return JSON.stringify(obj);
}
// 空值处理方法
private getSafeListLength(data: ListData | null): number {
return data?.list?.length ?? 0;
}
build() {
Column() {
// 变量展示
Text(`用户名:${this.userName}`)
.fontSize(18)
.fontWeight(FontWeight.Bold)
// 常量展示
Text(`最大计数:${this.MAX_COUNT}`)
// 算术运算结果
Text(`算术运算:${this.a} + ${this.b} = ${this.sum}`)
// 比较运算结果
Text(`比较运算:${this.a} > ${this.b} = ${this.isBigger}`)
// 逻辑运算结果
Text(`逻辑运算:(${this.a} > 0) && (${this.b} < 10) = ${this.isOk}`)
// 权限判断
Text(`权限判断:是否有读权限?${this.hasRead}`)
// 按钮文案(根据状态动态变化)
Text(`按钮文案:${this.loginBtnText}`)
// 数据转换示例
Text(`字符串转数字:"123" → ${this.convertStringToNumber("123")}`)
// JSON 处理示例 - 使用预定义数据
Text(`JSON解析:${this.stringifyObject(this.jsonData)}`)
// 空值处理
Text(`空值处理:列表长度 = ${this.getSafeListLength(this.nullData)}`)
// 类型断言示例
Text(`类型断言:${this.typeAssertedString}`)
// 交互组件演示状态变化
Button("切换登录状态")
.onClick(() => {
this.isLogin = !this.isLogin;
})
Button("增加数值A")
.onClick(() => {
this.a += 1;
})
Button("增加数值B")
.onClick(() => {
this.b += 1;
})
Button("增加计数")
.onClick(() => {
this.count += 1;
})
.margin({ top: 10 })
Text(`当前计数:${this.count}`)
}
.width('100%')
.padding(20)
}
}
@Entry
@Component
struct Index {
// 基础状态数据 - 单向绑定
@State message: string = 'Hello World';
// 双向绑定数据 - 使用@State实现数据同步
@State userName: string = 'HarmonyOS User';
@State newTaskText: string = '';
// 复杂对象数据绑定
@State userInfo: UserInfo = new UserInfo('张三', 25, 'developer@example.com');
// 列表数据绑定
@State todoList: Array<TodoItem> = [
new TodoItem('学习HarmonyOS', false),
new TodoItem('实现双向绑定', false),
new TodoItem('测试应用功能', true)
];
build() {
Column() {
// 1. 基础文本双向绑定展示
Text(this.message)
.fontSize($r('app.float.page_text_font_size'))
.fontWeight(FontWeight.Bold)
.margin({ top: 50, bottom: 30 })
.onClick(() => {
// 数据变更自动同步到UI
this.message = this.message === 'Hello World' ? 'Welcome to HarmonyOS' : 'Hello World';
})
// 2. 输入框双向绑定
Text('输入框双向绑定示例:')
.fontSize(18)
.fontWeight(FontWeight.Medium)
.margin({ bottom: 10 })
TextInput({ text: this.userName })
.width('80%')
.height(50)
.backgroundColor(Color.White)
.borderRadius(10)
.padding(10)
.margin({ bottom: 15 })
.onChange((value: string) => {
// UI输入变更实时同步到数据
this.userName = value;
})
Text('当前用户名: ' + this.userName)
.fontSize(16)
.fontColor(Color.Blue)
.margin({ bottom: 30 })
// 3. 复杂对象数据绑定
Text('复杂对象数据绑定:')
.fontSize(18)
.fontWeight(FontWeight.Medium)
.margin({ bottom: 10 })
Text('用户信息: ' + this.userInfo.name + ', ' + this.userInfo.age + '岁')
.fontSize(16)
.fontColor(Color.Green)
.padding(10)
.backgroundColor('#e8f5e8')
.borderRadius(8)
.margin({ bottom: 15 })
.onClick(() => {
// 修改对象属性,UI自动更新
this.userInfo.age += 1;
this.userInfo.name = this.userInfo.name === '张三' ? '李四' : '张三';
// 需要重新赋值触发更新
})
// 4. 列表数据双向绑定
Text('列表数据双向绑定:')
.fontSize(18)
.fontWeight(FontWeight.Medium)
.margin({ bottom: 10 })
Column() {
Text('待办事项列表:')
.fontSize(16)
.fontWeight(FontWeight.Bold)
.margin({ bottom: 10 })
ForEach(this.todoList, (item: TodoItem, index: number) => {
Row() {
Checkbox({ name: item.task, group: 'todo' })
.select(item.completed)
.onChange((value: boolean) => {
// 复选框状态变更同步到数据
this.todoList[index].completed = value;
// 需要重新赋值触发更新
this.todoList = [...this.todoList];
})
Text(item.task)
.fontSize(14)
.margin({ left: 10 })
.decoration({ type: item.completed ? TextDecorationType.LineThrough : TextDecorationType.None })
.fontColor(item.completed ? Color.Gray : Color.Black)
.layoutWeight(1)
Button('删除')
.fontSize(12)
.height(30)
.backgroundColor(Color.Red)
.fontColor(Color.White)
.onClick(() => {
// 删除任务,数据变更自动同步到UI
this.todoList.splice(index, 1);
this.todoList = [...this.todoList];
})
}
.width('100%')
.height(50)
.justifyContent(FlexAlign.SpaceBetween)
.padding(10)
.backgroundColor(Color.White)
.borderRadius(8)
.margin({ bottom: 8 })
})
// 添加新任务
Row() {
TextInput({ text: this.newTaskText })
.width('70%')
.height(40)
.backgroundColor(Color.White)
.borderRadius(5)
.padding(8)
.onChange((value: string) => {
this.newTaskText = value;
})
Button('添加')
.width('25%')
.height(40)
.margin({ left: 10 })
.backgroundColor(Color.Blue)
.fontColor(Color.White)
.onClick(() => {
if (this.newTaskText.trim() !== '') {
this.todoList.push(new TodoItem(this.newTaskText.trim(), false));
this.todoList = [...this.todoList]; // 触发更新
this.newTaskText = ''; // 清空输入框
}
})
}
.width('100%')
.margin({ top: 15 })
}
.width('90%')
.padding(15)
.backgroundColor('#f5f5f5')
.borderRadius(10)
.margin({ bottom: 20 })
// 5. 数据统计展示
Text(`已完成: ${this.getCompletedCount()}/${this.todoList.length}`)
.fontSize(16)
.fontColor(Color.Red)
.fontWeight(FontWeight.Bold)
.margin({ bottom: 20 })
// 6. 重置按钮
Button('重置所有数据')
.width('60%')
.height(45)
.backgroundColor(Color.Orange)
.fontColor(Color.White)
.fontSize(16)
.onClick(() => {
// 重置所有数据,展示完整的数据绑定流程
this.message = 'Hello World';
this.userName = 'HarmonyOS User';
this.userInfo = new UserInfo('张三', 25, 'developer@example.com');
this.todoList = [
new TodoItem('学习HarmonyOS', false),
new TodoItem('实现双向绑定', false),
new TodoItem('测试应用功能', true)
];
this.newTaskText = '';
})
}
.width('100%')
.height('100%')
.backgroundColor('#f0f0f0')
.padding(20)
.alignItems(HorizontalAlign.Center)
}
// 获取已完成任务数量
private getCompletedCount(): number {
return this.todoList.filter(item => item.completed).length;
}
}
// 用户信息类
class UserInfo {
name: string;
age: number;
email: string;
constructor(name: string, age: number, email: string) {
this.name = name;
this.age = age;
this.email = email;
}
}
// 待办事项类
class TodoItem {
task: string;
completed: boolean;
constructor(task: string, completed: boolean) {
this.task = task;
this.completed = completed;
}
}
import preferences from '@ohos.data.preferences';
import common from '@ohos.app.ability.common';
@Entry
@Component
struct Index {
@State message: string = 'Preferences示例';
@State storedValue: string = '';
@State preferences: preferences.Preferences | null = null;
@State keyInput: string = '';
@State valueInput: string = '';
context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
async aboutToAppear() {
// 创建或获取Preferences实例
try {
this.preferences = await preferences.getPreferences(this.context, 'myPreferences');
this.message = 'Preferences初始化成功';
await this.loadStoredValue();
} catch (err) {
this.message = 'Preferences初始化失败: ' + (err as Error).message;
}
}
async loadStoredValue() {
if (!this.preferences) return;
try {
// 读取存储的值,如果不存在则返回默认值
const value = await this.preferences.get('myKey', '无数据');
this.storedValue = String(value);
} catch (err) {
console.error('读取数据失败:', err);
}
}
// 保存数据
async saveData() {
if (!this.preferences || !this.keyInput || !this.valueInput) {
this.message = '请输入键和值';
return;
}
try {
await this.preferences.put(this.keyInput, this.valueInput);
await this.preferences.flush(); // 提交更改
this.message = `数据保存成功: ${this.keyInput} = ${this.valueInput}`;
this.keyInput = '';
this.valueInput = '';
await this.loadStoredValue();
} catch (err) {
this.message = '保存数据失败: ' + (err as Error).message;
}
}
// 读取数据
async readData() {
if (!this.preferences || !this.keyInput) {
this.message = '请输入要读取的键';
return;
}
try {
const value = await this.preferences.get(this.keyInput, '键不存在');
this.message = `读取结果: ${this.keyInput} = ${value}`;
} catch (err) {
this.message = '读取数据失败: ' + (err as Error).message;
}
}
// 删除数据
async deleteData() {
if (!this.preferences || !this.keyInput) {
this.message = '请输入要删除的键';
return;
}
try {
await this.preferences.delete(this.keyInput);
await this.preferences.flush();
this.message = `数据删除成功: ${this.keyInput}`;
this.keyInput = '';
this.valueInput = '';
await this.loadStoredValue();
} catch (err) {
this.message = '删除数据失败: ' + (err as Error).message;
}
}
// 清空所有数据
async clearAllData() {
if (!this.preferences) return;
try {
await this.preferences.clear();
await this.preferences.flush();
this.message = '所有数据已清空';
this.keyInput = '';
this.valueInput = '';
await this.loadStoredValue();
} catch (err) {
this.message = '清空数据失败: ' + (err as Error).message;
}
}
build() {
Column({ space: 20 }) {
// 标题
Text(this.message)
.fontSize(24)
.fontWeight(FontWeight.Bold)
.margin({ top: 40 })
// 当前存储的值显示
Text('当前存储的值: ' + this.storedValue)
.fontSize(16)
.fontColor(Color.Blue)
.margin({ top: 10 })
// 输入区域
Column({ space: 10 }) {
TextInput({ placeholder: '请输入键名' })
.width('80%')
.height(40)
.border({ width: 1, color: Color.Gray })
.onChange((value: string) => {
this.keyInput = value;
})
TextInput({ placeholder: '请输入值' })
.width('80%')
.height(40)
.border({ width: 1, color: Color.Gray })
.onChange((value: string) => {
this.valueInput = value;
})
}
.margin({ top: 20 })
// 操作按钮
Row({ space: 10 }) {
Button('保存数据')
.backgroundColor(Color.Green)
.fontColor(Color.White)
.onClick(() => {
this.saveData();
})
Button('读取数据')
.backgroundColor(Color.Blue)
.fontColor(Color.White)
.onClick(() => {
this.readData();
})
Button('删除数据')
.backgroundColor(Color.Red)
.fontColor(Color.White)
.onClick(() => {
this.deleteData();
})
}
.margin({ top: 20 })
// 清空按钮
Button('清空所有数据')
.backgroundColor(Color.Orange)
.fontColor(Color.White)
.onClick(() => {
this.clearAllData();
})
.margin({ top: 10 })
// 功能说明
Column({ space: 5 }) {
Text('功能说明:')
.fontSize(14)
.fontWeight(FontWeight.Bold)
.margin({ top: 30 })
Text('• 保存数据: 将键值对保存到Preferences')
.fontSize(12)
Text('• 读取数据: 根据键名读取对应的值')
.fontSize(12)
Text('• 删除数据: 删除指定的键值对')
.fontSize(12)
Text('• 清空所有: 删除Preferences中的所有数据')
.fontSize(12)
}
.alignItems(HorizontalAlign.Start)
.width('80%')
.margin({ top: 20 })
}
.width('100%')
.height('100%')
.padding(20)
}
}
@Entry
@Component
struct Index {
@State message: string = '多层级交互事件演示';
@State tapCount: number = 0;
@State longPressCount: number = 0;
@State swipeCount: number = 0;
@State lastGesture: string = '无';
@State gestureHistory: string[] = [];
// 添加手势历史记录
addGestureHistory(gesture: string) {
if (this.gestureHistory.length >= 5) {
this.gestureHistory.shift();
}
this.gestureHistory.push(`${new Date().toLocaleTimeString()}: ${gesture}`);
}
build() {
Column({ space: 20 }) {
// 标题和统计信息
Column({ space: 10 }) {
Text(this.message)
.fontSize(30)
.fontWeight(FontWeight.Bold)
.fontColor('#007DFF')
.margin({ top: 30 })
Row({ space: 20 }) {
Column({ space: 5 }) {
Text(`点击: ${this.tapCount}`)
.fontSize(14)
.fontColor('#4CAF50')
Text(`长按: ${this.longPressCount}`)
.fontSize(14)
.fontColor('#FF9800')
Text(`滑动: ${this.swipeCount}`)
.fontSize(14)
.fontColor('#2196F3')
}
Column({ space: 5 }) {
Text(`最后手势: ${this.lastGesture}`)
.fontSize(14)
.fontColor('#9C27B0')
}
}
.margin({ top: 10 })
}
// 多层级事件冒泡演示区域
Column({ space: 15 }) {
Text('多层级事件冒泡演示')
.fontSize(18)
.fontWeight(FontWeight.Medium)
.fontColor('#333333')
.margin({ bottom: 10 })
// 第一层:最外层容器
Column({ space: 10 }) {
Text('第一层 - 最外层容器')
.fontSize(16)
.fontColor('#FFFFFF')
.padding(10)
.backgroundColor('#4CAF50')
.borderRadius(8)
// 第二层:中间容器
Row({ space: 10 }) {
// 第二层左侧 - 阻止冒泡
Column({ space: 8 }) {
Column() {
Text('第二层左侧-阻止冒泡')
.fontSize(14)
.fontColor('#FFFFFF')
.padding(8)
.backgroundColor('#FF9800')
.borderRadius(6)
}
.onClick(() => {
this.message = '第二层左侧被点击';
this.tapCount++;
this.lastGesture = '点击-第二层左侧';
this.addGestureHistory('点击-第二层左侧');
})
// 第三层:内层元素
Column() {
Text('第三层 - 内层元素')
.fontSize(12)
.fontColor('#FFFFFF')
.padding(6)
.backgroundColor('#9C27B0')
.borderRadius(4)
}
.onClick(() => {
this.message = '第三层元素被点击';
this.tapCount++;
this.lastGesture = '点击-第三层';
this.addGestureHistory('点击-第三层');
})
}
// 第二层右侧 - 允许冒泡
Column({ space: 8 }) {
Column() {
Text('第二层右侧-允许冒泡')
.fontSize(14)
.fontColor('#FFFFFF')
.padding(8)
.backgroundColor('#2196F3')
.borderRadius(6)
}
.onClick(() => {
this.message = '第二层右侧被点击';
this.tapCount++;
this.lastGesture = '点击-第二层右侧';
this.addGestureHistory('点击-第二层右侧');
})
// 第三层:内层元素
Column() {
Text('第三层 - 内层元素')
.fontSize(12)
.fontColor('#FFFFFF')
.padding(6)
.backgroundColor('#E91E63')
.borderRadius(4)
}
.onClick(() => {
this.message = '第三层元素被点击';
this.tapCount++;
this.lastGesture = '点击-第三层';
this.addGestureHistory('点击-第三层');
})
}
}
.padding(15)
.backgroundColor('#E3F2FD')
.borderRadius(10)
.onClick(() => {
this.message = '第二层容器被点击';
this.tapCount++;
this.lastGesture = '点击-第二层容器';
this.addGestureHistory('点击-第二层容器');
})
}
.padding(20)
.backgroundColor('#F5F5F5')
.borderRadius(12)
.onClick(() => {
this.message = '第一层区域被点击';
this.tapCount++;
this.lastGesture = '点击-第一层区域';
this.addGestureHistory('点击-第一层区域');
})
}
.width('95%')
.margin({ top: 20 })
// 手势交互演示区域
Column({ space: 15 }) {
Text('手势交互演示区域')
.fontSize(18)
.fontWeight(FontWeight.Medium)
.fontColor('#333333')
// 手势检测区域
Column({ space: 10 }) {
Text('点击、长按、滑动此区域')
.fontSize(16)
.fontColor('#FFFFFF')
.padding(10)
.backgroundColor('#00000080')
.borderRadius(8)
.margin({ bottom: 10 })
// 手势检测层
Column() {
Text('手势交互层')
.fontSize(16)
.fontColor('#666666')
}
.width('100%')
.height(100)
.backgroundColor('#FFF3E0')
.borderRadius(15)
.justifyContent(FlexAlign.Center)
.alignItems(HorizontalAlign.Center)
.onClick(() => {
this.message = '点击事件触发';
this.tapCount++;
this.lastGesture = '点击-手势层';
this.addGestureHistory('点击-手势层');
})
.onTouch((event: TouchEvent) => {
if (event.type === TouchType.Down) {
// 长按检测 - 简单实现
setTimeout(() => {
if (event.type === TouchType.Down) {
this.message = '长按事件触发';
this.longPressCount++;
this.lastGesture = '长按-手势层';
this.addGestureHistory('长按-手势层');
}
}, 2000);
}
})
}
.width('95%')
.height(150)
.margin({ top: 10 })
.backgroundColor('#2196F3')
.borderRadius(15)
.justifyContent(FlexAlign.Center)
.alignItems(HorizontalAlign.Center)
}
.width('95%')
.alignItems(HorizontalAlign.Center)
// 手势历史记录
Column({ space: 8 }) {
Text('手势历史记录(最近5次)')
.fontSize(16)
.fontWeight(FontWeight.Medium)
.fontColor('#333333')
.margin({ top: 20 })
if (this.gestureHistory.length === 0) {
Text('暂无手势记录')
.fontSize(14)
.fontColor('#999999')
.fontStyle(FontStyle.Italic)
} else {
ForEach(this.gestureHistory, (item: string, index: number) => {
Text(`${index + 1}. ${item}`)
.fontSize(12)
.fontColor('#666666')
.textAlign(TextAlign.Start)
.width('90%')
}, (item: string) => item)
}
}
.width('95%')
.alignItems(HorizontalAlign.Start)
// 重置按钮
Button('重置计数器')
.width('80%')
.height(50)
.fontSize(18)
.fontColor('#FFFFFF')
.backgroundColor('#FF5722')
.borderRadius(10)
.margin({ top: 20, bottom: 30 })
.onClick(() => {
this.tapCount = 0;
this.longPressCount = 0;
this.swipeCount = 0;
this.lastGesture = '无';
this.gestureHistory = [];
this.message = '计数器已重置';
})
}
.width('100%')
.height('100%')
.backgroundColor('#FFFFFF')
.padding(15)
}
}
@Entry
@Component
struct Index {
@State message: string = '交互事件多层级处理演示';
@State eventHistory: string[] = [];
@State bubbleEnabled: boolean = true;
@State captureEnabled: boolean = false;
@State clickCount: number = 0;
@State currentLevel: number = 0;
// 添加事件历史记录
addEventHistory(event: string) {
if (this.eventHistory.length >= 8) {
this.eventHistory.shift();
}
this.eventHistory.push(`${new Date().toLocaleTimeString()}: ${event}`);
}
// 清空历史记录
clearHistory() {
this.eventHistory = [];
this.clickCount = 0;
this.message = '历史记录已清空';
}
build() {
Column({ space: 20 }) {
// 标题和控制面板
Column({ space: 15 }) {
Text(this.message)
.fontSize(30)
.fontWeight(FontWeight.Bold)
.fontColor('#007DFF')
.margin({ top: 30 })
// 统计信息
Row({ space: 30 }) {
Column({ space: 5 }) {
Text(`点击次数: ${this.clickCount}`)
.fontSize(16)
.fontColor('#4CAF50')
Text(`当前层级: ${this.currentLevel}`)
.fontSize(16)
.fontColor('#2196F3')
}
Column({ space: 5 }) {
Text(`事件冒泡: ${this.bubbleEnabled ? '开启' : '关闭'}`)
.fontSize(16)
.fontColor(this.bubbleEnabled ? '#FF9800' : '#9E9E9E')
Text(`事件捕获: ${this.captureEnabled ? '开启' : '关闭'}`)
.fontSize(16)
.fontColor(this.captureEnabled ? '#9C27B0' : '#9E9E9E')
}
}
.width('100%')
.justifyContent(FlexAlign.SpaceAround)
.padding(10)
.backgroundColor('#F5F5F5')
.borderRadius(8)
// 控制按钮
Row({ space: 10 }) {
Button(this.bubbleEnabled ? '关闭冒泡' : '开启冒泡')
.width('45%')
.height(40)
.fontSize(14)
.backgroundColor(this.bubbleEnabled ? '#FF9800' : '#4CAF50')
.onClick(() => {
this.bubbleEnabled = !this.bubbleEnabled;
this.message = `事件冒泡${this.bubbleEnabled ? '开启' : '关闭'}`;
})
Button('清空记录')
.width('45%')
.height(40)
.fontSize(14)
.backgroundColor('#F44336')
.onClick(() => {
this.clearHistory();
})
}
.width('100%')
.justifyContent(FlexAlign.SpaceAround)
}
// 多层级事件处理演示区域
Column({ space: 20 }) {
Text('多层级事件处理演示')
.fontSize(20)
.fontWeight(FontWeight.Medium)
.fontColor('#333333')
// 1. 基础事件冒泡演示
Column({ space: 10 }) {
Text('1. 基础事件冒泡演示')
.fontSize(16)
.fontColor('#4CAF50')
.fontWeight(FontWeight.Medium)
// 五层嵌套结构
Column({ space: 5 }) {
Text('第五层 - 最外层')
.fontSize(14)
.fontColor('#FFFFFF')
.padding(10)
.backgroundColor('#FF6B6B')
.borderRadius(8)
.onClick(() => {
this.message = '第五层被点击';
this.clickCount++;
this.currentLevel = 5;
this.addEventHistory('第五层点击');
})
Column({ space: 5 }) {
Text('第四层容器')
.fontSize(13)
.fontColor('#FFFFFF')
.padding(8)
.backgroundColor('#4ECDC4')
.borderRadius(6)
.onClick(() => {
this.message = '第四层被点击';
this.clickCount++;
this.currentLevel = 4;
this.addEventHistory('第四层点击');
})
Column({ space: 5 }) {
Text('第三层容器')
.fontSize(12)
.fontColor('#FFFFFF')
.padding(6)
.backgroundColor('#45B7D1')
.borderRadius(4)
.onClick(() => {
this.message = '第三层被点击';
this.clickCount++;
this.currentLevel = 3;
this.addEventHistory('第三层点击');
})
Column({ space: 5 }) {
Text('第二层容器')
.fontSize(11)
.fontColor('#FFFFFF')
.padding(4)
.backgroundColor('#96CEB4')
.borderRadius(3)
.onClick(() => {
this.message = '第二层被点击';
this.clickCount++;
this.currentLevel = 2;
this.addEventHistory('第二层点击');
})
Column({ space: 5 }) {
Text('第一层 - 最内层')
.fontSize(10)
.fontColor('#FFFFFF')
.padding(3)
.backgroundColor('#FFEAA7')
.borderRadius(2)
.onClick(() => {
this.message = '第一层被点击';
this.clickCount++;
this.currentLevel = 1;
this.addEventHistory('第一层点击');
})
}
.padding(8)
.backgroundColor('#DDA0DD')
.borderRadius(5)
.onClick(() => {
this.message = '第二层容器被点击';
this.clickCount++;
this.currentLevel = 2;
this.addEventHistory('第二层容器点击');
})
}
.padding(10)
.backgroundColor('#98D8C8')
.borderRadius(6)
.onClick(() => {
this.message = '第三层容器被点击';
this.clickCount++;
this.currentLevel = 3;
this.addEventHistory('第三层容器点击');
})
}
.padding(12)
.backgroundColor('#F7DC6F')
.borderRadius(7)
.onClick(() => {
this.message = '第四层容器被点击';
this.clickCount++;
this.currentLevel = 4;
this.addEventHistory('第四层容器点击');
})
}
.padding(14)
.backgroundColor('#BB8FCE')
.borderRadius(8)
.onClick(() => {
this.message = '第五层容器被点击';
this.clickCount++;
this.currentLevel = 5;
this.addEventHistory('第五层容器点击');
})
}
.padding(16)
.backgroundColor('#85C1E9')
.borderRadius(10)
.onClick(() => {
this.message = '最外层容器被点击';
this.clickCount++;
this.currentLevel = 6;
this.addEventHistory('最外层容器点击');
})
}
.width('95%')
.padding(10)
.backgroundColor('#F8F9FA')
.borderRadius(12)
// 2. 阻止事件冒泡演示
Column({ space: 10 }) {
Text('2. 阻止事件冒泡演示')
.fontSize(16)
.fontColor('#2196F3')
.fontWeight(FontWeight.Medium)
Column({ space: 8 }) {
Text('外层容器(点击会冒泡)')
.fontSize(14)
.fontColor('#FFFFFF')
.padding(10)
.backgroundColor('#4CAF50')
.borderRadius(8)
.onClick(() => {
this.message = '外层容器被点击';
this.clickCount++;
this.currentLevel = 1;
this.addEventHistory('外层容器点击');
})
Row({ space: 15 }) {
// 左侧 - 阻止冒泡
Column({ space: 5 }) {
Text('左侧-阻止冒泡')
.fontSize(12)
.fontColor('#FFFFFF')
.padding(8)
.backgroundColor('#FF9800')
.borderRadius(6)
.onClick((event: ClickEvent) => {
this.message = '左侧被点击 - 阻止冒泡';
this.clickCount++;
this.currentLevel = 2;
this.addEventHistory('左侧点击(阻止冒泡)');
if (!this.bubbleEnabled) {
// 在实际应用中,这里应该使用event.stopPropagation()
// 但HarmonyOS中需要特殊处理
this.addEventHistory('冒泡被阻止');
}
})
Text('内层元素')
.fontSize(10)
.fontColor('#FFFFFF')
.padding(6)
.backgroundColor('#E91E63')
.borderRadius(4)
.onClick(() => {
this.message = '左侧内层被点击';
this.clickCount++;
this.currentLevel = 3;
this.addEventHistory('左侧内层点击');
})
}
// 右侧 - 允许冒泡
Column({ space: 5 }) {
Text('右侧-允许冒泡')
.fontSize(12)
.fontColor('#FFFFFF')
.padding(8)
.backgroundColor('#2196F3')
.borderRadius(6)
.onClick(() => {
this.message = '右侧被点击 - 允许冒泡';
this.clickCount++;
this.currentLevel = 2;
this.addEventHistory('右侧点击(允许冒泡)');
})
Text('内层元素')
.fontSize(10)
.fontColor('#FFFFFF')
.padding(6)
.backgroundColor('#3F51B5')
.borderRadius(4)
.onClick(() => {
this.message = '右侧内层被点击';
this.clickCount++;
this.currentLevel = 3;
this.addEventHistory('右侧内层点击');
})
}
}
.padding(12)
.backgroundColor('#E3F2FD')
.borderRadius(8)
.onClick(() => {
this.message = '中间容器被点击';
this.clickCount++;
this.currentLevel = 2;
this.addEventHistory('中间容器点击');
})
}
.padding(15)
.backgroundColor('#F5F5F5')
.borderRadius(10)
.onClick(() => {
this.message = '外层区域被点击';
this.clickCount++;
this.currentLevel = 1;
this.addEventHistory('外层区域点击');
})
}
.width('95%')
.padding(10)
.backgroundColor('#F8F9FA')
.borderRadius(12)
// 3. 复杂交互场景
Column({ space: 10 }) {
Text('3. 复杂交互场景演示')
.fontSize(16)
.fontColor('#9C27B0')
.fontWeight(FontWeight.Medium)
Stack({ alignContent: Alignment.Center }) {
// 背景层
Column() {
Text('交互背景层')
.fontSize(14)
.fontColor('#666666')
}
.width('100%')
.height(120)
.backgroundColor('#FFF3E0')
.borderRadius(10)
.onClick(() => {
this.message = '背景层被点击';
this.clickCount++;
this.currentLevel = 1;
this.addEventHistory('背景层点击');
})
// 交互层
Column() {
Text('主交互区域')
.fontSize(16)
.fontColor('#FFFFFF')
.padding(15)
.backgroundColor('#00000080')
.borderRadius(8)
}
.width('80%')
.height(80)
.backgroundColor('#2196F350')
.borderRadius(10)
.onClick(() => {
this.message = '主交互区域被点击';
this.clickCount++;
this.currentLevel = 2;
this.addEventHistory('主交互区域点击');
})
// 浮动按钮
Column() {
Text('浮动按钮')
.fontSize(12)
.fontColor('#FFFFFF')
}
.width(60)
.height(60)
.backgroundColor('#FF5722')
.borderRadius(30)
.margin({ top: -30, right: -30 })
.onClick(() => {
this.message = '浮动按钮被点击';
this.clickCount++;
this.currentLevel = 3;
this.addEventHistory('浮动按钮点击');
})
}
.width('100%')
.height(120)
.onClick(() => {
this.message = 'Stack容器被点击';
this.clickCount++;
this.currentLevel = 0;
this.addEventHistory('Stack容器点击');
})
}
.width('95%')
.padding(10)
.backgroundColor('#F8F9FA')
.borderRadius(12)
// 事件历史记录
Column({ space: 8 }) {
Text('事件历史记录(最近8次)')
.fontSize(16)
.fontWeight(FontWeight.Medium)
.fontColor('#333333')
.margin({ top: 10 })
if (this.eventHistory.length === 0) {
Text('暂无事件记录')
.fontSize(14)
.fontColor('#999999')
.fontStyle(FontStyle.Italic)
} else {
ForEach(this.eventHistory, (item: string, index: number) => {
Text(`${index + 1}. ${item}`)
.fontSize(12)
.fontColor('#666666')
.textAlign(TextAlign.Start)
.width('95%')
.padding(2)
}, (item: string) => item)
}
}
.width('95%')
.alignItems(HorizontalAlign.Start)
.padding(10)
.backgroundColor('#F5F5F5')
.borderRadius(8)
}
.width('100%')
.alignItems(HorizontalAlign.Center)
}
.width('100%')
.height('100%')
.backgroundColor('#FFFFFF')
.padding(15)
}
}
import socket from '@ohos.net.socket';
import { BusinessError } from '@ohos.base';
@Entry
@Component
struct Index {
@State message: string = 'TCP/IP协议基础通信演示';
@State serverIP: string = '192.168.1.100';
@State serverPort: string = '8080';
@State clientMessage: string = 'Hello Server!';
@State connectionStatus: string = '未连接';
@State logMessages: string[] = [];
@State isConnected: boolean = false;
private tcpSocket: socket.TCPSocket | null = null;
// 添加日志
addLog(message: string) {
if (this.logMessages.length >= 10) {
this.logMessages.shift();
}
const timestamp = new Date().toLocaleTimeString();
this.logMessages.push(`[${timestamp}] ${message}`);
}
// 初始化TCP Socket
initTCPSocket() {
try {
this.tcpSocket = socket.constructTCPSocketInstance();
this.addLog('TCP Socket初始化成功');
// 监听连接事件
this.tcpSocket.on('connect', () => {
this.connectionStatus = '已连接';
this.isConnected = true;
this.addLog('连接到服务器成功');
});
// 监听消息接收事件 - 修正参数类型
this.tcpSocket.on('message', (data: socket.SocketMessageInfo) => {
const message = this.arrayBufferToString(data.message);
this.addLog(`收到消息: ${message}`);
});
// 监听关闭事件
this.tcpSocket.on('close', () => {
this.connectionStatus = '已断开';
this.isConnected = false;
this.addLog('连接已关闭');
});
// 监听错误事件
this.tcpSocket.on('error', (err: BusinessError) => {
this.connectionStatus = '连接错误';
this.isConnected = false;
this.addLog(`错误: ${err.code} - ${err.message}`);
});
} catch (error) {
const err = error as BusinessError;
this.addLog(`初始化失败: ${err.message}`);
}
}
// ArrayBuffer转字符串
arrayBufferToString(buffer: ArrayBuffer): string {
const uint8Array = new Uint8Array(buffer);
let result = '';
for (let i = 0; i < uint8Array.length; i++) {
result += String.fromCharCode(uint8Array[i]);
}
return result;
}
// 字符串转ArrayBuffer
stringToArrayBuffer(str: string): ArrayBuffer {
const buffer = new ArrayBuffer(str.length);
const uint8Array = new Uint8Array(buffer);
for (let i = 0; i < str.length; i++) {
uint8Array[i] = str.charCodeAt(i);
}
return buffer;
}
// 连接到服务器
connectToServer() {
if (!this.tcpSocket) {
this.initTCPSocket();
}
if (this.tcpSocket) {
try {
const netAddress: socket.NetAddress = {
address: this.serverIP,
port: parseInt(this.serverPort)
};
const tcpConnectOptions: socket.TCPConnectOptions = {
address: netAddress,
timeout: 5000
};
this.connectionStatus = '连接中...';
this.addLog(`正在连接到 ${this.serverIP}:${this.serverPort}`);
this.tcpSocket.connect(tcpConnectOptions, (err: BusinessError) => {
if (err) {
this.connectionStatus = '连接失败';
this.addLog(`连接失败: ${err.message}`);
}
});
} catch (error) {
const err = error as BusinessError;
this.addLog(`连接错误: ${err.message}`);
}
}
}
// 发送消息
sendMessage() {
if (!this.tcpSocket || !this.isConnected) {
this.addLog('请先建立连接');
return;
}
if (this.clientMessage.trim() === '') {
this.addLog('消息不能为空');
return;
}
try {
const data = this.stringToArrayBuffer(this.clientMessage);
this.tcpSocket.send({
data: data
}, (err: BusinessError) => {
if (err) {
this.addLog(`发送失败: ${err.message}`);
} else {
this.addLog(`发送成功: ${this.clientMessage}`);
}
});
} catch (error) {
const err = error as BusinessError;
this.addLog(`发送错误: ${err.message}`);
}
}
// 断开连接
disconnect() {
if (this.tcpSocket && this.isConnected) {
try {
this.tcpSocket.close((err: BusinessError) => {
if (err) {
this.addLog(`断开失败: ${err.message}`);
} else {
this.connectionStatus = '已断开';
this.isConnected = false;
this.addLog('已断开连接');
}
});
} catch (error) {
const err = error as BusinessError;
this.addLog(`断开错误: ${err.message}`);
}
}
}
// 组件销毁时清理资源
aboutToDisappear() {
if (this.tcpSocket) {
this.tcpSocket.close();
this.tcpSocket = null;
}
}
build() {
Scroll() {
Column({ space: 20 }) {
// 标题区域
Column({ space: 15 }) {
Text(this.message)
.fontSize(30)
.fontWeight(FontWeight.Bold)
.fontColor('#007DFF')
.margin({ top: 30 })
// 连接状态显示
Row({ space: 20 }) {
Column({ space: 5 }) {
Text('连接状态:')
.fontSize(16)
.fontColor('#333333')
Text(this.connectionStatus)
.fontSize(18)
.fontColor(this.isConnected ? '#4CAF50' : '#F44336')
.fontWeight(FontWeight.Bold)
}
Button(this.isConnected ? '断开连接' : '连接服务器')
.width(120)
.height(40)
.fontSize(14)
.backgroundColor(this.isConnected ? '#F44336' : '#4CAF50')
.onClick(() => {
if (this.isConnected) {
this.disconnect();
} else {
this.connectToServer();
}
})
}
.width('100%')
.justifyContent(FlexAlign.SpaceAround)
.padding(10)
.backgroundColor('#F5F5F5')
.borderRadius(8)
}
// 服务器配置区域
Column({ space: 10 }) {
Text('服务器配置')
.fontSize(18)
.fontWeight(FontWeight.Medium)
.fontColor('#333333')
Column({ space: 8 }) {
Row({ space: 10 }) {
Text('IP地址:')
.fontSize(14)
.fontColor('#666666')
.width('25%')
TextInput({ text: this.serverIP })
.width('75%')
.height(40)
.fontSize(14)
.backgroundColor('#FFFFFF')
.border({ width: 1, color: '#E0E0E0' })
.borderRadius(4)
.onChange((value: string) => {
this.serverIP = value;
})
}
Row({ space: 10 }) {
Text('端口号:')
.fontSize(14)
.fontColor('#666666')
.width('25%')
TextInput({ text: this.serverPort })
.width('75%')
.height(40)
.fontSize(14)
.backgroundColor('#FFFFFF')
.border({ width: 1, color: '#E0E0E0' })
.borderRadius(4)
.onChange((value: string) => {
this.serverPort = value;
})
}
}
.width('100%')
.padding(15)
.backgroundColor('#F8F9FA')
.borderRadius(10)
}
.width('95%')
// 消息发送区域
Column({ space: 10 }) {
Text('消息发送')
.fontSize(18)
.fontWeight(FontWeight.Medium)
.fontColor('#333333')
Column({ space: 8 }) {
Text('消息内容:')
.fontSize(14)
.fontColor('#666666')
.alignSelf(ItemAlign.Start)
TextInput({ text: this.clientMessage, placeholder: '输入要发送的消息' })
.width('100%')
.height(60)
.fontSize(14)
.backgroundColor('#FFFFFF')
.border({ width: 1, color: '#E0E0E0' })
.borderRadius(4)
.onChange((value: string) => {
this.clientMessage = value;
})
Button('发送消息')
.width('100%')
.height(45)
.fontSize(16)
.backgroundColor('#2196F3')
.fontColor('#FFFFFF')
.onClick(() => {
this.sendMessage();
})
}
.width('100%')
.padding(15)
.backgroundColor('#F8F9FA')
.borderRadius(10)
}
.width('95%')
// TCP协议说明区域
Column({ space: 10 }) {
Text('TCP协议基础说明')
.fontSize(18)
.fontWeight(FontWeight.Medium)
.fontColor('#333333')
Column({ space: 8 }) {
Text('• TCP是面向连接的可靠传输协议')
.fontSize(12)
.fontColor('#666666')
.alignSelf(ItemAlign.Start)
Text('• 提供数据包的顺序传输和错误检测')
.fontSize(12)
.fontColor('#666666')
.alignSelf(ItemAlign.Start)
Text('• 三次握手建立连接,四次挥手断开连接')
.fontSize(12)
.fontColor('#666666')
.alignSelf(ItemAlign.Start)
Text('• 适用于需要可靠传输的应用场景')
.fontSize(12)
.fontColor('#666666')
.alignSelf(ItemAlign.Start)
}
.width('100%')
.padding(15)
.backgroundColor('#E3F2FD')
.borderRadius(10)
}
.width('95%')
// 通信日志区域
Column({ space: 10 }) {
Text('通信日志')
.fontSize(18)
.fontWeight(FontWeight.Medium)
.fontColor('#333333')
Column({ space: 5 }) {
if (this.logMessages.length === 0) {
Text('暂无通信日志')
.fontSize(14)
.fontColor('#999999')
.fontStyle(FontStyle.Italic)
.padding(20)
} else {
ForEach(this.logMessages, (item: string, index: number) => {
Text(item)
.fontSize(12)
.fontColor('#666666')
.textAlign(TextAlign.Start)
.width('100%')
.padding(8)
.backgroundColor(index % 2 === 0 ? '#F9F9F9' : '#FFFFFF')
.borderRadius(4)
}, (item: string) => item)
}
}
.width('100%')
.height(200)
.padding(10)
.backgroundColor('#FFFFFF')
.border({ width: 1, color: '#E0E0E0' })
.borderRadius(8)
Row({ space: 10 }) {
Button('清空日志')
.width('45%')
.height(35)
.fontSize(12)
.backgroundColor('#FF9800')
.onClick(() => {
this.logMessages = [];
this.addLog('日志已清空');
})
Button('测试连接')
.width('45%')
.height(35)
.fontSize(12)
.backgroundColor('#4CAF50')
.onClick(() => {
this.addLog('开始测试连接...');
this.connectToServer();
})
}
.width('100%')
.justifyContent(FlexAlign.SpaceAround)
}
.width('95%')
.margin({ bottom: 30 })
}
.width('100%')
.padding(15)
}
.scrollable(ScrollDirection.Vertical)
.scrollBar(BarState.On)
.scrollBarColor('#007DFF')
.scrollBarWidth(10)
.edgeEffect(EdgeEffect.Spring)
.width('100%')
.height('100%')
.backgroundColor('#FFFFFF')
.onAppear(() => {
this.initTCPSocket();
})
}
}
@Entry
@Component
struct Index {
@State message: string = '容器交互事件演示'
@State clickCount: number = 0
build() {
Column({ space: 20 }) {
// 标题区域
Text(this.message)
.fontSize(30)
.fontWeight(FontWeight.Bold)
.fontColor(Color.Blue)
// 点击计数器
Text(`总点击次数: ${this.clickCount}`)
.fontSize(20)
.fontColor(Color.Red)
// 主要容器组件
GrandParentContainer({
onEventTriggered: () => {
this.clickCount++
}
})
// 滚动容器示例
Column({ space: 10 }) {
Text('滚动容器内容')
.fontSize(18)
.fontWeight(FontWeight.Medium)
Scroll() {
Column({ space: 8 }) {
ForEach([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], (item: number) => {
Text(`列表项 ${item}`)
.fontSize(16)
.padding(10)
.backgroundColor(item % 2 === 0 ? Color.Gray : Color.White)
.width('100%')
})
}
}
.height(200)
.width('90%')
.border({ width: 1, color: Color.Black })
}
.width('100%')
.alignItems(HorizontalAlign.Center)
// 操作说明
Text('操作说明: 点击各个容器组件观察事件传递')
.fontSize(14)
.fontColor(Color.Green)
.margin({ top: 20 })
}
.width('100%')
.height('100%')
.padding(20)
.backgroundColor('#F0F0F0')
}
}
@Component
struct GrandParentContainer {
@State private eventCount: number = 0
private onEventTriggered?: () => void
aboutToAppear(): void {
console.log('GrandParentContainer 组件已加载')
}
build() {
Column({ space: 15 }) {
Text('祖父容器')
.fontSize(24)
.fontWeight(FontWeight.Bold)
.fontColor('#FF6B35')
Text(`事件计数: ${this.eventCount}`)
.fontSize(18)
.fontColor(Color.Black)
// 嵌套容器示例
ParentContainer({
onChildClick: () => {
this.eventCount++
this.onEventTriggered?.()
}
})
// 容器样式演示
Column() {
Text('容器样式示例')
.fontSize(16)
.margin({ bottom: 10 })
Row({ space: 10 }) {
Column() {
Text('圆角')
.fontSize(14)
Blank()
.width(50)
.height(50)
.backgroundColor(Color.Blue)
.borderRadius(10)
}
Column() {
Text('边框')
.fontSize(14)
Blank()
.width(50)
.height(50)
.backgroundColor(Color.Orange)
.border({ width: 3, color: Color.Red })
}
Column() {
Text('阴影')
.fontSize(14)
Blank()
.width(50)
.height(50)
.backgroundColor(Color.Green)
.shadow({ radius: 5, color: Color.Black, offsetX: 2, offsetY: 2 })
}
}
}
.padding(15)
.backgroundColor(Color.White)
.borderRadius(15)
.margin({ top: 10 })
}
.width('90%')
.padding(20)
.backgroundColor('#E8F4FD')
.borderRadius(20)
.alignItems(HorizontalAlign.Center)
}
}
@Component
struct ParentContainer {
private onChildClick?: () => void
@State private parentClickCount: number = 0
build() {
Column({ space: 12 }) {
Text('父容器')
.fontSize(20)
.fontWeight(FontWeight.Medium)
.fontColor('#4CAF50')
Text(`父容器点击: ${this.parentClickCount}`)
.fontSize(16)
// 第一行:布局演示
Row({ space: 20 }) {
Text('左对齐')
.fontSize(14)
.backgroundColor('#FFE0B2')
.padding(8)
.borderRadius(5)
Text('居中')
.fontSize(14)
.backgroundColor('#C8E6C9')
.padding(8)
.borderRadius(5)
Text('右对齐')
.fontSize(14)
.backgroundColor('#BBDEFB')
.padding(8)
.borderRadius(5)
}
.width('100%')
.justifyContent(FlexAlign.SpaceBetween)
// 第二行:空白和文本
Row({ space: 15 }) {
Text('左侧文本')
.fontSize(14)
Blank()
.backgroundColor(Color.Yellow)
.height(30)
.layoutWeight(1) // 占据剩余空间
Text('右侧文本')
.fontSize(14)
}
.width('100%')
.height(40)
.backgroundColor('#F5F5F5')
.padding(10)
.borderRadius(8)
// 第三行:子组件
Row({ space: 10 }) {
ChildComponent({
onButtonClick: () => {
this.parentClickCount++
this.onChildClick?.()
},
buttonText: '点击我!'
})
ChildComponent({
onButtonClick: () => {
this.parentClickCount += 2
this.onChildClick?.()
},
buttonText: '双击我!'
})
}
.width('100%')
.justifyContent(FlexAlign.SpaceAround)
.margin({ top: 10 })
}
.width('100%')
.padding(15)
.backgroundColor('#FFF3E0')
.borderRadius(15)
.border({ width: 2, color: '#FFA000' })
}
}
@Component
struct ChildComponent {
private onButtonClick?: () => void
private buttonText: string = '点击'
@State private isClicked: boolean = false
build() {
Column() {
Text(this.buttonText)
.fontSize(16)
.fontColor(this.isClicked ? Color.White : Color.Black)
.fontWeight(FontWeight.Medium)
}
.width(100)
.height(50)
.backgroundColor(this.isClicked ? '#2196F3' : '#E0E0E0')
.borderRadius(10)
.justifyContent(FlexAlign.Center)
.alignItems(HorizontalAlign.Center)
.onClick(() => {
this.isClicked = !this.isClicked
this.onButtonClick?.()
})
}
}
import socket from '@ohos.net.socket';
import { BusinessError } from '@ohos.base';
// 简化的MQTT协议实现
class SimpleMQTTClient {
private tcpSocket: socket.TCPSocket | null = null;
private isConnected: boolean = false;
private messageCallbacks: Map<string, (topic: string, message: string) => void> = new Map();
private clientId: string;
constructor(clientId: string) {
this.clientId = clientId;
}
// 连接到MQTT服务器
connect(host: string, port: number, onConnect?: () => void, onError?: (error: string) => void): void {
try {
this.tcpSocket = socket.constructTCPSocketInstance();
// 设置事件监听
this.tcpSocket.on('connect', () => {
this.isConnected = true;
this.sendConnectPacket();
if (onConnect) onConnect();
});
this.tcpSocket.on('message', (data: socket.SocketMessageInfo) => {
this.handleIncomingMessage(data.message);
});
this.tcpSocket.on('close', () => {
this.isConnected = false;
});
this.tcpSocket.on('error', (err: BusinessError) => {
this.isConnected = false;
if (onError) onError(`MQTT连接错误: ${err.message}`);
});
// 建立连接
const netAddress: socket.NetAddress = {
address: host,
port: port
};
const tcpConnectOptions: socket.TCPConnectOptions = {
address: netAddress,
timeout: 5000
};
this.tcpSocket.connect(tcpConnectOptions, (err: BusinessError) => {
if (err && onError) {
onError(`连接失败: ${err.message}`);
}
});
} catch (error) {
const err = error as BusinessError;
if (onError) onError(`初始化失败: ${err.message}`);
}
}
// 发送CONNECT包(简化版)
private sendConnectPacket(): void {
const connectMessage = `CONNECT|${this.clientId}`;
this.sendMessage(connectMessage);
}
// 订阅主题
subscribe(topic: string, callback: (topic: string, message: string) => void): void {
this.messageCallbacks.set(topic, callback);
if (this.isConnected) {
const subscribeMessage = `SUBSCRIBE|${topic}`;
this.sendMessage(subscribeMessage);
}
}
// 取消订阅
unsubscribe(topic: string): void {
this.messageCallbacks.delete(topic);
if (this.isConnected) {
const unsubscribeMessage = `UNSUBSCRIBE|${topic}`;
this.sendMessage(unsubscribeMessage);
}
}
// 发布消息
publish(topic: string, message: string): void {
if (this.isConnected) {
const publishMessage = `PUBLISH|${topic}|${message}`;
this.sendMessage(publishMessage);
}
}
// 断开连接
disconnect(): void {
if (this.tcpSocket && this.isConnected) {
const disconnectMessage = 'DISCONNECT';
this.sendMessage(disconnectMessage);
this.tcpSocket.close();
this.isConnected = false;
}
}
// 发送消息
private sendMessage(message: string): void {
if (this.tcpSocket && this.isConnected) {
const data = this.stringToArrayBuffer(message);
this.tcpSocket.send({ data: data });
}
}
// 处理接收到的消息
private handleIncomingMessage(buffer: ArrayBuffer): void {
const message = this.arrayBufferToString(buffer);
const parts = message.split('|');
if (parts.length >= 3 && parts[0] === 'PUBLISH') {
const topic = parts[1];
const payload = parts.slice(2).join('|');
const callback = this.messageCallbacks.get(topic);
if (callback) {
callback(topic, payload);
}
}
}
// 工具方法:ArrayBuffer转字符串
private arrayBufferToString(buffer: ArrayBuffer): string {
const uint8Array = new Uint8Array(buffer);
let result = '';
for (let i = 0; i < uint8Array.length; i++) {
result += String.fromCharCode(uint8Array[i]);
}
return result;
}
// 工具方法:字符串转ArrayBuffer
private stringToArrayBuffer(str: string): ArrayBuffer {
const buffer = new ArrayBuffer(str.length);
const uint8Array = new Uint8Array(buffer);
for (let i = 0; i < str.length; i++) {
uint8Array[i] = str.charCodeAt(i);
}
return buffer;
}
// 获取连接状态
getConnected(): boolean {
return this.isConnected;
}
}
@Entry
@Component
struct Index {
@State message: string = 'MQTT协议客户端演示';
@State brokerHost: string = 'test.mosquitto.org';
@State brokerPort: string = '1883';
@State clientId: string = 'harmonyos_client_' + Date.now().toString();
@State subscribeTopic: string = 'test/topic';
@State publishTopic: string = 'test/topic';
@State publishMessageContent: string = 'Hello MQTT!';
@State connectionStatus: string = '未连接';
@State logMessages: string[] = [];
@State subscribedTopics: string[] = [];
@State receivedMessages: string[] = [];
private mqttClient: SimpleMQTTClient | null = null;
// 添加日志
addLog(message: string) {
if (this.logMessages.length >= 15) {
this.logMessages.shift();
}
const timestamp = new Date().toLocaleTimeString();
this.logMessages.push(`[${timestamp}] ${message}`);
}
// 添加接收到的消息
addReceivedMessage(topic: string, message: string) {
if (this.receivedMessages.length >= 10) {
this.receivedMessages.shift();
}
const timestamp = new Date().toLocaleTimeString();
this.receivedMessages.push(`[${timestamp}] ${topic}: ${message}`);
}
// 连接到MQTT代理
connectToBroker() {
if (!this.mqttClient) {
this.mqttClient = new SimpleMQTTClient(this.clientId);
}
this.connectionStatus = '连接中...';
this.addLog(`正在连接到 ${this.brokerHost}:${this.brokerPort}`);
this.mqttClient.connect(
this.brokerHost,
parseInt(this.brokerPort),
() => {
this.connectionStatus = '已连接';
this.addLog('MQTT连接成功');
},
(error: string) => {
this.connectionStatus = '连接失败';
this.addLog(error);
}
);
}
// 断开连接
disconnectFromBroker() {
if (this.mqttClient) {
this.mqttClient.disconnect();
this.connectionStatus = '已断开';
this.addLog('MQTT连接已断开');
this.subscribedTopics = [];
}
}
// 订阅主题
subscribeToTopic() {
if (!this.mqttClient || !this.mqttClient.getConnected()) {
this.addLog('请先建立MQTT连接');
return;
}
if (this.subscribeTopic.trim() === '') {
this.addLog('订阅主题不能为空');
return;
}
if (this.subscribedTopics.includes(this.subscribeTopic)) {
this.addLog(`已订阅主题: ${this.subscribeTopic}`);
return;
}
this.mqttClient.subscribe(this.subscribeTopic, (topic: string, message: string) => {
this.addReceivedMessage(topic, message);
this.addLog(`收到消息: ${topic} - ${message}`);
});
this.subscribedTopics.push(this.subscribeTopic);
this.addLog(`已订阅主题: ${this.subscribeTopic}`);
}
// 取消订阅
unsubscribeFromTopic(topic: string) {
if (this.mqttClient) {
this.mqttClient.unsubscribe(topic);
this.subscribedTopics = this.subscribedTopics.filter(t => t !== topic);
this.addLog(`已取消订阅: ${topic}`);
}
}
// 发布消息
publishMessageToTopic() {
if (!this.mqttClient || !this.mqttClient.getConnected()) {
this.addLog('请先建立MQTT连接');
return;
}
if (this.publishTopic.trim() === '') {
this.addLog('发布主题不能为空');
return;
}
if (this.publishMessageContent.trim() === '') {
this.addLog('发布消息不能为空');
return;
}
this.mqttClient.publish(this.publishTopic, this.publishMessageContent);
this.addLog(`已发布消息到 ${this.publishTopic}: ${this.publishMessageContent}`);
}
// 生成随机客户端ID
generateClientId() {
this.clientId = 'harmonyos_client_' + Date.now().toString() + '_' + Math.floor(Math.random() * 1000).toString();
this.addLog(`生成新的客户端ID: ${this.clientId}`);
}
// 组件销毁时清理资源
aboutToDisappear() {
if (this.mqttClient) {
this.mqttClient.disconnect();
}
}
build() {
Scroll() {
Column({ space: 20 }) {
// 标题区域
Column({ space: 15 }) {
Text(this.message)
.fontSize(30)
.fontWeight(FontWeight.Bold)
.fontColor('#007DFF')
.margin({ top: 30 })
// 连接状态显示
Row({ space: 20 }) {
Column({ space: 5 }) {
Text('连接状态:')
.fontSize(16)
.fontColor('#333333')
Text(this.connectionStatus)
.fontSize(18)
.fontColor(this.connectionStatus === '已连接' ? '#4CAF50' :
this.connectionStatus === '连接中...' ? '#FF9800' : '#F44336')
.fontWeight(FontWeight.Bold)
}
Button(this.connectionStatus === '已连接' ? '断开连接' : '连接代理')
.width(120)
.height(40)
.fontSize(14)
.backgroundColor(this.connectionStatus === '已连接' ? '#F44336' : '#4CAF50')
.onClick(() => {
if (this.connectionStatus === '已连接') {
this.disconnectFromBroker();
} else {
this.connectToBroker();
}
})
}
.width('100%')
.justifyContent(FlexAlign.SpaceAround)
.padding(10)
.backgroundColor('#F5F5F5')
.borderRadius(8)
}
// MQTT代理配置区域
Column({ space: 10 }) {
Text('MQTT代理配置')
.fontSize(18)
.fontWeight(FontWeight.Medium)
.fontColor('#333333')
Column({ space: 8 }) {
Row({ space: 10 }) {
Text('代理地址:')
.fontSize(14)
.fontColor('#666666')
.width('25%')
TextInput({ text: this.brokerHost })
.width('75%')
.height(40)
.fontSize(14)
.backgroundColor('#FFFFFF')
.border({ width: 1, color: '#E0E0E0' })
.borderRadius(4)
.onChange((value: string) => {
this.brokerHost = value;
})
}
Row({ space: 10 }) {
Text('端口号:')
.fontSize(14)
.fontColor('#666666')
.width('25%')
TextInput({ text: this.brokerPort })
.width('75%')
.height(40)
.fontSize(14)
.backgroundColor('#FFFFFF')
.border({ width: 1, color: '#E0E0E0' })
.borderRadius(4)
.onChange((value: string) => {
this.brokerPort = value;
})
}
Row({ space: 10 }) {
Text('客户端ID:')
.fontSize(14)
.fontColor('#666666')
.width('25%')
TextInput({ text: this.clientId })
.width('60%')
.height(40)
.fontSize(14)
.backgroundColor('#FFFFFF')
.border({ width: 1, color: '#E0E0E0' })
.borderRadius(4)
.onChange((value: string) => {
this.clientId = value;
})
Button('生成')
.width(60)
.height(40)
.fontSize(12)
.backgroundColor('#9C27B0')
.onClick(() => {
this.generateClientId();
})
}
}
.width('100%')
.padding(15)
.backgroundColor('#F8F9FA')
.borderRadius(10)
}
.width('95%')
// 订阅主题区域
Column({ space: 10 }) {
Text('主题订阅')
.fontSize(18)
.fontWeight(FontWeight.Medium)
.fontColor('#333333')
Column({ space: 8 }) {
Row({ space: 10 }) {
TextInput({ text: this.subscribeTopic, placeholder: '输入订阅主题' })
.width('70%')
.height(40)
.fontSize(14)
.backgroundColor('#FFFFFF')
.border({ width: 1, color: '#E0E0E0' })
.borderRadius(4)
.onChange((value: string) => {
this.subscribeTopic = value;
})
Button('订阅')
.width('25%')
.height(40)
.fontSize(14)
.backgroundColor('#2196F3')
.onClick(() => {
this.subscribeToTopic();
})
}
// 已订阅主题列表
if (this.subscribedTopics.length > 0) {
Text('已订阅主题:')
.fontSize(14)
.fontColor('#666666')
.alignSelf(ItemAlign.Start)
Column({ space: 5 }) {
ForEach(this.subscribedTopics, (topic: string, index: number) => {
Row({ space: 10 }) {
Text(topic)
.fontSize(12)
.fontColor('#4CAF50')
.textAlign(TextAlign.Start)
.width('80%')
Button('取消')
.width(50)
.height(25)
.fontSize(10)
.backgroundColor('#F44336')
.onClick(() => {
this.unsubscribeFromTopic(topic);
})
}
.width('100%')
.padding(5)
.backgroundColor('#F9F9F9')
.borderRadius(4)
}, (topic: string) => topic)
}
.width('100%')
}
}
.width('100%')
.padding(15)
.backgroundColor('#F8F9FA')
.borderRadius(10)
}
.width('95%')
// 发布消息区域
Column({ space: 10 }) {
Text('消息发布')
.fontSize(18)
.fontWeight(FontWeight.Medium)
.fontColor('#333333')
Column({ space: 8 }) {
Row({ space: 10 }) {
Text('主题:')
.fontSize(14)
.fontColor('#666666')
.width('20%')
TextInput({ text: this.publishTopic })
.width('80%')
.height(40)
.fontSize(14)
.backgroundColor('#FFFFFF')
.border({ width: 1, color: '#E0E0E0' })
.borderRadius(4)
.onChange((value: string) => {
this.publishTopic = value;
})
}
Text('消息内容:')
.fontSize(14)
.fontColor('#666666')
.alignSelf(ItemAlign.Start)
TextInput({ text: this.publishMessageContent, placeholder: '输入要发布的消息' })
.width('100%')
.height(60)
.fontSize(14)
.backgroundColor('#FFFFFF')
.border({ width: 1, color: '#E0E0E0' })
.borderRadius(4)
.onChange((value: string) => {
this.publishMessageContent = value;
})
Button('发布消息')
.width('100%')
.height(45)
.fontSize(16)
.backgroundColor('#FF9800')
.fontColor('#FFFFFF')
.onClick(() => {
this.publishMessageToTopic();
})
}
.width('100%')
.padding(15)
.backgroundColor('#F8F9FA')
.borderRadius(10)
}
.width('95%')
// MQTT协议说明区域
Column({ space: 10 }) {
Text('MQTT协议基础说明')
.fontSize(18)
.fontWeight(FontWeight.Medium)
.fontColor('#333333')
Column({ space: 8 }) {
Text('• MQTT是轻量级的发布/订阅消息传输协议')
.fontSize(12)
.fontColor('#666666')
.alignSelf(ItemAlign.Start)
Text('• 基于TCP/IP协议,适用于物联网和移动应用')
.fontSize(12)
.fontColor('#666666')
.alignSelf(ItemAlign.Start)
Text('• 支持三种服务质量等级(QoS): 0,1,2')
.fontSize(12)
.fontColor('#666666')
.alignSelf(ItemAlign.Start)
Text('• 支持遗言消息和会话保持')
.fontSize(12)
.fontColor('#666666')
.alignSelf(ItemAlign.Start)
}
.width('100%')
.padding(15)
.backgroundColor('#E3F2FD')
.borderRadius(10)
}
.width('95%')
// 接收消息区域
Column({ space: 10 }) {
Text('接收到的消息')
.fontSize(18)
.fontWeight(FontWeight.Medium)
.fontColor('#333333')
Column({ space: 5 }) {
if (this.receivedMessages.length === 0) {
Text('暂无接收到的消息')
.fontSize(14)
.fontColor('#999999')
.fontStyle(FontStyle.Italic)
.padding(20)
} else {
ForEach(this.receivedMessages, (item: string, index: number) => {
Text(item)
.fontSize(12)
.fontColor('#4CAF50')
.textAlign(TextAlign.Start)
.width('100%')
.padding(8)
.backgroundColor(index % 2 === 0 ? '#F9F9F9' : '#FFFFFF')
.borderRadius(4)
}, (item: string) => item)
}
}
.width('100%')
.height(150)
.padding(10)
.backgroundColor('#FFFFFF')
.border({ width: 1, color: '#E0E0E0' })
.borderRadius(8)
}
.width('95%')
// 通信日志区域
Column({ space: 10 }) {
Text('通信日志')
.fontSize(18)
.fontWeight(FontWeight.Medium)
.fontColor('#333333')
Column({ space: 5 }) {
if (this.logMessages.length === 0) {
Text('暂无通信日志')
.fontSize(14)
.fontColor('#999999')
.fontStyle(FontStyle.Italic)
.padding(20)
} else {
ForEach(this.logMessages, (item: string, index: number) => {
Text(item)
.fontSize(12)
.fontColor('#666666')
.textAlign(TextAlign.Start)
.width('100%')
.padding(8)
.backgroundColor(index % 2 === 0 ? '#F9F9F9' : '#FFFFFF')
.borderRadius(4)
}, (item: string) => item)
}
}
.width('100%')
.height(200)
.padding(10)
.backgroundColor('#FFFFFF')
.border({ width: 1, color: '#E0E0E0' })
.borderRadius(8)
Row({ space: 10 }) {
Button('清空日志')
.width('45%')
.height(35)
.fontSize(12)
.backgroundColor('#FF9800')
.onClick(() => {
this.logMessages = [];
this.receivedMessages = [];
this.addLog('日志已清空');
})
Button('测试连接')
.width('45%')
.height(35)
.fontSize(12)
.backgroundColor('#4CAF50')
.onClick(() => {
this.addLog('开始测试MQTT连接...');
this.connectToBroker();
})
}
.width('100%')
.justifyContent(FlexAlign.SpaceAround)
}
.width('95%')
.margin({ bottom: 30 })
}
.width('100%')
.padding(15)
}
.scrollable(ScrollDirection.Vertical)
.scrollBar(BarState.On)
.scrollBarColor('#007DFF')
.scrollBarWidth(10)
.edgeEffect(EdgeEffect.Spring)
.width('100%')
.height('100%')
.backgroundColor('#FFFFFF')
}
}
更多推荐



所有评论(0)