在 `LoginWindow.xaml` 中添加了 `Closing` 事件处理程序,以便在窗口关闭时执行特定逻辑。新增的 `Window_Closing` 方法会检查 `MainWindow.token` 是否为 `null`,并在必要时关闭应用程序。此外,在 `MainWindow.xaml.cs` 中确保在清理资源时将 `token` 设置为 `null`,以避免潜在的资源泄漏或错误。
223 lines
7.9 KiB
C#
223 lines
7.9 KiB
C#
using System;
|
||
using System.ComponentModel;
|
||
using System.Text;
|
||
using System.Text.Json;
|
||
using System.Threading.Tasks;
|
||
using System.Windows;
|
||
using System.Net.Sockets;
|
||
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
|
||
{
|
||
/// <summary>
|
||
/// LoginWindow.xaml 的交互逻辑
|
||
/// </summary>
|
||
public partial class LoginWindow : Window, INotifyPropertyChanged
|
||
{
|
||
private static readonly ILog log = LogManager.GetLogger(typeof(LoginWindow));
|
||
public LoginWindow()
|
||
{
|
||
InitializeComponent();
|
||
this.DataContext = this;
|
||
}
|
||
public event PropertyChangedEventHandler? PropertyChanged;
|
||
private void Update(string UpdateName)
|
||
{
|
||
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(UpdateName));
|
||
}
|
||
public static string UserName { get; set; } = "";
|
||
public static string UserPassword { get; set; } = "";
|
||
public static string SignName { get; set; } = "";
|
||
public static string SignPassword1 { get; set; } = "";
|
||
public static string SignPassword2 { get; set; } = "";
|
||
private string? _LoginMsg;
|
||
public string? LoginMsg
|
||
{
|
||
get { return _LoginMsg; }
|
||
set
|
||
{
|
||
_LoginMsg = value;
|
||
Update("LoginMsg");
|
||
}
|
||
}
|
||
private string? _SignMsg;
|
||
public string? SignMsg
|
||
{
|
||
get { return _SignMsg; }
|
||
set
|
||
{
|
||
_SignMsg = value;
|
||
Update("SignMsg");
|
||
}
|
||
}
|
||
private bool _SaveAccount;
|
||
public bool SaveAccount
|
||
{
|
||
get { return _SaveAccount; }
|
||
set
|
||
{
|
||
_SaveAccount = value;
|
||
Update("SaveAccount");
|
||
}
|
||
}
|
||
private async void Login_Click(object sender, RoutedEventArgs e)
|
||
{
|
||
if (UserName == "")
|
||
{
|
||
LoginMsg = "用户名不能为空";
|
||
}
|
||
else if (UserPassword == "")
|
||
{
|
||
LoginMsg = "密码不能为空";
|
||
}
|
||
else
|
||
{
|
||
await Login(false, UserName, UserPassword);
|
||
}
|
||
}
|
||
private void Sign_Click(object sender, RoutedEventArgs e)
|
||
{
|
||
if (SignName == "")
|
||
{
|
||
SignMsg = "用户名不能为空";
|
||
}
|
||
else if (SignPassword1 == "")
|
||
{
|
||
SignMsg = "密码不能为空";
|
||
}
|
||
else if (SignPassword2 == "")
|
||
{
|
||
SignMsg = "请再次确认密码";
|
||
}
|
||
else if (SignPassword1 != SignPassword2)
|
||
{
|
||
SignMsg = "两次密码输入不一致";
|
||
}
|
||
else
|
||
{
|
||
log.Info($"向服务器发送注册HttpAPI请求(UserName:{SignName})");
|
||
SignRegistryUser(SignName, SignPassword1).ContinueWith(task =>
|
||
{
|
||
if (task.IsCompletedSuccessfully)
|
||
{
|
||
log.Info("注册请求发送成功");
|
||
}
|
||
else
|
||
{
|
||
log.Error("注册请求发送失败", task.Exception);
|
||
}
|
||
});
|
||
}
|
||
}
|
||
public static async Task SignRegistryUser(string Username, string Userpassword)
|
||
{
|
||
try
|
||
{
|
||
var SignData = new
|
||
{
|
||
type = "register",
|
||
username = Username,
|
||
password = Userpassword
|
||
};
|
||
string SignJsonData = JsonSerializer.Serialize(SignData);
|
||
byte[] dataBytes = Encoding.UTF8.GetBytes(SignJsonData);
|
||
var content = new StringContent(SignJsonData, Encoding.UTF8, "application/json");
|
||
var response = await MainWindow.HttpClient.PostAsync($"{Server.ServerUrl}/api/register", content);
|
||
var responseBody = await response.Content.ReadAsStringAsync();
|
||
log.Info($"注册请求已发送,响应内容: {responseBody}");
|
||
var signresponse = JsonSerializer.Deserialize<SignResultData>(responseBody);
|
||
if (signresponse!.success)
|
||
{
|
||
log.Info($"注册成功: {signresponse.message}");
|
||
await Login(true, Username, Userpassword);
|
||
}
|
||
else
|
||
{
|
||
log.Error($"注册失败: {signresponse.message}");
|
||
Application.Current.Dispatcher.Invoke(() =>
|
||
{
|
||
var loginWindow = Application.Current.Windows.OfType<LoginWindow>().FirstOrDefault();
|
||
loginWindow!.SignMsg = signresponse.message;
|
||
});
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
log.Error("注册请求发送失败", ex);
|
||
}
|
||
finally
|
||
{
|
||
log.Info("注册请求已完成");
|
||
}
|
||
}
|
||
public static async Task Login(bool Sign, string Username, string Userpassword)
|
||
{
|
||
// 公共的登录数据准备
|
||
var LoginData = new
|
||
{
|
||
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)
|
||
{
|
||
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<LoginWindow>().FirstOrDefault();
|
||
if (loginWindow != null)
|
||
{
|
||
if (Sign) loginWindow.SignMsg = errorMsg;
|
||
else loginWindow.LoginMsg = errorMsg;
|
||
}
|
||
});
|
||
}
|
||
});
|
||
}
|
||
public void Window_Loaded(object sender, RoutedEventArgs e)
|
||
{
|
||
// 窗口加载时可以进行一些初始化操作
|
||
log.Info("登录窗口已加载");
|
||
// 如果需要从配置文件或其他地方加载保存的账号信息,可以在这里实现
|
||
// 例如:UserName = LoadSavedUsername();
|
||
// Update("UserName");
|
||
}
|
||
public void Window_Closing(object sender, CancelEventArgs e)
|
||
{
|
||
if(MainWindow.token == null) Application.Current.Shutdown();
|
||
}
|
||
}
|
||
}
|
||
|