修复bug,优化了登录方法,适配了新API。完成了登录界面优化。

This commit is contained in:
绪山七寻 2025-06-02 16:40:36 +08:00
parent b58016caf4
commit 20be6f6613
5 changed files with 267 additions and 90 deletions

View File

@ -11,7 +11,7 @@
ResizeMode="NoResize">
<TabControl>
<TabItem Header="登录账号" Cursor="Hand">
<TabItem Header="登录账号" Cursor="Hand" Height="40">
<Grid Background="#FFE5E5E5">
<Grid.RowDefinitions>
<RowDefinition Height="1.2*"/>
@ -33,7 +33,7 @@
Style="{StaticResource MaterialDesignOutlinedRevealPasswordBox}"/>
<Grid>
<CheckBox Content="记住我" IsChecked="{Binding SaveAccount}"/>
<TextBlock x:Name="LoginMsg" Text="" Style="{StaticResource MaterialDesignBody2TextBlock}" HorizontalAlignment="Right" Foreground="#FFCC3333"/>
<TextBlock Text="{Binding LoginMsg}" Style="{StaticResource MaterialDesignBody2TextBlock}" HorizontalAlignment="Right" Foreground="#FFCC3333"/>
</Grid>
<Button Content="登录" Margin="0,20,0,0" Click="Login_Click" Style="{StaticResource MaterialDesignRaisedButton}" ToolTip="登录账号" FontWeight="Normal"/>
</StackPanel>
@ -42,7 +42,7 @@
</Grid>
</Grid>
</TabItem>
<TabItem Header="注册账号">
<TabItem Header="注册账号" Height="40">
<Grid Background="#FFE5E5E5">
<Grid.RowDefinitions>
<RowDefinition Height="0.8*"/>

View File

@ -1,25 +1,14 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Net.Sockets;
using System.IO;
using log4net;
using log4net.Config;
using System.Windows.Interop;
using chatapi;
using System.Runtime.CompilerServices;
using System.Net.Http;
using Microsoft.Win32;
namespace chatclient
@ -45,6 +34,16 @@ namespace chatclient
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
{
@ -69,48 +68,15 @@ namespace chatclient
{
if (UserName == "")
{
LoginMsg.Text = "用户名不能为空";
LoginMsg = "用户名不能为空";
}
else if (UserPassword == "")
{
LoginMsg.Text = "密码不能为空";
LoginMsg = "密码不能为空";
}
else
{
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("127.0.0.1", 5555);
}
catch (Exception ex)
{
log.Error(ex);
MainWindow.Client.Close();
}
finally
{
LoginMsg.Text = "服务器连接失败或已断开连接";
}
}
}
Login(false,UserName,UserPassword);
}
}
private void Sign_Click(object sender, RoutedEventArgs e)
@ -132,17 +98,87 @@ namespace chatclient
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 = SignName,
password = SignPassword1
username = Username,
password = Userpassword
};
string SignJsonData = JsonSerializer.Serialize(SignData);
byte[] dataBytes = Encoding.UTF8.GetBytes(SignJsonData);
log.Info($"向服务器发送注册请求UserName:{SignName}");
Update("LoginMsg");
var content = new StringContent(SignJsonData, Encoding.UTF8, "application/json");
var response = await MainWindow.HttpClient.PostAsync($"{chatapi.Server.ServerUrl}/api/register", content);
var responseBody = await response.Content.ReadAsStringAsync();
log.Info($"注册请求已发送,响应内容: {responseBody}");
var signresponse = JsonSerializer.Deserialize<SignResultData>(responseBody);
if (signresponse!.success)
{
// 显示 MainWindow
Application.Current.Dispatcher.Invoke(() =>
{
var mainWindow = Application.Current.Windows
.OfType<MainWindow>()
.FirstOrDefault();
});
log.Info($"注册成功: {signresponse.message}");
Application.Current.Dispatcher.Invoke(() =>
{
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("注册请求已完成");
}
}
//var loginWindow = Application.Current.Windows.OfType<LoginWindow>().FirstOrDefault();
//loginWindow?.Close();
public static void Login(bool Sign,string Username, string Userpassword)
{
if (Sign)
{
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)
@ -155,7 +191,7 @@ namespace chatclient
{
log.Info("未连接服务器,尝试连接");
MainWindow.Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
MainWindow.Client.Connect("127.0.0.1", 5555);
MainWindow.Client.Connect(System.Net.IPAddress.Parse(Server.ServerIP), Server.ServerPort);
}
catch (Exception ex)
{
@ -164,11 +200,69 @@ namespace chatclient
}
finally
{
SignMsg = "服务器连接失败或已断开连接";
Application.Current.Dispatcher.Invoke(() =>
{
var loginWindow = Application.Current.Windows.OfType<LoginWindow>().FirstOrDefault();
loginWindow!.SignMsg = "在完成注册后与服务器断开连接\n请尝试在登录窗口重新登录";
});
//"服务器连接失败";
}
}
}
}
else
{
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<LoginWindow>().FirstOrDefault();
if (loginWindow != null)
{
loginWindow.LoginMsg = "服务器连接失败";
}
});
}
}
}
}
}
public void Window_Loaded(object sender, RoutedEventArgs e)
{
// 窗口加载时可以进行一些初始化操作
log.Info("登录窗口已加载");
// 如果需要从配置文件或其他地方加载保存的账号信息,可以在这里实现
// 例如UserName = LoadSavedUsername();
// Update("UserName");
}
}
}

View File

