diff --git a/chatclient/Data/chatapi.cs b/chatclient/Data/chatapi.cs index 720508d..a0ff082 100644 --- a/chatclient/Data/chatapi.cs +++ b/chatclient/Data/chatapi.cs @@ -13,11 +13,13 @@ namespace chatclient.Data public string? type { get; set; } = null; public string? username { get; set; } = null; public string? password { get; set; } = null; + public string? token { get; set; } = null; } internal class LoginResultData { - public string? status { get; set; } = null; - public string? message { get; set; } = null; + public string? status { get; set; } + public string? message { get; set; } + public string? token { get; set; } } internal class SignData { @@ -37,6 +39,7 @@ namespace chatclient.Data internal class ChatRegisterData { public string? user { get; set; } = "Unnamed"; + public string? status { get; set; } = null; public string? message { get; set; } = null; public string? image { get; set; } = null; public DateTime timestamp { get; set; } = DateTime.Now; diff --git a/chatclient/LoginWindow.xaml.cs b/chatclient/LoginWindow.xaml.cs index 63c32d5..7d2d871 100644 --- a/chatclient/LoginWindow.xaml.cs +++ b/chatclient/LoginWindow.xaml.cs @@ -9,6 +9,8 @@ using log4net; using System.Net.Http; using Microsoft.Win32; using chatclient.Data; +using System.Net; +using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel; namespace chatclient @@ -64,7 +66,7 @@ namespace chatclient Update("SaveAccount"); } } - private void Login_Click(object sender, RoutedEventArgs e) + private async void Login_Click(object sender, RoutedEventArgs e) { if (UserName == "") { @@ -76,7 +78,7 @@ namespace chatclient } else { - Login(false,UserName,UserPassword); + await Login(false, UserName, UserPassword); } } private void Sign_Click(object sender, RoutedEventArgs e) @@ -132,18 +134,8 @@ namespace chatclient var signresponse = JsonSerializer.Deserialize(responseBody); if (signresponse!.success) { - // 显示 MainWindow - Application.Current.Dispatcher.Invoke(() => - { - var mainWindow = Application.Current.Windows - .OfType() - .FirstOrDefault(); - }); log.Info($"注册成功: {signresponse.message}"); - Application.Current.Dispatcher.Invoke(() => - { - Login(true, Username, Userpassword); - }); + await Login(true, Username, Userpassword); } else { @@ -164,96 +156,54 @@ namespace chatclient log.Info("注册请求已完成"); } } - //var loginWindow = Application.Current.Windows.OfType().FirstOrDefault(); - //loginWindow?.Close(); - public static void Login(bool Sign,string Username, string Userpassword) + public static async Task Login(bool Sign, string Username, string Userpassword) { - if (Sign) + // 公共的登录数据准备 + var LoginData = new { - var LoginData = new - { - type = "login", - username = Username, - password = Userpassword - }; - string LoginJsonData = JsonSerializer.Serialize(LoginData); - byte[] dataBytes = Encoding.UTF8.GetBytes(LoginJsonData); - log.Info($"向服务器发送登录请求(UserName:{UserName})"); - if (MainWindow.Client is not null) - { - if (MainWindow.Client.Connected) - { - MainWindow.Client.Send(dataBytes); - } - else - { - try - { - log.Info("未连接服务器,尝试连接"); - MainWindow.Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - MainWindow.Client.Connect(System.Net.IPAddress.Parse(Server.ServerIP), Server.ServerPort); - } - catch (Exception ex) - { - log.Error(ex); - MainWindow.Client.Close(); - } - finally - { - Application.Current.Dispatcher.Invoke(() => - { - var loginWindow = Application.Current.Windows.OfType().FirstOrDefault(); - loginWindow!.SignMsg = "在完成注册后与服务器断开连接\n请尝试在登录窗口重新登录"; - }); - //"服务器连接失败"; - } - } - } - } - else + type = "login", + username = Username, + password = Userpassword + }; + string LoginJsonData = JsonSerializer.Serialize(LoginData); + byte[] dataBytes = Encoding.UTF8.GetBytes(LoginJsonData); + log.Info($"向服务器发送登录请求(UserName:{Username})"); + // 检查Socket是否可用 + if (MainWindow.Client?.Connected == true) { - var LoginData = new - { - type = "login", - username = Username, - password = Userpassword - }; - string LoginJsonData = JsonSerializer.Serialize(LoginData); - byte[] dataBytes = Encoding.UTF8.GetBytes(LoginJsonData); - log.Info($"向服务器发送登录请求(UserName:{UserName})"); - if (MainWindow.Client is not null) - { - if (MainWindow.Client.Connected) - { - MainWindow.Client.Send(dataBytes); - } - else - { - try - { - log.Info("未连接服务器,尝试连接"); - MainWindow.Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - MainWindow.Client.Connect(System.Net.IPAddress.Parse(Server.ServerIP), Server.ServerPort); - } - catch (Exception ex) - { - log.Error(ex); - MainWindow.Client.Close(); - } - finally - { - Application.Current.Dispatcher.Invoke(() => - { - var loginWindow = Application.Current.Windows.OfType().FirstOrDefault(); - if (loginWindow != null) - { - loginWindow.LoginMsg = "服务器连接失败"; - } - }); - } - } - } + MainWindow.Client.Send(dataBytes); + return; } + log.Info("未连接服务器,尝试异步连接"); + // 异步连接操作 + await Task.Run(() => + { + try + { + MainWindow.Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + MainWindow.Client?.Connect(IPAddress.Parse(Server.ServerIP), Server.ServerPort); + MainWindow.StartReceive(); + MainWindow.Client?.Send(dataBytes); + } + catch (Exception ex) + { + log.Error($"连接失败: {ex.Message}"); + MainWindow.Client?.Close(); + // 根据Sign类型更新UI + string errorMsg = Sign ? + "在完成注册后与服务器断开连接\n请尝试在登录窗口重新登录" : + "服务器连接失败"; + Application.Current.Dispatcher.Invoke(() => + { + var loginWindow = Application.Current.Windows.OfType().FirstOrDefault(); + if (loginWindow != null) + { + if (Sign) loginWindow.SignMsg = errorMsg; + else loginWindow.LoginMsg = errorMsg; + } + }); + } + }); } public void Window_Loaded(object sender, RoutedEventArgs e) { diff --git a/chatclient/MainWindow.xaml.cs b/chatclient/MainWindow.xaml.cs index 4df079b..8e5cc86 100644 --- a/chatclient/MainWindow.xaml.cs +++ b/chatclient/MainWindow.xaml.cs @@ -32,7 +32,8 @@ namespace chatclient { LoginWindow Login = new(); static string? receive; - public static string? UserName = null; + public static string UserName { get; set; } = "?"; + public static string? token = null; private static readonly ILog log = LogManager.GetLogger(typeof(MainWindow)); public static Socket? Client; public static readonly HttpClient HttpClient = new HttpClient(); @@ -73,8 +74,7 @@ namespace chatclient log.Error(ex); } Login.Show(); - Thread th = new Thread(Receive); - th.Start(); + if(Client != null && Client.Connected == true) StartReceive(); MessageList.ItemsSource = Messages; ((INotifyCollectionChanged)MessageList.Items).CollectionChanged += (s, e) => { @@ -85,6 +85,15 @@ namespace chatclient }), DispatcherPriority.ContextIdle); }; } + public static void StartReceive() + { + if (Client != null && Client.Connected == true) + { + Thread th = new Thread(Receive); + th.Start(); + } + else { log.Fatal("在Client为NULL或未连接服务器时被调用StartReceive()"); } + } static void Receive() { byte[] buffer = new byte[1024]; @@ -125,7 +134,7 @@ namespace chatclient { if (LoginResponse!.status == "success" && LoginResponse != null) { - log.Info($"用户 {UserName} 登录成功"); + token = LoginResponse.token; Application.Current.Dispatcher.Invoke(() => { var mainWindow = Application.Current.Windows.OfType().FirstOrDefault(); @@ -138,6 +147,7 @@ namespace chatclient mainWindow.Activate(); } }); + log.Info($"用户 {UserName} 登录成功(token:{token})"); } else { @@ -193,6 +203,11 @@ namespace chatclient else { log.Error($"未知的消息类型: {Type.type},请检查服务器响应格式"); + Application.Current.Dispatcher.Invoke(() => + { + var loginWindow = Application.Current.Windows.OfType().FirstOrDefault(); + if (loginWindow != null) loginWindow.LoginMsg = "服务器返回了错误的值"; + }); } } } diff --git a/chatclient/chatclient.csproj b/chatclient/chatclient.csproj index d27dadf..7f1c629 100644 --- a/chatclient/chatclient.csproj +++ b/chatclient/chatclient.csproj @@ -33,10 +33,22 @@ + + + True + True + DataSet.xsd + + + PreserveNewest + + MSDataSetGenerator + DataSet.Designer.cs + diff --git a/chatclient/config/log4net.config b/chatclient/config/log4net.config index f30cfcc..346ce4c 100644 --- a/chatclient/config/log4net.config +++ b/chatclient/config/log4net.config @@ -2,15 +2,15 @@ - + - + - + diff --git a/chatclient/resource/chat.ico b/chatclient/resource/chat.ico index 868f348..843ade8 100644 Binary files a/chatclient/resource/chat.ico and b/chatclient/resource/chat.ico differ diff --git a/chatclient/resource/chat.png b/chatclient/resource/chat.png new file mode 100644 index 0000000..0260bd3 Binary files /dev/null and b/chatclient/resource/chat.png differ