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