修复聊天闪退bug,添加对接聊天服务器
This commit is contained in:
parent
3f5dd9ddaf
commit
a676fe8cd0
@ -7,6 +7,7 @@ import logManager, { LogCategory, LogEventType } from './logtext';
|
||||
import settingsService from './SettingsService';
|
||||
import { DatabaseService } from './DatabaseService';
|
||||
import http from '@ohos.net.http';
|
||||
import { JSON } from '@kit.ArkTS';
|
||||
|
||||
// 课堂会话状态
|
||||
export enum ClassSessionStatus {
|
||||
@ -107,6 +108,22 @@ export class MessageModel {
|
||||
this.content = content;
|
||||
this.timestamp = new Date();
|
||||
}
|
||||
|
||||
static fromJSON(jsons: string): MessageModel {
|
||||
let json = JSON.parse(jsons) as Map<string,object>
|
||||
const msg = new MessageModel(
|
||||
json["id"] as string,
|
||||
json["senderId"] as string,
|
||||
json["senderName"] as SenderRole,
|
||||
json["content"] as string
|
||||
);
|
||||
msg.timestamp = new Date();
|
||||
return msg;
|
||||
}
|
||||
|
||||
public useTime(){
|
||||
this.timestamp = new Date()
|
||||
}
|
||||
}
|
||||
|
||||
// 题目模型
|
||||
@ -847,7 +864,7 @@ export class ClassRoomService {
|
||||
} else {
|
||||
// Enhanced error logging with response details
|
||||
hilog.error(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `消息发送失败: ${response.message || '未知错误'}`);
|
||||
logManager.error(LogCategory.CLASS, `Send message failed: ${response.message || 'Unknown error'}, Response data: ${JSON.stringify(response.data || {})}`);
|
||||
logManager.error(LogCategory.CLASS, `Send message failed: ${response.message || 'Unknown error'}, Response data: ${JSON.stringify(response.data)}`);
|
||||
hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `========= 消息发送失败 =========`);
|
||||
return false;
|
||||
}
|
||||
|
@ -16,11 +16,11 @@ export class UserModel {
|
||||
category: string = '';
|
||||
|
||||
constructor(account: string = '',
|
||||
nickname: string = '',
|
||||
email: string = '',
|
||||
phone: string = '',
|
||||
photo: string = '',
|
||||
category: string = '') {
|
||||
nickname: string = '',
|
||||
email: string = '',
|
||||
phone: string = '',
|
||||
photo: string = '',
|
||||
category: string = '') {
|
||||
this.account = account;
|
||||
this.nickname = nickname;
|
||||
this.email = email;
|
||||
@ -51,13 +51,16 @@ export interface UserInfo {
|
||||
export interface ApiConfig {
|
||||
baseUrl: string;
|
||||
timeout: number;
|
||||
websocketDomain: string
|
||||
}
|
||||
|
||||
// 定义API服务配置
|
||||
const API_CONFIG: ApiConfig = {
|
||||
// 修改为用户实际使用的服务器地址
|
||||
baseUrl: 'http://139.155.155.67:2342/api',
|
||||
timeout: 10000 // 10秒超时
|
||||
timeout: 10000, // 10秒超时
|
||||
websocketDomain: "139.155.155.67:4233",
|
||||
// websocketDomain: "198.18.0.1:8080",
|
||||
};
|
||||
|
||||
// 修正JSON响应类型处理
|
||||
@ -80,7 +83,6 @@ export class DatabaseService {
|
||||
private userCache: Map<string, UserModel> = new Map();
|
||||
// 缓存验证结果
|
||||
private authCache: Map<string, boolean> = new Map();
|
||||
|
||||
// Callbacks for user data changes
|
||||
private userDataChangeCallbacks: (() => void)[] = [];
|
||||
|
||||
@ -96,6 +98,10 @@ export class DatabaseService {
|
||||
return DatabaseService.instance;
|
||||
}
|
||||
|
||||
public static getApiConfig():ApiConfig{
|
||||
return API_CONFIG;
|
||||
}
|
||||
|
||||
// 创建HTTP请求客户端
|
||||
private createHttpClient(): http.HttpRequest {
|
||||
let httpRequest = http.createHttp();
|
||||
@ -179,10 +185,10 @@ export class DatabaseService {
|
||||
hilog.error(0, 'ClassMG', `Error validating user: ${error instanceof Error ? error.message : String(error)}`);
|
||||
|
||||
// 临时降级到模拟验证 - 仅用于开发/测试
|
||||
/* if (account === '2' || account === '9222' || account === '0') {
|
||||
return password === '1';
|
||||
}
|
||||
*/
|
||||
/* if (account === '2' || account === '9222' || account === '0') {
|
||||
return password === '1';
|
||||
}
|
||||
*/
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@ -214,9 +220,15 @@ export class DatabaseService {
|
||||
}
|
||||
|
||||
// 默认值 - 仅用于开发/测试
|
||||
if (account === '2') return '张三';
|
||||
if (account === '9222') return '李华';
|
||||
if (account === '0') return '教师demo';
|
||||
if (account === '2') {
|
||||
return '张三';
|
||||
}
|
||||
if (account === '9222') {
|
||||
return '李华';
|
||||
}
|
||||
if (account === '0') {
|
||||
return '教师demo';
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
@ -279,13 +291,13 @@ export class DatabaseService {
|
||||
hilog.error(0, 'ClassMG', `Error getting user: ${error instanceof Error ? error.message : String(error)}`);
|
||||
|
||||
// 降级到模拟数据 - 仅用于开发/测试
|
||||
/* if (account === '2') {
|
||||
return new UserModel('2', '张三', 'student@qq.com', '17267383831', '', 'student');
|
||||
} else if (account === '9222') {
|
||||
return new UserModel('9222', '李华', 'student123@qq.com', '12345678901', '', 'student');
|
||||
} else if (account === '0') {
|
||||
return new UserModel('0', '教师demo', 'teach@qq.com', '', '', 'teacher');
|
||||
}*/
|
||||
/* if (account === '2') {
|
||||
return new UserModel('2', '张三', 'student@qq.com', '17267383831', '', 'student');
|
||||
} else if (account === '9222') {
|
||||
return new UserModel('9222', '李华', 'student123@qq.com', '12345678901', '', 'student');
|
||||
} else if (account === '0') {
|
||||
return new UserModel('0', '教师demo', 'teach@qq.com', '', '', 'teacher');
|
||||
}*/
|
||||
|
||||
return null;
|
||||
}
|
||||
|
@ -20,6 +20,9 @@ import {
|
||||
import logManager, { LogCategory, LogEventType } from '../common/logtext';
|
||||
import http from '@ohos.net.http';
|
||||
import hilog from '@ohos.hilog';
|
||||
import WebSocketMessage from '../util/WebsocketMessage';
|
||||
import { BusinessError } from '@kit.BasicServicesKit';
|
||||
import { DatabaseService } from '../common/DatabaseService';
|
||||
|
||||
// 添加hilog和tianChannel常量
|
||||
const TIAN_CHANNEL_DOMAIN_ID = 0x00201; // 自定义域ID
|
||||
@ -133,8 +136,11 @@ struct ClassLivePage {
|
||||
};
|
||||
// 用于服务实例
|
||||
private classRoomService: ClassRoomService = ClassRoomService.getInstance();
|
||||
wsClient: WebSocketMessage = new WebSocketMessage(DatabaseService.getApiConfig().websocketDomain, "111111")
|
||||
|
||||
aboutToAppear() {
|
||||
this.wsClient.connect();
|
||||
|
||||
// 注册语言变化的回调
|
||||
settingsService.registerLanguageChangeCallback(() => {
|
||||
this.texts = settingsService.getTextResources();
|
||||
@ -170,6 +176,19 @@ struct ClassLivePage {
|
||||
this.registerEventListeners();
|
||||
|
||||
logManager.info(LogCategory.CLASS, LogEventType.PAGE_APPEAR, 'ClassLivePage');
|
||||
|
||||
|
||||
this.wsClient.setOnMessage((data) => {
|
||||
hilog.debug(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, "收到消息: " + data.toString());
|
||||
try {
|
||||
let j: MessageModel = MessageModel.fromJSON(data.toString()) //JSON.parse(data.toString()) as MessageModel
|
||||
this.messages.push(j)
|
||||
hilog.debug(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, "渲染: " + j);
|
||||
// this.messages.push(data.toString())
|
||||
} catch (e) {
|
||||
hilog.debug(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, "消息解析失败: " + e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 注册事件监听
|
||||
@ -177,6 +196,7 @@ struct ClassLivePage {
|
||||
// 接收新消息
|
||||
this.messageCallback = (data: EventData) => {
|
||||
const message = data as MessageModel;
|
||||
message.useTime()
|
||||
if (message && message.id) {
|
||||
// 检查消息是否已经存在(防止重复)
|
||||
const existingMessage = this.messages.find(m => m.id === message.id);
|
||||
|
81
entry/src/main/ets/util/WebsocketMessage.ets
Normal file
81
entry/src/main/ets/util/WebsocketMessage.ets
Normal file
@ -0,0 +1,81 @@
|
||||
import { webSocket } from "@kit.NetworkKit";
|
||||
import { BusinessError } from "@kit.BasicServicesKit";
|
||||
import { hilog } from "@kit.PerformanceAnalysisKit";
|
||||
|
||||
const DOMAIN: number = 0
|
||||
const TAG: string = "websocket message"
|
||||
|
||||
export default class WebSocketMessage {
|
||||
private ws = webSocket.createWebSocket();
|
||||
private url: string;
|
||||
private room: string;
|
||||
private onMessageCallback: (data: string | ArrayBuffer) => void = () => {
|
||||
};
|
||||
|
||||
constructor(url: string, room: string) {
|
||||
this.url = url;
|
||||
this.room = room;
|
||||
}
|
||||
|
||||
public connect(): void {
|
||||
this.ws.on('open', (err: BusinessError, value: Object) => {
|
||||
hilog.debug(DOMAIN, TAG, "on open, status: " + JSON.stringify(value));
|
||||
this.ws.send("Hello, server!", (err: BusinessError, success: boolean) => {
|
||||
if (!err) {
|
||||
hilog.debug(DOMAIN, TAG, "Message sent successfully");
|
||||
} else {
|
||||
hilog.debug(DOMAIN, TAG, "Failed to send the message. Err: " + JSON.stringify(err));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
this.ws.on('message', (err: BusinessError, value: string | ArrayBuffer) => {
|
||||
hilog.debug(DOMAIN, TAG, "on message, message: " + value);
|
||||
if (value === 'bye') {
|
||||
this.close();
|
||||
}
|
||||
this.onMessageCallback(value);
|
||||
});
|
||||
|
||||
this.ws.on('close', (err: BusinessError, value: webSocket.CloseResult) => {
|
||||
hilog.debug(DOMAIN, TAG, "on close, code: " + value.code + ", reason: " + value.reason);
|
||||
});
|
||||
|
||||
this.ws.on('error', (err: BusinessError) => {
|
||||
hilog.debug(DOMAIN, TAG, "on error, error: " + JSON.stringify(err));
|
||||
});
|
||||
|
||||
const wsUrl = `ws://${this.url}/ws/room?room=${this.room}`;
|
||||
this.ws.connect(wsUrl, (err: BusinessError, connected: boolean) => {
|
||||
if (!err) {
|
||||
hilog.debug(DOMAIN, TAG, "Connected successfully");
|
||||
} else {
|
||||
hilog.debug(DOMAIN, TAG, "Connection failed. Err: " + JSON.stringify(err));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public setOnMessage(callback: (data: string | ArrayBuffer) => void): void {
|
||||
this.onMessageCallback = callback;
|
||||
}
|
||||
|
||||
public sendMessage(message: string): void {
|
||||
this.ws.send(message, (err: BusinessError, success: boolean) => {
|
||||
if (!err) {
|
||||
hilog.debug(DOMAIN, TAG, "Message sent: " + message);
|
||||
} else {
|
||||
hilog.debug(DOMAIN, TAG, "Send failed: " + JSON.stringify(err));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public close(): void {
|
||||
this.ws.close((err: BusinessError, success: boolean) => {
|
||||
if (!err) {
|
||||
hilog.debug(DOMAIN, TAG, "Connection closed successfully");
|
||||
} else {
|
||||
hilog.debug(DOMAIN, TAG, "Failed to close the connection. Err: " + JSON.stringify(err));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user