Update SocketHandler (#8)

This commit is contained in:
milimoe 2023-04-24 01:40:38 +08:00 committed by GitHub
parent 8b435390bd
commit 5aa9439f2c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 75 additions and 199 deletions

View File

@ -14,6 +14,8 @@ namespace Milimoe.FunGame.Desktop.Controller
private MainModel MainModel { get; } private MainModel MainModel { get; }
private Main Main { get; } private Main Main { get; }
private readonly Core.Model.Session Usercfg = RunTime.Session;
public MainController(Main Main) public MainController(Main Main)
{ {
this.Main = Main; this.Main = Main;

View File

@ -7,9 +7,9 @@ using Milimoe.FunGame.Desktop.UI;
namespace Milimoe.FunGame.Desktop.Controller namespace Milimoe.FunGame.Desktop.Controller
{ {
public class RunTimeController public class RunTimeController : Core.Controller.RunTimeController
{ {
public bool Connected => RunTimeModel.Connected; public override bool Connected => RunTimeModel.Connected;
private RunTimeModel RunTimeModel { get; } private RunTimeModel RunTimeModel { get; }
private Main Main { get; } private Main Main { get; }
@ -20,7 +20,7 @@ namespace Milimoe.FunGame.Desktop.Controller
RunTimeModel = new RunTimeModel(Main); RunTimeModel = new RunTimeModel(Main);
} }
public async Task<bool> GetServerConnection() public override async Task<bool> GetServerConnection()
{ {
bool result = false; bool result = false;
@ -37,7 +37,7 @@ namespace Milimoe.FunGame.Desktop.Controller
return result; return result;
} }
public async Task<ConnectResult> Connect() public override async Task<ConnectResult> Connect()
{ {
ConnectResult result = ConnectResult.ConnectFailed; ConnectResult result = ConnectResult.ConnectFailed;
@ -60,7 +60,7 @@ namespace Milimoe.FunGame.Desktop.Controller
return result; return result;
} }
public bool Disconnect() public override bool Disconnect()
{ {
bool result = false; bool result = false;
@ -82,7 +82,7 @@ namespace Milimoe.FunGame.Desktop.Controller
return result; return result;
} }
public bool Close(Exception? e = null) public override bool Close(Exception? e = null)
{ {
bool result; bool result;
@ -98,12 +98,12 @@ namespace Milimoe.FunGame.Desktop.Controller
return result; return result;
} }
public bool Error(Exception e) public override bool Error(Exception e)
{ {
return Close(e); return Close(e);
} }
public async Task AutoLogin(string Username, string Password, string AutoKey) public override async Task AutoLogin(string Username, string Password, string AutoKey)
{ {
try try
{ {
@ -116,5 +116,10 @@ namespace Milimoe.FunGame.Desktop.Controller
Main.GetMessage(e.GetErrorInfo(), TimeType.None); Main.GetMessage(e.GetErrorInfo(), TimeType.None);
} }
} }
public override void WritelnSystemInfo(string msg)
{
Main?.GetMessage(msg);
}
} }
} }

View File

@ -2,9 +2,6 @@
{ {
public class Config public class Config
{ {
/**
* FunGame Desktop Configs
*/
public static bool FunGame_isAutoConnect { get; set; } = true; // 是否自动连接服务器 public static bool FunGame_isAutoConnect { get; set; } = true; // 是否自动连接服务器
public static bool FunGame_isAutoLogin { get; set; } = false; // 是否自动登录 public static bool FunGame_isAutoLogin { get; set; } = false; // 是否自动登录
public static bool FunGame_isMatching { get; set; } = false; // 是否在匹配中 public static bool FunGame_isMatching { get; set; } = false; // 是否在匹配中
@ -19,9 +16,5 @@
public static string FunGame_AutoLoginUser { get; set; } = ""; // 自动登录的账号 public static string FunGame_AutoLoginUser { get; set; } = ""; // 自动登录的账号
public static string FunGame_AutoLoginPassword { get; set; } = ""; // 自动登录的密码 public static string FunGame_AutoLoginPassword { get; set; } = ""; // 自动登录的密码
public static string FunGame_AutoLoginKey { get; set; } = ""; // 自动登录的秘钥 public static string FunGame_AutoLoginKey { get; set; } = ""; // 自动登录的秘钥
/*** GUID For Socket ***/
public static Guid Guid_Socket { get; set; } = Guid.Empty;
public static Guid Guid_LoginKey { get; set; } = Guid.Empty;
} }
} }

View File

@ -6,8 +6,10 @@
/// </summary> /// </summary>
public class RunTime public class RunTime
{ {
public static Core.Model.RoomList RoomList { get; } = new();
public static Core.Model.Session Session { get; } = new();
public static Core.Library.Common.Network.Socket? Socket { get; set; } = null; public static Core.Library.Common.Network.Socket? Socket { get; set; } = null;
public static Controller.RunTimeController? Connector { get; set; } = null; public static Controller.RunTimeController? Controller { get; set; } = null;
public static UI.Main? Main { get; set; } = null; public static UI.Main? Main { get; set; } = null;
public static UI.Login? Login { get; set; } = null; public static UI.Login? Login { get; set; } = null;
public static UI.Register? Register { get; set; } = null; public static UI.Register? Register { get; set; } = null;
@ -18,7 +20,7 @@
public static void WritelnSystemInfo(string msg) public static void WritelnSystemInfo(string msg)
{ {
Main?.GetMessage(msg); Controller?.WritelnSystemInfo(msg);
} }
} }
} }

