增强登录注册功能,支持异步处理
在 `chatapi.cs` 中添加 `token` 属性以支持身份验证,并在 `ChatRegisterData` 中添加 `status` 属性。将 `Login_Click` 方法和 `Login` 方法修改为异步,以提高响应速度和流畅度。更新 `MainWindow` 中的 `UserName` 属性类型,并添加 `StartReceive` 方法以启动接收线程。改进日志记录功能以更好地跟踪用户操作和系统状态。更新项目文件以支持设计时生成,并调整日志文件的生成路径和日期模式。
This commit is contained in:
parent
10fda56999
commit
6f97c400c0
@ -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;
|
||||
|
@ -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<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);
|
||||
});
|
||||
await Login(true, Username, Userpassword);
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -164,96 +156,54 @@ namespace chatclient
|
||||
log.Info("注册请求已完成");
|
||||
}
|
||||
}
|
||||
//var loginWindow = Application.Current.Windows.OfType<LoginWindow>().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<LoginWindow>().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<LoginWindow>().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<LoginWindow>().FirstOrDefault();
|
||||
if (loginWindow != null)
|
||||
{
|
||||
if (Sign) loginWindow.SignMsg = errorMsg;
|
||||
else loginWindow.LoginMsg = errorMsg;
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
public void Window_Loaded(object sender, RoutedEventArgs e)
|
||||
{
|
||||
|
@ -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<MainWindow>().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<LoginWindow>().FirstOrDefault();
|
||||
if (loginWindow != null) loginWindow.LoginMsg = "服务器返回了错误的值";
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -33,10 +33,22 @@
|
||||
<Resource Include="resource\user.png" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Data\DataSet.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
<AutoGen>True</AutoGen>
|
||||
<DependentUpon>DataSet.xsd</DependentUpon>
|
||||
</Compile>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="config\log4net.config">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Data\DataSet.xsd">
|
||||
<Generator>MSDataSetGenerator</Generator>
|
||||
<LastGenOutput>DataSet.Designer.cs</LastGenOutput>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
@ -2,15 +2,15 @@
|
||||
<configuration>
|
||||
<log4net>
|
||||
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
|
||||
<datePattern value="yyyyMM\\yyyyMMdd'_chat.log'" />
|
||||
<datePattern value="yyyyMMdd'_chat.log'" />
|
||||
<encoding value="utf-8" />
|
||||
<file value="..\\..\\log\\" />
|
||||
<file value="log\\" />
|
||||
<appendToFile value="true" />
|
||||
<rollingStyle value="Date" />
|
||||
<staticLogFileName value="false" />
|
||||
<param name="MaxSizeRollBackups" value="100" />
|
||||
<layout type="log4net.Layout.PatternLayout">
|
||||
<conversionPattern value="[%date %thread %-5level %logger]%ndc - %message%newline" />
|
||||
<conversionPattern value="[%date %thread %logger %-5level]%ndc - %message%newline" />
|
||||
</layout>
|
||||
</appender>
|
||||
<root>
|
||||
|
Binary file not shown.
Before Width: | Height: | Size: 87 KiB After Width: | Height: | Size: 99 KiB |
BIN
chatclient/resource/chat.png
Normal file
BIN
chatclient/resource/chat.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 128 KiB |
Loading…
x
Reference in New Issue
Block a user