@ -12,9 +12,12 @@
<materialDesign:Card>
<TabControl VerticalContentAlignment="Bottom" materialDesign:ColorZoneAssist.Mode="PrimaryMid" Style="{StaticResource MaterialDesignNavigationRailTabControl}">
<materialDesign:NavigationRailAssist.FloatingContent>
<Button Style="{StaticResource MaterialDesignFloatingActionMiniLightButton}" Margin="12" ToolTip="name">
<Image Source="/user.png" />
</Button>
<StackPanel>
<Button Style="{StaticResource MaterialDesignFloatingActionMiniLightButton}" Margin="12" >
<Image Source="/user.png" />
</Button>
<TextBlock Text="{Binding Username}"/>
</StackPanel>
</materialDesign:NavigationRailAssist.FloatingContent>
<TabItem>
<TabItem.Header>

View File

@ -8,7 +8,8 @@ using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net.Sockets;
using System.Net.Sockets;//socket库
using System.Net.Http;
using System.Net;
using System.IO;
using System;
@ -20,6 +21,7 @@ using chatapi;
using System.Diagnostics;
using System.Windows.Interop;
using ControlzEx.Standard;
using System.ComponentModel;
[assembly: XmlConfigurator(ConfigFile = "config/log4net.config", Watch = true)]
namespace chatclient
@ -27,24 +29,40 @@ namespace chatclient
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
public partial class MainWindow : Window, INotifyPropertyChanged
{
LoginWindow Login = new();
static string? receive;
public static int user_id = 0;
public static string? LoginMsg = "123";
public static string? UserName = null;
private static readonly ILog log = LogManager.GetLogger(typeof(MainWindow));
public static Socket? Client;
public static readonly HttpClient HttpClient = new HttpClient();
public event PropertyChangedEventHandler? PropertyChanged;
private string? _Username;
public string? Username
{
get { return _Username; }
set
{
_Username = value;
Update("Username");
}
}
private void Update(string UpdateName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(UpdateName));
}
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
log.Info("Hello World!");
this.Hide();
Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
log.Info("连接服务器 127.0.0.1:5555 ");
Client.Connect("127.0.0.1", 5555);
log.Info($"连接服务器 {Server.ServerIP}:{Server.ServerPort} ");
Client.Connect(Server.ServerIP, Server.ServerPort);
}
catch (Exception ex)
{
@ -55,6 +73,7 @@ namespace chatclient
Thread th = new Thread(Receive);
th.Start();
}
static void Receive()
{
byte[] buffer = new byte[1024];
@ -73,7 +92,8 @@ namespace chatclient
response(receive);
}
}
catch (Exception ex) {
catch (Exception ex)
{
log.Error(ex);
}
finally
@ -81,18 +101,64 @@ namespace chatclient
Client?.Close();
}
}
static void response(string msg)
static void response(string msg)
{
LoginData data = JsonSerializer.Deserialize<LoginData>(msg)!;
if (data.success) {
log.Info($"收到服务器消息: {msg}");
try
{
var Type = JsonSerializer.Deserialize<RegisterData>(msg);
if (Type != null)
{
var LoginResponse = JsonSerializer.Deserialize<LoginResultData>(msg);
if (Type.type == "login_1")
{
if (LoginResponse!.status == "success" && LoginResponse != null)
{
log.Info($"用户 {UserName} 登录成功");
Application.Current.Dispatcher.Invoke(() =>
{
var mainWindow = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();
if (mainWindow != null)
{
mainWindow.Username = UserName;
mainWindow.Show();
var loginWindow = Application.Current.Windows.OfType<LoginWindow>().FirstOrDefault();
loginWindow?.Close();
mainWindow.Activate();
}
});
}
else if (LoginResponse != null)
{
log.Warn($"登录失败: {LoginResponse.message}\nMsg:{msg}");
var loginWindow = Application.Current.Windows.OfType<LoginWindow>().FirstOrDefault();
loginWindow!.LoginMsg = LoginResponse.message;
}
}
else if (Type.type == "login_0")
{
if (LoginResponse != null)
{
var loginWindow = Application.Current.Windows.OfType<LoginWindow>().FirstOrDefault();
loginWindow!.LoginMsg = LoginResponse.message;
}
else
{
var loginWindow = Application.Current.Windows.OfType<LoginWindow>().FirstOrDefault();
loginWindow!.LoginMsg = "服务器返回错误";
}
}
}
}
else {
//LoginWindow.Instance.LoginMsg.Text = msg;
catch (JsonException ex)
{
log.Error("JSON解析错误", ex);
}
catch (Exception ex)
{
log.Error("处理响应时发生错误", ex);
}
}
}
}

View File

@ -1,22 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace chatapi
{
internal class Server
{
public const string ServerUrl = "http://127.0.0.1:5001";
public const string ServerIP = "127.0.0.1";
public const int ServerPort = 8889;
}
internal class LoginData
{
public bool success { get; set; }
public string? message { get; set; }
public string? token { get; set; }
public int? user_id { get; set; }
public string? username { get; set; }
public string? type { get; set; } = null;
public string? username { get; set; } = null;
public string? password { get; set; } = null;
}
internal class LoginResultData
{
public string? status { get; set; } = null;
public string? message { get; set; } = null;
}
internal class SignData
{
public string? type { get; set; } = null;
public string? username { get; set; } = null;
public string? password { get; set; } = null;
}
internal class SignResultData
{
public bool success { get; set; } = false;
public string? message { get; set; } = null;
}
internal class RegisterData
{
public bool success { get; set; }
public string? message { get; set; }
public string? type { get; set; }
}
}