From 778958042d620e4761adfe95961bac141869c5d7 Mon Sep 17 00:00:00 2001 From: XuShanQiXun <3401460572@qq.com> Date: Fri, 6 Jun 2025 22:50:21 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=88=86=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- chatclient/Data/chatapi.cs | 7 +++++ chatclient/MainWindow.xaml.cs | 43 +++++++++++++++++++++-------- chatclient/{ => resource}/user.png | Bin 3 files changed, 38 insertions(+), 12 deletions(-) rename chatclient/{ => resource}/user.png (100%) diff --git a/chatclient/Data/chatapi.cs b/chatclient/Data/chatapi.cs index 4d36103..2e0c7d2 100644 --- a/chatclient/Data/chatapi.cs +++ b/chatclient/Data/chatapi.cs @@ -32,4 +32,11 @@ { public string? type { get; set; } } + internal class ChatData + { + public string? user { get; set; } = "Unnamed"; + public string? message { get; set; } = null; + public string? image { get; set; } = null; + public DateTime timestamp { get; set; } = DateTime.Now; + } } diff --git a/chatclient/MainWindow.xaml.cs b/chatclient/MainWindow.xaml.cs index a914167..5a91a06 100644 --- a/chatclient/MainWindow.xaml.cs +++ b/chatclient/MainWindow.xaml.cs @@ -112,7 +112,6 @@ namespace chatclient Client?.Close(); } } - static void response(string msg) { log.Info($"收到服务器消息: {msg}"); @@ -152,28 +151,48 @@ namespace chatclient }); } } - else if(Type.type == "login_0" && LoginResponse != null) - { + else if (Type.type == "login_0" && LoginResponse != null) + { log.Warn($"登录失败: {LoginResponse.message}\nMsg:{msg}"); Application.Current.Dispatcher.Invoke(() => { var loginWindow = Application.Current.Windows.OfType().FirstOrDefault(); if (loginWindow != null) { - loginWindow.LoginMsg = LoginResponse.message; + loginWindow.LoginMsg = "用户名或密码错误"; } }); } + else if (Type.type == "chat") + { + var chat = JsonSerializer.Deserialize(msg); + if (chat != null) + { + // 处理聊天消息 + var chatmessage = new ChatMessage + { + Sender = chat.user ?? "未知用户", + Type = MessageType.Text, + Image = new BitmapImage(new Uri(chat.image ?? "pack://application:,,,/user.png", UriKind.Absolute)), + Content = chat.message ?? "无内容", + Timestamp = chat.timestamp, + Alignment = HorizontalAlignment.Left, + SenderColor = new SolidColorBrush(Colors.Black) + }; + Application.Current.Dispatcher.Invoke(() => + { + var mainWindow = Application.Current.Windows.OfType().FirstOrDefault(); + mainWindow?.Messages.Add(chatmessage); + }); + } + else + { + log.Error("反序列化聊天数据时返回了 null"); + } + } else { - Application.Current.Dispatcher.Invoke(() => - { - var loginWindow = Application.Current.Windows.OfType().FirstOrDefault(); - if (loginWindow != null) - { - loginWindow.LoginMsg = LoginResponse != null ? LoginResponse.message : "服务器返回错误"; - } - }); + log.Error($"未知的消息类型: {Type.type},请检查服务器响应格式"); } } } diff --git a/chatclient/user.png b/chatclient/resource/user.png similarity index 100% rename from chatclient/user.png rename to chatclient/resource/user.png