修复聊天闪退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 settingsService from './SettingsService';
|
||||||
import { DatabaseService } from './DatabaseService';
|
import { DatabaseService } from './DatabaseService';
|
||||||
import http from '@ohos.net.http';
|
import http from '@ohos.net.http';
|
||||||
|
import { JSON } from '@kit.ArkTS';
|
||||||
|
|
||||||
// 课堂会话状态
|
// 课堂会话状态
|
||||||
export enum ClassSessionStatus {
|
export enum ClassSessionStatus {
|
||||||
@ -107,6 +108,22 @@ export class MessageModel {
|
|||||||
this.content = content;
|
this.content = content;
|
||||||
this.timestamp = new Date();
|
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 {
|
} else {
|
||||||
// Enhanced error logging with response details
|
// Enhanced error logging with response details
|
||||||
hilog.error(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `消息发送失败: ${response.message || '未知错误'}`);
|
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, `========= 消息发送失败 =========`);
|
hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `========= 消息发送失败 =========`);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
@ -51,13 +51,16 @@ export interface UserInfo {
|
|||||||
export interface ApiConfig {
|
export interface ApiConfig {
|
||||||
baseUrl: string;
|
baseUrl: string;
|
||||||
timeout: number;
|
timeout: number;
|
||||||
|
websocketDomain: string
|
||||||
}
|
}
|
||||||
|
|
||||||
// 定义API服务配置
|
// 定义API服务配置
|
||||||
const API_CONFIG: ApiConfig = {
|
const API_CONFIG: ApiConfig = {
|
||||||
// 修改为用户实际使用的服务器地址
|
// 修改为用户实际使用的服务器地址
|
||||||
baseUrl: 'http://139.155.155.67:2342/api',
|
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响应类型处理
|
// 修正JSON响应类型处理
|
||||||
@ -80,7 +83,6 @@ export class DatabaseService {
|
|||||||
private userCache: Map<string, UserModel> = new Map();
|
private userCache: Map<string, UserModel> = new Map();
|
||||||
// 缓存验证结果
|
// 缓存验证结果
|
||||||
private authCache: Map<string, boolean> = new Map();
|
private authCache: Map<string, boolean> = new Map();
|
||||||
|
|
||||||
// Callbacks for user data changes
|
// Callbacks for user data changes
|
||||||
private userDataChangeCallbacks: (() => void)[] = [];
|
private userDataChangeCallbacks: (() => void)[] = [];
|
||||||
|
|
||||||
@ -96,6 +98,10 @@ export class DatabaseService {
|
|||||||
return DatabaseService.instance;
|
return DatabaseService.instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static getApiConfig():ApiConfig{
|
||||||
|
return API_CONFIG;
|
||||||
|
}
|
||||||
|
|
||||||
// 创建HTTP请求客户端
|
// 创建HTTP请求客户端
|
||||||
private createHttpClient(): http.HttpRequest {
|
private createHttpClient(): http.HttpRequest {
|
||||||
let httpRequest = http.createHttp();
|
let httpRequest = http.createHttp();
|
||||||
@ -214,9 +220,15 @@ export class DatabaseService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 默认值 - 仅用于开发/测试
|
// 默认值 - 仅用于开发/测试
|
||||||
if (account === '2') return '张三';
|
if (account === '2') {
|
||||||
if (account === '9222') return '李华';
|
return '张三';
|
||||||
if (account === '0') return '教师demo';
|
}
|
||||||
|
if (account === '9222') {
|
||||||
|
return '李华';
|
||||||
|
}
|
||||||
|
if (account === '0') {
|
||||||
|
return '教师demo';
|
||||||
|
}
|
||||||
|
|
||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
|
@ -20,6 +20,9 @@ import {
|
|||||||
import logManager, { LogCategory, LogEventType } from '../common/logtext';
|
import logManager, { LogCategory, LogEventType } from '../common/logtext';
|
||||||
import http from '@ohos.net.http';
|
import http from '@ohos.net.http';
|
||||||
import hilog from '@ohos.hilog';
|
import hilog from '@ohos.hilog';
|
||||||
|
import WebSocketMessage from '../util/WebsocketMessage';
|
||||||
|
import { BusinessError } from '@kit.BasicServicesKit';
|
||||||
|
import { DatabaseService } from '../common/DatabaseService';
|
||||||
|
|
||||||
// 添加hilog和tianChannel常量
|
// 添加hilog和tianChannel常量
|
||||||
const TIAN_CHANNEL_DOMAIN_ID = 0x00201; // 自定义域ID
|
const TIAN_CHANNEL_DOMAIN_ID = 0x00201; // 自定义域ID
|
||||||
@ -133,8 +136,11 @@ struct ClassLivePage {
|
|||||||
};
|
};
|
||||||
// 用于服务实例
|
// 用于服务实例
|
||||||
private classRoomService: ClassRoomService = ClassRoomService.getInstance();
|
private classRoomService: ClassRoomService = ClassRoomService.getInstance();
|
||||||
|
wsClient: WebSocketMessage = new WebSocketMessage(DatabaseService.getApiConfig().websocketDomain, "111111")
|
||||||
|
|
||||||
aboutToAppear() {
|
aboutToAppear() {
|
||||||
|
this.wsClient.connect();
|
||||||
|
|
||||||
// 注册语言变化的回调
|
// 注册语言变化的回调
|
||||||
settingsService.registerLanguageChangeCallback(() => {
|
settingsService.registerLanguageChangeCallback(() => {
|
||||||
this.texts = settingsService.getTextResources();
|
this.texts = settingsService.getTextResources();
|
||||||
@ -170,6 +176,19 @@ struct ClassLivePage {
|
|||||||
this.registerEventListeners();
|
this.registerEventListeners();
|
||||||
|
|
||||||
logManager.info(LogCategory.CLASS, LogEventType.PAGE_APPEAR, 'ClassLivePage');
|
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) => {
|
this.messageCallback = (data: EventData) => {
|
||||||
const message = data as MessageModel;
|
const message = data as MessageModel;
|
||||||
|
message.useTime()
|
||||||
if (message && message.id) {
|
if (message && message.id) {
|
||||||
// 检查消息是否已经存在(防止重复)
|
// 检查消息是否已经存在(防止重复)
|
||||||
const existingMessage = this.messages.find(m => m.id === 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