View File

@ -1,15 +0,0 @@
using Milimoe.FunGame.Core.Entity;
using Milimoe.FunGame.Core.Library.Constant;
namespace Milimoe.FunGame.Desktop.Library
{
public class Usercfg
{
/**
*
*/
public static User LoginUser { get; set; } = General.UnknownUserInstance; // 已登录的用户
public static string LoginUserName { get; set; } = ""; // 已登录用户名
public static Room InRoom { get; set; } = General.HallInstance; // 所处的房间
}
}

View File

@ -99,7 +99,7 @@ namespace Milimoe.FunGame.Desktop.Model
if (Work.Length > 1) msg = Work.GetParam<string>(1); if (Work.Length > 1) msg = Work.GetParam<string>(1);
if (key != Guid.Empty) if (key != Guid.Empty)
{ {
Config.Guid_LoginKey = key; RunTime.Session.LoginKey = key;
} }
} }
catch (Exception e) catch (Exception e)

View File

@ -14,6 +14,7 @@ namespace Milimoe.FunGame.Desktop.Model
public class MainModel : BaseModel public class MainModel : BaseModel
{ {
private readonly Main Main; private readonly Main Main;
private readonly Core.Model.Session Usercfg = RunTime.Session;
public MainModel(Main main) : base(RunTime.Socket) public MainModel(Main main) : base(RunTime.Socket)
{ {
@ -27,17 +28,17 @@ namespace Milimoe.FunGame.Desktop.Model
try try
{ {
// 需要当时登录给的Key发回去确定是账号本人在操作才允许登出 // 需要当时登录给的Key发回去确定是账号本人在操作才允许登出
if (Config.Guid_LoginKey != Guid.Empty) if (Usercfg.LoginKey != Guid.Empty)
{ {
SetWorking(); SetWorking();
if (RunTime.Socket?.Send(SocketMessageType.Logout, Config.Guid_LoginKey) == SocketResult.Success) if (RunTime.Socket?.Send(SocketMessageType.Logout, Usercfg.LoginKey) == SocketResult.Success)
{ {
string msg = ""; string msg = "";
Guid key = Guid.Empty; Guid key = Guid.Empty;
(msg, key) = await Task.Factory.StartNew(SocketHandler_LogOut); (msg, key) = await Task.Factory.StartNew(SocketHandler_LogOut);
if (key == Config.Guid_LoginKey) if (key == Usercfg.LoginKey)
{ {
Config.Guid_LoginKey = Guid.Empty; Usercfg.LoginKey = Guid.Empty;
Main.UpdateUI(MainInvokeType.LogOut, msg ?? ""); Main.UpdateUI(MainInvokeType.LogOut, msg ?? "");
return true; return true;
} }
@ -202,9 +203,9 @@ namespace Milimoe.FunGame.Desktop.Model
if (SocketObject.Length > 0) key = SocketObject.GetParam<Guid>(0); if (SocketObject.Length > 0) key = SocketObject.GetParam<Guid>(0);
if (SocketObject.Length > 1) msg = SocketObject.GetParam<string>(1); if (SocketObject.Length > 1) msg = SocketObject.GetParam<string>(1);
msg ??= ""; msg ??= "";
if (key == Config.Guid_LoginKey) if (key == Usercfg.LoginKey)
{ {
Config.Guid_LoginKey = Guid.Empty; Usercfg.LoginKey = Guid.Empty;
Main.UpdateUI(MainInvokeType.LogOut, msg ?? ""); Main.UpdateUI(MainInvokeType.LogOut, msg ?? "");
} }
} }
@ -236,7 +237,7 @@ namespace Milimoe.FunGame.Desktop.Model
} }
catch (Exception e) catch (Exception e)
{ {
RunTime.Connector?.Error(e); RunTime.Controller?.Error(e);
} }
} }

View File

@ -12,72 +12,19 @@ namespace Milimoe.FunGame.Desktop.Model
/// <summary> /// <summary>
/// 与创建关闭Socket相关的方法使用此类 /// 与创建关闭Socket相关的方法使用此类
/// </summary> /// </summary>
public class RunTimeModel public class RunTimeModel : Core.Model.RunTime
{ {
public bool Connected => Socket != null && Socket.Connected; public override Socket? Socket => _Socket;
private readonly Main Main; private readonly Main Main;
private Task? ReceivingTask; private readonly Core.Model.Session Usercfg = RunTime.Session;
private Socket? Socket;
private bool IsReceiving = false;
public RunTimeModel(Main main) public RunTimeModel(Main main)
{ {
Main = main; Main = main;
} }
#region public override async Task<ConnectResult> Connect()
public bool Disconnect()
{
bool result = false;
try
{
result = Socket?.Send(SocketMessageType.Disconnect, "") == SocketResult.Success;
}
catch (Exception e)
{
Main.GetMessage(e.GetErrorInfo());
}
return result;
}
public void Disconnected()
{
Disconnect();
}
public void GetServerConnection()
{
try
{
// 获取服务器IP
string? ipaddress = (string?)Implement.GetFunGameImplValue(InterfaceType.IClient, InterfaceMethod.RemoteServerIP);
if (ipaddress != null)
{
string[] s = ipaddress.Split(':');
if (s != null && s.Length > 1)
{
Constant.Server_IP = s[0];
Constant.Server_Port = Convert.ToInt32(s[1]);
}
}
else
{
ShowMessage.ErrorMessage("查找可用的服务器失败!");
Config.FunGame_isRetrying = false;
throw new FindServerFailedException();
}
}
catch (Exception e)
{
Main.GetMessage(e.GetErrorInfo(), TimeType.None);
}
}
public async Task<ConnectResult> Connect()
{ {
if (Constant.Server_IP == "" || Constant.Server_Port <= 0) if (Constant.Server_IP == "" || Constant.Server_Port <= 0)
{ {
@ -105,7 +52,7 @@ namespace Milimoe.FunGame.Desktop.Model
// 与服务器建立连接 // 与服务器建立连接
Socket?.Close(); Socket?.Close();
Config.FunGame_isRetrying = true; Config.FunGame_isRetrying = true;
Socket = Socket.Connect(Constant.Server_IP, Constant.Server_Port); _Socket = Socket.Connect(Constant.Server_IP, Constant.Server_Port);
if (Socket != null && Socket.Connected) if (Socket != null && Socket.Connected)
{ {
// 设置可复用Socket // 设置可复用Socket
@ -123,7 +70,7 @@ namespace Milimoe.FunGame.Desktop.Model
{ {
while (true) while (true)
{ {
if (IsReceiving) if (_IsReceiving)
{ {
break; break;
} }
@ -155,31 +102,7 @@ namespace Milimoe.FunGame.Desktop.Model
} }
} }
public bool Close() public override void Error(Exception e)
{
try
{
if (Socket != null)
{
Socket.Close();
Socket = null;
}
if (ReceivingTask != null && !ReceivingTask.IsCompleted)
{
ReceivingTask.Wait(1);
ReceivingTask = null;
IsReceiving = false;
}
}
catch (Exception e)
{
Main.GetMessage(e.GetErrorInfo(), TimeType.None);
return false;
}
return true;
}
public void Error(Exception e)
{ {
Main.GetMessage(e.GetErrorInfo(), TimeType.None); Main.GetMessage(e.GetErrorInfo(), TimeType.None);
Main.UpdateUI(MainInvokeType.Disconnected); Main.UpdateUI(MainInvokeType.Disconnected);
@ -187,76 +110,35 @@ namespace Milimoe.FunGame.Desktop.Model
Close(); Close();
} }
#endregion public override void GetServerConnection()
#region
private void StartReceiving()
{ {
ReceivingTask = Task.Factory.StartNew(() =>
{
Thread.Sleep(100);
IsReceiving = true;
while (Socket != null && Socket.Connected)
{
Receiving();
}
});
Socket?.StartReceiving(ReceivingTask);
}
private SocketObject GetServerMessage()
{
if (Socket != null && Socket.Connected)
{
return Socket.Receive();
}
return new SocketObject();
}
private SocketMessageType Receiving()
{
if (Socket is null) return SocketMessageType.Unknown;
SocketMessageType result = SocketMessageType.Unknown;
try try
{ {
SocketObject ServerMessage = GetServerMessage(); // 获取服务器IP
SocketMessageType type = ServerMessage.SocketType; string? ipaddress = (string?)Implement.GetFunGameImplValue(InterfaceType.IClient, InterfaceMethod.RemoteServerIP);
object[] objs = ServerMessage.Parameters; if (ipaddress != null)
result = type;
switch (type)
{ {
case SocketMessageType.Connect: string[] s = ipaddress.Split(':');
if (!SocketHandler_Connect(ServerMessage)) return SocketMessageType.Unknown; if (s != null && s.Length > 1)
break; {
Constant.Server_IP = s[0];
case SocketMessageType.Disconnect: Constant.Server_Port = Convert.ToInt32(s[1]);
SocketHandler_Disconnect(ServerMessage); }
break; }
else
case SocketMessageType.HeartBeat: {
if (Socket.Connected && Usercfg.LoginUser.Id != 0) ShowMessage.ErrorMessage("查找可用的服务器失败!");
Main.UpdateUI(MainInvokeType.SetGreenAndPing); Config.FunGame_isRetrying = false;
break; throw new FindServerFailedException();
case SocketMessageType.Unknown:
default:
break;
} }
} }
catch (Exception e) catch (Exception e)
{ {
// 报错中断服务器连接 Main.GetMessage(e.GetErrorInfo(), TimeType.None);
Error(e);
} }
return result;
} }
#endregion protected override bool SocketHandler_Connect(SocketObject ServerMessage)
#region SocketHandler
private bool SocketHandler_Connect(SocketObject ServerMessage)
{ {
string msg = ""; string msg = "";
Guid token = Guid.Empty; Guid token = Guid.Empty;
@ -276,14 +158,14 @@ namespace Milimoe.FunGame.Desktop.Model
Config.FunGame_Notice = ServerNotice; Config.FunGame_Notice = ServerNotice;
if (ServerMessage.Parameters.Length > 1) token = ServerMessage.GetParam<Guid>(1); if (ServerMessage.Parameters.Length > 1) token = ServerMessage.GetParam<Guid>(1);
Socket!.Token = token; Socket!.Token = token;
Config.Guid_Socket = token; Usercfg.SocketToken = token;
Main.GetMessage($"已连接服务器:{ServerName}。\n\n********** 服务器公告 **********\n\n{ServerNotice}\n\n"); Main.GetMessage($"已连接服务器:{ServerName}。\n\n********** 服务器公告 **********\n\n{ServerNotice}\n\n");
// 设置等待登录的黄灯 // 设置等待登录的黄灯
Main.UpdateUI(MainInvokeType.WaitLoginAndSetYellow); Main.UpdateUI(MainInvokeType.WaitLoginAndSetYellow);
return true; return true;
} }
private void SocketHandler_Disconnect(SocketObject ServerMessage) protected override void SocketHandler_Disconnect(SocketObject ServerMessage)
{ {
string msg = ""; string msg = "";
if (ServerMessage.Parameters.Length > 0) msg = ServerMessage.GetParam<string>(0)!; if (ServerMessage.Parameters.Length > 0) msg = ServerMessage.GetParam<string>(0)!;
@ -294,6 +176,12 @@ namespace Milimoe.FunGame.Desktop.Model
Main.OnAfterDisconnectEvent(new GeneralEventArgs()); Main.OnAfterDisconnectEvent(new GeneralEventArgs());
} }
#endregion protected override void SocketHandler_HeartBeat(SocketObject ServerMessage)
{
if (Socket != null && Socket.Connected && Usercfg.LoginUser.Id != 0)
{
Main.UpdateUI(MainInvokeType.SetGreenAndPing);
}
}
} }
} }

View File

@ -1,7 +1,6 @@
using System.Diagnostics; using System.Diagnostics;
using Milimoe.FunGame.Core.Api.Utility; using Milimoe.FunGame.Core.Api.Utility;
using Milimoe.FunGame.Core.Entity; using Milimoe.FunGame.Core.Entity;
using Milimoe.FunGame.Core.Library.Common.Architecture;
using Milimoe.FunGame.Core.Library.Common.Event; using Milimoe.FunGame.Core.Library.Common.Event;
using Milimoe.FunGame.Core.Library.Constant; using Milimoe.FunGame.Core.Library.Constant;
using Milimoe.FunGame.Core.Library.Exception; using Milimoe.FunGame.Core.Library.Exception;
@ -29,7 +28,8 @@ namespace Milimoe.FunGame.Desktop.UI
*/ */
private Task? MatchFunGame = null; // 匹配线程 private Task? MatchFunGame = null; // 匹配线程
private MainController? MainController = null; private MainController? MainController = null;
private readonly RoomList Rooms = new(); private readonly Core.Model.RoomList Rooms = RunTime.RoomList;
private readonly Core.Model.Session Usercfg = RunTime.Session;
/** /**
* *
@ -53,7 +53,7 @@ namespace Milimoe.FunGame.Desktop.UI
ShowFunGameInfo(); // 显示FunGame信息 ShowFunGameInfo(); // 显示FunGame信息
GetFunGameConfig(); // 获取FunGame配置 GetFunGameConfig(); // 获取FunGame配置
// 创建RunTime // 创建RunTime
RunTime.Connector = new RunTimeController(this); RunTime.Controller = new RunTimeController(this);
// 窗口句柄创建后,进行委托 // 窗口句柄创建后,进行委托
await Task.Factory.StartNew(() => await Task.Factory.StartNew(() =>
{ {
@ -64,7 +64,7 @@ namespace Milimoe.FunGame.Desktop.UI
break; break;
} }
} }
if (Config.FunGame_isAutoConnect) RunTime.Connector?.GetServerConnection(); if (Config.FunGame_isAutoConnect) RunTime.Controller?.GetServerConnection();
}); });
} }
@ -130,7 +130,7 @@ namespace Milimoe.FunGame.Desktop.UI
if (MainController != null && Config.FunGame_isAutoConnect) if (MainController != null && Config.FunGame_isAutoConnect)
{ {
// 自动连接服务器 // 自动连接服务器
RunTime.Connector?.Connect(); RunTime.Controller?.Connect();
} }
break; break;
@ -858,7 +858,7 @@ namespace Milimoe.FunGame.Desktop.UI
if (ShowMessage.OKCancelMessage("你确定关闭游戏?", "退出") == (int)MessageResult.OK) if (ShowMessage.OKCancelMessage("你确定关闭游戏?", "退出") == (int)MessageResult.OK)
{ {
if (MainController != null) await MainController.LogOut(); if (MainController != null) await MainController.LogOut();
RunTime.Connector?.Close(); RunTime.Controller?.Close();
Environment.Exit(0); Environment.Exit(0);
} }
} }
@ -1237,7 +1237,7 @@ namespace Milimoe.FunGame.Desktop.UI
Task.Run(() => Task.Run(() =>
{ {
Thread.Sleep(5000); Thread.Sleep(5000);
if (Config.FunGame_isConnected && Config.FunGame_isAutoRetry) RunTime.Connector?.Connect(); // 再次判断是否开启自动重连 if (Config.FunGame_isConnected && Config.FunGame_isAutoRetry) RunTime.Controller?.Connect(); // 再次判断是否开启自动重连
}); });
GetMessage("连接服务器失败5秒后自动尝试重连。"); GetMessage("连接服务器失败5秒后自动尝试重连。");
} }
@ -1258,7 +1258,7 @@ namespace Milimoe.FunGame.Desktop.UI
if (MainController != null && Config.FunGame_isAutoLogin && Config.FunGame_AutoLoginUser != "" && Config.FunGame_AutoLoginPassword != "" && Config.FunGame_AutoLoginKey != "") if (MainController != null && Config.FunGame_isAutoLogin && Config.FunGame_AutoLoginUser != "" && Config.FunGame_AutoLoginPassword != "" && Config.FunGame_AutoLoginKey != "")
{ {
// 自动登录 // 自动登录
_ = RunTime.Connector?.AutoLogin(Config.FunGame_AutoLoginUser, Config.FunGame_AutoLoginPassword, Config.FunGame_AutoLoginKey); _ = RunTime.Controller?.AutoLogin(Config.FunGame_AutoLoginUser, Config.FunGame_AutoLoginPassword, Config.FunGame_AutoLoginKey);
} }
return EventResult.Success; return EventResult.Success;
} }
@ -1337,7 +1337,7 @@ namespace Milimoe.FunGame.Desktop.UI
{ {
CurrentRetryTimes = -1; CurrentRetryTimes = -1;
Config.FunGame_isAutoRetry = true; Config.FunGame_isAutoRetry = true;
RunTime.Connector?.Connect(); RunTime.Controller?.Connect();
} }
else else
WritelnGameInfo(">> 你不能在连接服务器的同时重试连接!"); WritelnGameInfo(">> 你不能在连接服务器的同时重试连接!");
@ -1347,20 +1347,20 @@ namespace Milimoe.FunGame.Desktop.UI
{ {
CurrentRetryTimes = -1; CurrentRetryTimes = -1;
Config.FunGame_isAutoRetry = true; Config.FunGame_isAutoRetry = true;
RunTime.Connector?.GetServerConnection(); RunTime.Controller?.GetServerConnection();
} }
break; break;
case Constant.FunGame_Disconnect: case Constant.FunGame_Disconnect:
if (Config.FunGame_isConnected && MainController != null) if (Config.FunGame_isConnected && MainController != null)
{ {
// 先退出登录再断开连接 // 先退出登录再断开连接
if (MainController != null && await MainController.LogOut()) RunTime.Connector?.Disconnect(); if (MainController != null && await MainController.LogOut()) RunTime.Controller?.Disconnect();
} }
break; break;
case Constant.FunGame_DisconnectWhenNotLogin: case Constant.FunGame_DisconnectWhenNotLogin:
if (Config.FunGame_isConnected && MainController != null) if (Config.FunGame_isConnected && MainController != null)
{ {
RunTime.Connector?.Disconnect(); RunTime.Controller?.Disconnect();
} }
break; break;
case Constant.FunGame_ConnectTo: case Constant.FunGame_ConnectTo:
@ -1391,7 +1391,7 @@ namespace Milimoe.FunGame.Desktop.UI
Constant.Server_Port = port; Constant.Server_Port = port;
CurrentRetryTimes = -1; CurrentRetryTimes = -1;
Config.FunGame_isAutoRetry = true; Config.FunGame_isAutoRetry = true;
RunTime.Connector?.Connect(); RunTime.Controller?.Connect();
} }
else if (ErrorType == Core.Library.Constant.ErrorType.IsNotIP) ShowMessage.ErrorMessage("这不是一个IP地址"); else if (ErrorType == Core.Library.Constant.ErrorType.IsNotIP) ShowMessage.ErrorMessage("这不是一个IP地址");
else if (ErrorType == Core.Library.Constant.ErrorType.IsNotPort) ShowMessage.ErrorMessage("这不是一个端口号!\n正确范围1~65535"); else if (ErrorType == Core.Library.Constant.ErrorType.IsNotPort) ShowMessage.ErrorMessage("这不是一个端口号!\n正确范围1~65535");