diff --git a/FunGame.Console/FunGame.Console.csproj b/FunGame.Console/FunGame.Console.csproj index 7097cf2..31bcbd3 100644 --- a/FunGame.Console/FunGame.Console.csproj +++ b/FunGame.Console/FunGame.Console.csproj @@ -9,7 +9,7 @@ Milimoe FunGame FunGame.Console - images\logo.ico + logo.ico ..\bin\ FunGame Milimoe.$(MSBuildProjectName.Replace(" ", "_")) @@ -24,7 +24,7 @@ - + diff --git a/FunGame.Desktop/Images/logo.ico b/FunGame.Console/logo.ico similarity index 100% rename from FunGame.Desktop/Images/logo.ico rename to FunGame.Console/logo.ico diff --git a/FunGame.Core/Api/Utility/FactoryHelper.cs b/FunGame.Core/Api/Utility/Factory.cs similarity index 93% rename from FunGame.Core/Api/Utility/FactoryHelper.cs rename to FunGame.Core/Api/Utility/Factory.cs index 4faee88..f8642b0 100644 --- a/FunGame.Core/Api/Utility/FactoryHelper.cs +++ b/FunGame.Core/Api/Utility/Factory.cs @@ -8,8 +8,8 @@ using Milimoe.FunGame.Core.Library.Constant; namespace Milimoe.FunGame.Core.Api.Utility { - public class FactoryHelper - { + public class Factory + { /// /// 获取一个可能为NULL的实例 /// @@ -23,7 +23,7 @@ namespace Milimoe.FunGame.Core.Api.Utility if (objs is null || objs.Length == 0) return instance; if (typeof(T) == typeof(Entity.User)) { - instance = Factory.UserFactory.GetInstance("Mili"); + instance = Api.Factory.UserFactory.GetInstance("Mili"); } else if (typeof(T) == typeof(Skill)) { @@ -48,7 +48,7 @@ namespace Milimoe.FunGame.Core.Api.Utility if (objs is null || objs.Length == 0) return instance; if (typeof(T) == typeof(Entity.User)) { - instance = Factory.UserFactory.GetInstance("Mili"); + instance = Api.Factory.UserFactory.GetInstance("Mili"); } else if (typeof(T) == typeof(Skill)) { @@ -73,7 +73,7 @@ namespace Milimoe.FunGame.Core.Api.Utility if (objs is null || objs.Length == 0) return instance; if (typeof(T) == typeof(Entity.User)) { - instance = Factory.UserFactory.GetInstance("Mili"); + instance = Api.Factory.UserFactory.GetInstance("Mili"); } else if (typeof(T) == typeof(Skill)) { diff --git a/FunGame.Core/Api/Utility/General.cs b/FunGame.Core/Api/Utility/General.cs index 8e42294..ffafdda 100644 --- a/FunGame.Core/Api/Utility/General.cs +++ b/FunGame.Core/Api/Utility/General.cs @@ -156,7 +156,6 @@ namespace Milimoe.FunGame.Core.Api.Utility DateTime now = DateTime.Now; return type switch { - TimeType.General => now.ToString("yyyy-MM-dd HH:mm:ss"), TimeType.DateOnly => now.Date.ToString(""), TimeType.TimeOnly => now.ToString("T"), TimeType.Year4 => now.Year.ToString(), @@ -166,7 +165,7 @@ namespace Milimoe.FunGame.Core.Api.Utility TimeType.Hour => now.Hour.ToString(), TimeType.Minute => now.Minute.ToString(), TimeType.Second => now.Second.ToString(), - _ => now.ToString("yyyy-MM-dd HH:mm:ss") + _ => now.ToString("yyyy/MM/dd HH:mm:ss") }; } diff --git a/FunGame.Core/Api/Utility/Implement.cs b/FunGame.Core/Api/Utility/Implement.cs new file mode 100644 index 0000000..3b3c02f --- /dev/null +++ b/FunGame.Core/Api/Utility/Implement.cs @@ -0,0 +1,100 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; +using Milimoe.FunGame.Core.Library.Constant; + +namespace Milimoe.FunGame.Core.Api.Utility +{ + /// + /// Interface的定义已经搬至: + /// Milimoe.FunGame.Core.Library.Constant 中的 &InterfaceType 和 &InterfaceSet + /// + public class Implement + { + /// + /// 获取FunGame.Implement.dll中接口的实现方法 + /// + /// 接口代号 + /// + private static Type? GetFunGameImplementType(System.Reflection.Assembly Assembly, InterfaceType Interface) + { + // 通过类名获取命名空间+类名称 + string ClassName = GetImplementClassName(Interface); + List? Classes = null; + if (Assembly != null) + { + Classes = Assembly.GetTypes().Where(w => + w.Namespace == "Milimoe.FunGame.Core.Implement" && + w.Name.Contains(ClassName) + ).ToList(); + if (Classes != null && Classes.Count > 0) + return Classes[0]; + else return null; + } + else return null; + } + + /// + /// 获取接口实现类类名 + /// + /// 接口类型 + /// + private static string GetImplementClassName(InterfaceType Interface) + { + return Interface switch + { + InterfaceType.IClient => InterfaceSet.Type.IClient, + InterfaceType.IServer => InterfaceSet.Type.IServer, + _ => "" + }; + } + + /// + /// 获取接口方法名 + /// + /// 方法 + /// + private static string GetImplementMethodName(InterfaceMethod Method) + { + return Method switch + { + InterfaceMethod.RemoteServerIP => InterfaceSet.Method.RemoteServerIP, + InterfaceMethod.DBConnection => InterfaceSet.Method.DBConnection, + InterfaceMethod.GetServerSettings => InterfaceSet.Method.GetServerSettings, + _ => "" + }; + } + + /// + /// 公开方法:获取FunGame.Implement.DLL中指定方法的返回值 + /// + /// 接口代号 + /// 方法代号 + /// + public static object? GetFunGameImplValue(InterfaceType Interface, InterfaceMethod Method) + { + MethodInfo? MethodInfo; + + Assembly? Assembly = System.Reflection.Assembly.LoadFile(ReflectionSet.EXEFolderPath + ReflectionSet.FUNGAME_IMPL + ".dll"); + Type? Type = GetFunGameImplementType(Assembly, Interface); // 通过类名获取命名空间+类名称 + string MethodName = GetImplementMethodName(Method); // 获取方法名 + + if (Assembly != null && Type != null) MethodInfo = Type.GetMethod(MethodName); // 从Type中查找方法名 + else return null; + + object? Instance = Assembly.CreateInstance(Type.Namespace + "." + Type.Name); + if (Instance != null && MethodInfo != null) + { + object? value = MethodInfo.Invoke(Instance, Array.Empty()); // 实例方法的调用 + if (value != null) + return value; + else return null; + } + + return null; + } + } +} diff --git a/FunGame.Core/Api/Utility/ReflectionHelper.cs b/FunGame.Core/Api/Utility/ReflectionHelper.cs deleted file mode 100644 index d543492..0000000 --- a/FunGame.Core/Api/Utility/ReflectionHelper.cs +++ /dev/null @@ -1,86 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; - -namespace Milimoe.FunGame.Core.Api.Utility -{ - /// - /// Interface的定义已经搬至: - /// Milimoe.FunGame.Core.Library.Constant 中的 &InterfaceType 和 &InterfaceSet - /// - public class ReflectionHelper - { - /** - * 定义需要反射的DLL - */ - public const string FUNGAME_IMPL = "FunGame.Implement"; - - /** - * 无需二次修改的 - */ - public static string EXEDocPath = Environment.CurrentDirectory.ToString() + "\\"; // 程序目录 - public static string PluginDocPath = Environment.CurrentDirectory.ToString() + "\\plugins\\"; // 插件目录 - - //////////////////////////////////////////////////////////////////// - /////////////// * 下 面 是 工 具 类 实 现 * //////////////// - /////////////////////////////////////////////////////////////////// - - /** - * 定义反射变量 - */ - private Assembly? Assembly; - private Type? Type; - private MethodInfo? Method; - private object? Instance; - - /// - /// 获取FunGame.Implement.dll中接口的实现方法 - /// - /// 接口代号 - /// - private Type? GetFunGameImplementType(int Interface) - { - // 通过类名获取获取命名空间+类名称 - string ClassName = EnumHelper.GetImplementClassName(Interface); - List? Classes = null; - if (Assembly != null) - { - Classes = Assembly.GetTypes().Where(w => - w.Namespace == "Milimoe.FunGame.Core.Implement" && - w.Name.Contains(ClassName) - ).ToList(); - if (Classes != null && Classes.Count > 0) - return Classes[0]; - else return null; - } - else return null; - } - - /// - /// 公开方法:获取FunGame.Implement.DLL中指定方法的返回值 - /// - /// 接口代号 - /// 方法代号 - /// - public object? GetFunGameImplValue(int Interface, int Method) - { - Assembly = Assembly.LoadFile(EXEDocPath + FUNGAME_IMPL + ".dll"); - Type = GetFunGameImplementType(Interface); // 通过类名获取获取命名空间+类名称 - string MethodName = EnumHelper.GetImplementMethodName(Method); // 获取方法名 - if (Assembly != null && Type != null) this.Method = Type.GetMethod(MethodName); // 从Type中查找方法名 - else return null; - Instance = Assembly.CreateInstance(Type.Namespace + "." + Type.Name); - if (Instance != null && this.Method != null) - { - object? value = this.Method.Invoke(Instance, Array.Empty()); // 实例方法的调用 - if (value != null) - return value; - else return null; - } - else return null; - } - } -} diff --git a/FunGame.Core/Interface/Base/ISocket.cs b/FunGame.Core/Interface/Base/ISocket.cs deleted file mode 100644 index fec6584..0000000 --- a/FunGame.Core/Interface/Base/ISocket.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Milimoe.FunGame.Core.Interface.Base -{ - internal interface ISocket - { - internal int Send(); - internal int Read(); - } -} diff --git a/FunGame.Core/Library/Common/Network/Socket.cs b/FunGame.Core/Library/Common/Network/Socket.cs index c59a97d..c8b0086 100644 --- a/FunGame.Core/Library/Common/Network/Socket.cs +++ b/FunGame.Core/Library/Common/Network/Socket.cs @@ -15,11 +15,12 @@ namespace Milimoe.FunGame.Core.Library.Common.Network public class Socket { public System.Net.Sockets.Socket Instance { get; } + public int Runtime { get; } = (int)SocketRuntimeType.Client; public string ServerIP { get; } = ""; public int ServerPort { get; } = 0; public string ServerName { get; } = ""; public string ServerNotice { get; } = ""; - public int HeartBeatFaileds { get; } = 0; + public int HeartBeatFaileds { get; private set; } = 0; public bool Connected { get @@ -27,19 +28,26 @@ namespace Milimoe.FunGame.Core.Library.Common.Network return Instance != null && Instance.Connected; } } - + public bool Receiving { get; private set; } = false; + public bool SendingHeartBeat { get; private set; } = false; + + private Task? SendingHeartBeatTask; + private Task? ReceivingTask; + private Task? WaitHeartBeatReply; + private Socket(System.Net.Sockets.Socket Instance, string ServerIP, int ServerPort) { this.Instance = Instance; this.ServerIP= ServerIP; this.ServerPort = ServerPort; + this.StartSendingHeartBeat(); } public static Socket Connect(string IP, int Port = 22222) { System.Net.Sockets.Socket? socket = SocketManager.Connect(IP, Port); if (socket != null) return new Socket(socket, IP, Port); - else throw new Milimoe.FunGame.Core.Library.Exception.SystemError("创建Socket失败。"); + else throw new System.Exception("连接到服务器失败。"); } public SocketResult Send(SocketMessageType type, string msg = "") @@ -55,34 +63,86 @@ namespace Milimoe.FunGame.Core.Library.Common.Network return SocketResult.NotSent; } - private string[] Receive() + public string[] Receive() { - return SocketManager.Receive(); - } - - public void Run() - { - Task HeartBeatStream = Task.Factory.StartNew(StartSendHeartBeatStream); - Task StreamReader = Task.Factory.StartNew(StartReceive); - } - - private void StartReceive() - { - Thread.Sleep(100); - while (Connected) + string[] result = SocketManager.Receive(); + if (result[0] == SocketSet.HeartBeat) { - Receive(); + if (WaitHeartBeatReply != null && !WaitHeartBeatReply.IsCompleted) WaitHeartBeatReply.Wait(1); + HeartBeatFaileds = 0; } + return result; } - private void StartSendHeartBeatStream() + public void CheckHeartBeatFaileds() + { + if (HeartBeatFaileds >= 3) Close(); + } + + public void Close() + { + StopSendingHeartBeat(); + StopReceiving(); + Instance?.Close(); + } + + public void ResetHeartBeatFaileds() + { + HeartBeatFaileds = 0; + } + + public void StartReceiving(Task t) + { + Receiving = true; + ReceivingTask = t; + } + + private void StartSendingHeartBeat() + { + SendingHeartBeat = true; + SendingHeartBeatTask = Task.Factory.StartNew(SendHeartBeat); + } + + private void StopReceiving() + { + Receiving = false; + ReceivingTask?.Wait(1); + ReceivingTask = null; + } + + private void StopSendingHeartBeat() + { + SendingHeartBeat = false; + SendingHeartBeatTask?.Wait(1); + SendingHeartBeatTask = null; + } + + private void SendHeartBeat() { Thread.Sleep(100); while (Connected) { - Send(SocketMessageType.HeartBeat); // 发送心跳包 + if (!SendingHeartBeat) SendingHeartBeat= true; + // 发送心跳包 + if (Send(SocketMessageType.HeartBeat) == SocketResult.Success) + { + WaitHeartBeatReply = Task.Run(() => + { + Thread.Sleep(4000); + AddHeartBeatFaileds(); + }); + } + else AddHeartBeatFaileds(); Thread.Sleep(20000); } + SendingHeartBeat = false; + } + + private void AddHeartBeatFaileds() + { + // 超过三次没回应心跳,服务器连接失败。 + if (HeartBeatFaileds++ >= 3) + throw new System.Exception("ERROR:与服务器连接中断。"); } } } diff --git a/FunGame.Core/Library/Constant/ConstantSet.cs b/FunGame.Core/Library/Constant/ConstantSet.cs index 1f2abe3..13c7d28 100644 --- a/FunGame.Core/Library/Constant/ConstantSet.cs +++ b/FunGame.Core/Library/Constant/ConstantSet.cs @@ -8,13 +8,26 @@ namespace Milimoe.FunGame.Core.Library.Constant { public class InterfaceSet { - public const string IClient = "IClientImpl"; - public const string IServer = "IServerImpl"; + public class Type + { + public const string IClient = "IClientImpl"; + public const string IServer = "IServerImpl"; + } + + public class Method + { + public const string RemoteServerIP = "RemoteServerIP"; + public const string DBConnection = "DBConnection"; + public const string GetServerSettings = "GetServerSettings"; + } } public class SocketSet { + public static int MaxRetryTimes { get; } = 20; + public const string Unknown = "Unknown"; + public const string Connect = "Connect"; public const string GetNotice = "GetNotice"; public const string Login = "Login"; public const string CheckLogin = "CheckLogin"; @@ -22,4 +35,11 @@ namespace Milimoe.FunGame.Core.Library.Constant public const string Disconnect = "Disconnect"; public const string HeartBeat = "HeartBeat"; } + + public class ReflectionSet + { + public const string FUNGAME_IMPL = "FunGame.Implement"; + public static string EXEFolderPath { get; } = Environment.CurrentDirectory.ToString() + "\\"; // 程序目录 + public static string PluginFolderPath { get; } = Environment.CurrentDirectory.ToString() + "\\plugins\\"; // 插件目录 + } } diff --git a/FunGame.Core/Library/Constant/FunGameEnum.cs b/FunGame.Core/Library/Constant/FunGameEnum.cs index 35ceaf5..836ccd9 100644 --- a/FunGame.Core/Library/Constant/FunGameEnum.cs +++ b/FunGame.Core/Library/Constant/FunGameEnum.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; namespace Milimoe.FunGame.Core.Library.Constant { - public static class FunGameEnum + public class FunGameEnum { public enum FunGame { diff --git a/FunGame.Core/Library/Constant/MethodEnum.cs b/FunGame.Core/Library/Constant/MethodEnum.cs index 5dfa513..2fbc9b4 100644 --- a/FunGame.Core/Library/Constant/MethodEnum.cs +++ b/FunGame.Core/Library/Constant/MethodEnum.cs @@ -7,16 +7,6 @@ using System.Threading.Tasks; namespace Milimoe.FunGame.Core.Library.Constant { - public enum SocketHelperMethod - { - CreateSocket, - CloseSocket, - StartSocketHelper, - Login, - Logout, - Disconnect - } - public enum InterfaceMethod { RemoteServerIP, diff --git a/FunGame.Core/Library/Constant/ResultEnum.cs b/FunGame.Core/Library/Constant/ResultEnum.cs index 5c4d0ba..f0a7146 100644 --- a/FunGame.Core/Library/Constant/ResultEnum.cs +++ b/FunGame.Core/Library/Constant/ResultEnum.cs @@ -29,6 +29,14 @@ namespace Milimoe.FunGame.Core.Library.Constant NotReceived } + public enum ConnectResult + { + Success, + ConnectFailed, + CanNotConnect, + FindServerFailed + } + public enum ProxyResult { Success, diff --git a/FunGame.Core/Library/Constant/TypeEnum.cs b/FunGame.Core/Library/Constant/TypeEnum.cs index 544b4c0..f61ec0e 100644 --- a/FunGame.Core/Library/Constant/TypeEnum.cs +++ b/FunGame.Core/Library/Constant/TypeEnum.cs @@ -39,6 +39,7 @@ namespace Milimoe.FunGame.Core.Library.Constant public enum SocketMessageType { Unknown, + Connect, GetNotice, Login, CheckLogin, @@ -47,6 +48,12 @@ namespace Milimoe.FunGame.Core.Library.Constant HeartBeat } + public enum SocketRuntimeType + { + Client, + Server + } + public enum ErrorType { None, diff --git a/FunGame.Core/Library/Exception/ExceptionHelper.cs b/FunGame.Core/Library/Exception/ExceptionHelper.cs new file mode 100644 index 0000000..7abb131 --- /dev/null +++ b/FunGame.Core/Library/Exception/ExceptionHelper.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Milimoe.FunGame.Core.Entity; + +namespace Milimoe.FunGame.Core.Library.Exception +{ + public static class ExceptionHelper + { + public static string GetStackTrace(this System.Exception e) + { + if (e.Message != null && e.Message != "") + { + return $"ERROR: {e.Message}\n{e.StackTrace}"; + } + else + { + return $"ERROR: \n{e.StackTrace}"; + } + } + } +} diff --git a/FunGame.Core/Library/Exception/SystemError.cs b/FunGame.Core/Library/Exception/SystemError.cs index 9d775bc..ec7e5a4 100644 --- a/FunGame.Core/Library/Exception/SystemError.cs +++ b/FunGame.Core/Library/Exception/SystemError.cs @@ -13,16 +13,22 @@ namespace Milimoe.FunGame.Core.Library.Exception public new string StackTrace { get => base.StackTrace ?? ""; } - public SystemError() { } + private System.Exception e { get; } + + public SystemError() + { + e = new System.Exception(); + } public SystemError(string Name) { this.Name = Name; + e = new System.Exception(Name); } public string GetStackTrace() { - return Name + "\r\n" + StackTrace; + return e.GetStackTrace(); } } } diff --git a/FunGame.Core/Service/SocketManager.cs b/FunGame.Core/Service/SocketManager.cs index f54a34d..f7700e6 100644 --- a/FunGame.Core/Service/SocketManager.cs +++ b/FunGame.Core/Service/SocketManager.cs @@ -8,7 +8,6 @@ using System.Collections; using System.Net.Sockets; using System.Net; using Milimoe.FunGame.Core.Library.Constant; -using Milimoe.FunGame.Core.Api.Utility; namespace Milimoe.FunGame.Core.Service { @@ -33,7 +32,7 @@ namespace Milimoe.FunGame.Core.Service socket.Connect(ServerEndPoint); if (socket.Connected) { - SocketManager.Socket = socket; + Socket = socket; return socket; } } @@ -51,7 +50,7 @@ namespace Milimoe.FunGame.Core.Service { if (Socket != null) { - if (Socket.Send(Core.Library.Constant.General.DEFAULT_ENCODING.GetBytes(MakeMessage(type, msg))) > 0) + if (Socket.Send(General.DEFAULT_ENCODING.GetBytes(MakeMessage(type, msg))) > 0) { return SocketResult.Success; } @@ -62,7 +61,7 @@ namespace Milimoe.FunGame.Core.Service internal static string[] Receive() { - string[] result = new string[2]; + string[] result = new string[2] { GetTypeString(SocketMessageType.Unknown), "" }; if (Socket != null) { // 从服务器接收消息 @@ -70,7 +69,7 @@ namespace Milimoe.FunGame.Core.Service int length = Socket.Receive(buffer); if (length > 0) { - string msg = Core.Library.Constant.General.DEFAULT_ENCODING.GetString(buffer, 0, length); + string msg = General.DEFAULT_ENCODING.GetString(buffer, 0, length); result[0] = GetTypeString(GetType(msg)); result[1] = GetMessage(msg); return result; @@ -103,6 +102,7 @@ namespace Milimoe.FunGame.Core.Service { return type switch { + SocketMessageType.Connect => SocketSet.Connect, SocketMessageType.GetNotice => SocketSet.GetNotice, SocketMessageType.Login => SocketSet.Login, SocketMessageType.CheckLogin => SocketSet.CheckLogin, diff --git a/FunGame.Desktop/Controllers/UI/InventoryController.cs b/FunGame.Desktop/Controller/InventoryController.cs similarity index 100% rename from FunGame.Desktop/Controllers/UI/InventoryController.cs rename to FunGame.Desktop/Controller/InventoryController.cs diff --git a/FunGame.Desktop/Controllers/UI/LoginController.cs b/FunGame.Desktop/Controller/LoginController.cs similarity index 100% rename from FunGame.Desktop/Controllers/UI/LoginController.cs rename to FunGame.Desktop/Controller/LoginController.cs diff --git a/FunGame.Desktop/Controller/MainController.cs b/FunGame.Desktop/Controller/MainController.cs new file mode 100644 index 0000000..a0c49ef --- /dev/null +++ b/FunGame.Desktop/Controller/MainController.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Milimoe.FunGame.Core.Api.Utility; +using Milimoe.FunGame.Core.Library.Common.Event; +using Milimoe.FunGame.Core.Library.Constant; +using Milimoe.FunGame.Core.Library.Exception; +using Milimoe.FunGame.Desktop.Library.Component; +using Milimoe.FunGame.Desktop.Model; +using Milimoe.FunGame.Desktop.Others; +using Milimoe.FunGame.Desktop.UI; + +namespace Milimoe.FunGame.Desktop.Controller +{ + public class MainController + { + private MainModel MainModel; + + public MainController(Main Main) + { + MainModel = new MainModel(Main); + } + + public T Do(string DoType) + { + object result = new(); + switch(DoType) + { + case MainControllerSet.GetServerConnection: + result = MainModel.GetServerConnection(); + break; + case MainControllerSet.Connect: + result = MainModel.Connect(); + break; + case MainControllerSet.Connected: + if (MainModel.Socket is null) result = false; + else result = MainModel.Socket.Connected; + break; + case MainControllerSet.Disconnect: + MainModel.Disconnect(); + break; + case MainControllerSet.Disconnected: + MainModel.Disconnect(); + break; + case MainControllerSet.WaitConnectAndSetYellow: + break; + case MainControllerSet.WaitLoginAndSetYellow: + break; + case MainControllerSet.SetGreenAndPing: + break; + case MainControllerSet.SetGreen: + break; + case MainControllerSet.SetYellow: + break; + case MainControllerSet.SetRed: + break; + case MainControllerSet.SetUser: + break; + case MainControllerSet.LogOut: + result = MainModel.Logout(); + break; + case MainControllerSet.LogIn: + result = MainModel.Login(); + break; + case MainControllerSet.Close: + result = MainModel.Close(); + break; + default: + break; + } + return (T)result; + } + } +} diff --git a/FunGame.Desktop/Controllers/UI/RegisterController.cs b/FunGame.Desktop/Controller/RegisterController.cs similarity index 100% rename from FunGame.Desktop/Controllers/UI/RegisterController.cs rename to FunGame.Desktop/Controller/RegisterController.cs diff --git a/FunGame.Desktop/Controllers/UI/RoomSettingController.cs b/FunGame.Desktop/Controller/RoomSettingController.cs similarity index 100% rename from FunGame.Desktop/Controllers/UI/RoomSettingController.cs rename to FunGame.Desktop/Controller/RoomSettingController.cs diff --git a/FunGame.Desktop/Controllers/UI/StoreController.cs b/FunGame.Desktop/Controller/StoreController.cs similarity index 100% rename from FunGame.Desktop/Controllers/UI/StoreController.cs rename to FunGame.Desktop/Controller/StoreController.cs diff --git a/FunGame.Desktop/Controllers/UI/UserCenterController.cs b/FunGame.Desktop/Controller/UserCenterController.cs similarity index 100% rename from FunGame.Desktop/Controllers/UI/UserCenterController.cs rename to FunGame.Desktop/Controller/UserCenterController.cs diff --git a/FunGame.Desktop/Controllers/UI/MainController.cs b/FunGame.Desktop/Controllers/UI/MainController.cs deleted file mode 100644 index 7df247c..0000000 --- a/FunGame.Desktop/Controllers/UI/MainController.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Milimoe.FunGame.Desktop.Controller -{ - public class MainController - { - } -} diff --git a/FunGame.Desktop/Controllers/Utility/SocketController.cs b/FunGame.Desktop/Controllers/Utility/SocketController.cs deleted file mode 100644 index 12cb7f2..0000000 --- a/FunGame.Desktop/Controllers/Utility/SocketController.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Milimoe.FunGame.Desktop.Controller -{ - public class SocketController - { - - } -} diff --git a/FunGame.Desktop/FunGame.Desktop.csproj b/FunGame.Desktop/FunGame.Desktop.csproj index 0b9bd75..8860a00 100644 --- a/FunGame.Desktop/FunGame.Desktop.csproj +++ b/FunGame.Desktop/FunGame.Desktop.csproj @@ -6,7 +6,7 @@ enable true enable - Images\logo.ico + Image\logo.ico logo.ico Milimoe @@ -31,7 +31,7 @@ - + @@ -68,7 +68,7 @@ - + True \ diff --git a/FunGame.Desktop/Images/back.jpg b/FunGame.Desktop/Image/back.jpg similarity index 100% rename from FunGame.Desktop/Images/back.jpg rename to FunGame.Desktop/Image/back.jpg diff --git a/FunGame.Desktop/Images/exit.png b/FunGame.Desktop/Image/exit.png similarity index 100% rename from FunGame.Desktop/Images/exit.png rename to FunGame.Desktop/Image/exit.png diff --git a/FunGame.Desktop/Images/green.png b/FunGame.Desktop/Image/green.png similarity index 100% rename from FunGame.Desktop/Images/green.png rename to FunGame.Desktop/Image/green.png diff --git a/FunGame.Desktop/Image/logo.ico b/FunGame.Desktop/Image/logo.ico new file mode 100644 index 0000000..4082874 Binary files /dev/null and b/FunGame.Desktop/Image/logo.ico differ diff --git a/FunGame.Desktop/Images/min.png b/FunGame.Desktop/Image/min.png similarity index 100% rename from FunGame.Desktop/Images/min.png rename to FunGame.Desktop/Image/min.png diff --git a/FunGame.Desktop/Images/red.png b/FunGame.Desktop/Image/red.png similarity index 100% rename from FunGame.Desktop/Images/red.png rename to FunGame.Desktop/Image/red.png diff --git a/FunGame.Desktop/Images/send.png b/FunGame.Desktop/Image/send.png similarity index 100% rename from FunGame.Desktop/Images/send.png rename to FunGame.Desktop/Image/send.png diff --git a/FunGame.Desktop/Images/yellow.png b/FunGame.Desktop/Image/yellow.png similarity index 100% rename from FunGame.Desktop/Images/yellow.png rename to FunGame.Desktop/Image/yellow.png diff --git a/FunGame.Desktop/Entities/Component/ExitButton.Designer.cs b/FunGame.Desktop/Library/Component/ExitButton.Designer.cs similarity index 94% rename from FunGame.Desktop/Entities/Component/ExitButton.Designer.cs rename to FunGame.Desktop/Library/Component/ExitButton.Designer.cs index 92f30cb..73edb2d 100644 --- a/FunGame.Desktop/Entities/Component/ExitButton.Designer.cs +++ b/FunGame.Desktop/Library/Component/ExitButton.Designer.cs @@ -1,4 +1,4 @@ -namespace Milimoe.FunGame.Desktop.Entity.Component +namespace Milimoe.FunGame.Desktop.Library.Component { partial class ExitButton { diff --git a/FunGame.Desktop/Entities/Component/ExitButton.cs b/FunGame.Desktop/Library/Component/ExitButton.cs similarity index 98% rename from FunGame.Desktop/Entities/Component/ExitButton.cs rename to FunGame.Desktop/Library/Component/ExitButton.cs index 1e62000..11c0d3d 100644 --- a/FunGame.Desktop/Entities/Component/ExitButton.cs +++ b/FunGame.Desktop/Library/Component/ExitButton.cs @@ -6,7 +6,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace Milimoe.FunGame.Desktop.Entity.Component +namespace Milimoe.FunGame.Desktop.Library.Component { public partial class ExitButton : Button { diff --git a/FunGame.Desktop/Entities/Component/ShowMessage.Designer.cs b/FunGame.Desktop/Library/Component/ShowMessage.Designer.cs similarity index 96% rename from FunGame.Desktop/Entities/Component/ShowMessage.Designer.cs rename to FunGame.Desktop/Library/Component/ShowMessage.Designer.cs index a024b6e..837edad 100644 --- a/FunGame.Desktop/Entities/Component/ShowMessage.Designer.cs +++ b/FunGame.Desktop/Library/Component/ShowMessage.Designer.cs @@ -1,4 +1,4 @@ -namespace Milimoe.FunGame.Desktop.Entity.Component +namespace Milimoe.FunGame.Desktop.Library.Component { partial class ShowMessage { @@ -32,11 +32,11 @@ System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ShowMessage)); this.MsgText = new System.Windows.Forms.Label(); this.LeftButton = new System.Windows.Forms.Button(); - this.Exit = new FunGame.Desktop.Entity.Component.ExitButton(this.components); + this.Exit = new FunGame.Desktop.Library.Component.ExitButton(this.components); this.RightButton = new System.Windows.Forms.Button(); this.MidButton = new System.Windows.Forms.Button(); this.Title = new System.Windows.Forms.Label(); - this.TransparentRect = new FunGame.Desktop.Entity.Component.TransparentRect(); + this.TransparentRect = new FunGame.Desktop.Library.Component.TransparentRect(); this.InputButton = new System.Windows.Forms.Button(); this.InputText = new System.Windows.Forms.TextBox(); this.TransparentRect.SuspendLayout(); @@ -133,7 +133,7 @@ this.TransparentRect.Name = "TransparentRect"; this.TransparentRect.Opacity = 125; this.TransparentRect.Radius = 20; - this.TransparentRect.ShapeBorderStyle = FunGame.Desktop.Entity.Component.TransparentRect.ShapeBorderStyles.ShapeBSNone; + this.TransparentRect.ShapeBorderStyle = FunGame.Desktop.Library.Component.TransparentRect.ShapeBorderStyles.ShapeBSNone; this.TransparentRect.Size = new System.Drawing.Size(235, 170); this.TransparentRect.TabIndex = 103; this.TransparentRect.TabStop = false; diff --git a/FunGame.Desktop/Entities/Component/ShowMessage.cs b/FunGame.Desktop/Library/Component/ShowMessage.cs similarity index 99% rename from FunGame.Desktop/Entities/Component/ShowMessage.cs rename to FunGame.Desktop/Library/Component/ShowMessage.cs index 7df601e..49cd00e 100644 --- a/FunGame.Desktop/Entities/Component/ShowMessage.cs +++ b/FunGame.Desktop/Library/Component/ShowMessage.cs @@ -9,7 +9,7 @@ using System.Threading.Tasks; using System.Windows.Forms; using Milimoe.FunGame.Core.Library.Constant; -namespace Milimoe.FunGame.Desktop.Entity.Component +namespace Milimoe.FunGame.Desktop.Library.Component { public partial class ShowMessage : Form { diff --git a/FunGame.Desktop/Entities/Component/ShowMessage.resx b/FunGame.Desktop/Library/Component/ShowMessage.resx similarity index 100% rename from FunGame.Desktop/Entities/Component/ShowMessage.resx rename to FunGame.Desktop/Library/Component/ShowMessage.resx diff --git a/FunGame.Desktop/Entities/Component/TextArea.Designer.cs b/FunGame.Desktop/Library/Component/TextArea.Designer.cs similarity index 95% rename from FunGame.Desktop/Entities/Component/TextArea.Designer.cs rename to FunGame.Desktop/Library/Component/TextArea.Designer.cs index 407c314..d1079ca 100644 --- a/FunGame.Desktop/Entities/Component/TextArea.Designer.cs +++ b/FunGame.Desktop/Library/Component/TextArea.Designer.cs @@ -1,4 +1,4 @@ -namespace FunGame.Desktop.Models.Component +namespace Milimoe.FunGame.Desktop.Library.Component { partial class TextArea : RichTextBox { diff --git a/FunGame.Desktop/Entities/Component/TextArea.cs b/FunGame.Desktop/Library/Component/TextArea.cs similarity index 98% rename from FunGame.Desktop/Entities/Component/TextArea.cs rename to FunGame.Desktop/Library/Component/TextArea.cs index a9bfe1a..94333d2 100644 --- a/FunGame.Desktop/Entities/Component/TextArea.cs +++ b/FunGame.Desktop/Library/Component/TextArea.cs @@ -8,7 +8,7 @@ using System.Text; using System.Threading.Tasks; using System.Windows.Forms; -namespace Milimoe.FunGame.Desktop.Entity.Component +namespace Milimoe.FunGame.Desktop.Library.Component { [ToolboxBitmap(typeof(TextBox))] partial class TextArea : RichTextBox diff --git a/FunGame.Desktop/Entities/Component/TextArea.resx b/FunGame.Desktop/Library/Component/TextArea.resx similarity index 100% rename from FunGame.Desktop/Entities/Component/TextArea.resx rename to FunGame.Desktop/Library/Component/TextArea.resx diff --git a/FunGame.Desktop/Entities/Component/TransparentRect.Designer.cs b/FunGame.Desktop/Library/Component/TransparentRect.Designer.cs similarity index 95% rename from FunGame.Desktop/Entities/Component/TransparentRect.Designer.cs rename to FunGame.Desktop/Library/Component/TransparentRect.Designer.cs index 0c9168c..38596e3 100644 --- a/FunGame.Desktop/Entities/Component/TransparentRect.Designer.cs +++ b/FunGame.Desktop/Library/Component/TransparentRect.Designer.cs @@ -1,4 +1,4 @@ -namespace Milimoe.FunGame.Desktop.Entity.Component +namespace Milimoe.FunGame.Desktop.Library.Component { partial class TransparentRect { diff --git a/FunGame.Desktop/Entities/Component/TransparentRect.cs b/FunGame.Desktop/Library/Component/TransparentRect.cs similarity index 98% rename from FunGame.Desktop/Entities/Component/TransparentRect.cs rename to FunGame.Desktop/Library/Component/TransparentRect.cs index 23fd3a7..22645f9 100644 --- a/FunGame.Desktop/Entities/Component/TransparentRect.cs +++ b/FunGame.Desktop/Library/Component/TransparentRect.cs @@ -7,7 +7,7 @@ using System.Text; using System.Threading.Tasks; using System.Windows.Forms; -namespace Milimoe.FunGame.Desktop.Entity.Component +namespace Milimoe.FunGame.Desktop.Library.Component { partial class TransparentRect : GroupBox { diff --git a/FunGame.Desktop/Models/UI/InventoryModel.cs b/FunGame.Desktop/Model/InventoryModel.cs similarity index 100% rename from FunGame.Desktop/Models/UI/InventoryModel.cs rename to FunGame.Desktop/Model/InventoryModel.cs diff --git a/FunGame.Desktop/Models/UI/LoginModel.cs b/FunGame.Desktop/Model/LoginModel.cs similarity index 100% rename from FunGame.Desktop/Models/UI/LoginModel.cs rename to FunGame.Desktop/Model/LoginModel.cs diff --git a/FunGame.Desktop/Model/MainModel.cs b/FunGame.Desktop/Model/MainModel.cs new file mode 100644 index 0000000..4b475d1 --- /dev/null +++ b/FunGame.Desktop/Model/MainModel.cs @@ -0,0 +1,219 @@ +using Milimoe.FunGame.Core.Api.Utility; +using Milimoe.FunGame.Core.Library.Common.Event; +using Milimoe.FunGame.Core.Library.Constant; +using Milimoe.FunGame.Core.Library.Exception; +using Milimoe.FunGame.Desktop.Library.Component; +using Milimoe.FunGame.Desktop.Others; +using Milimoe.FunGame.Desktop.UI; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Milimoe.FunGame.Desktop.Model +{ + public class MainModel + { + public Core.Library.Common.Network.Socket? Socket { get; private set; } + public Core.Library.Common.Event.ConnectEvent ConnectEvent { get; } = new ConnectEvent(); + public Main Main { get; } + + private int CurrentRetryTimes = -1; + private int MaxRetryTimes { get; } = SocketSet.MaxRetryTimes; + private Task? ReceivingTask; + + public MainModel(Main main) + { + Main = main; + } + + public bool Login() + { + return false; + } + + public bool Logout() + { + return false; + } + + + public void Disconnect() + { + + } + + public bool 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) + { + Others.Constant.SERVER_IPADRESS = s[0]; + Others.Constant.SERVER_PORT = Convert.ToInt32(s[1]); + if (Connect() == ConnectResult.Success) return true; // 连接服务器 + } + } + else + { + ShowMessage.ErrorMessage("查找可用的服务器失败!"); + throw new Exception("查找可用的服务器失败,请重启FunGame。"); + } + } + catch (Exception e) + { + Main?.GetMessage(e.GetStackTrace(), false); + } + + return false; + } + + public ConnectResult Connect() + { + try + { + if (Others.Constant.SERVER_IPADRESS == "" || Others.Constant.SERVER_PORT <= 0) + { + ShowMessage.ErrorMessage("查找可用的服务器失败!"); + return ConnectResult.FindServerFailed; + } + while (true) + { + if (!Others.Config.FunGame_isConnected) + { + CurrentRetryTimes++; + if (CurrentRetryTimes == 0) Main?.GetMessage("开始连接服务器...", true, TimeType.General); + else Main?.GetMessage("第" + CurrentRetryTimes + "次重试连接服务器..."); + // 超过重连次数上限 + if (CurrentRetryTimes + 1 > MaxRetryTimes) + { + throw new Exception("无法连接至服务器,请检查网络并重启游戏再试。"); + } + // 与服务器建立连接 + Socket?.Close(); + Others.Config.FunGame_isRetrying = true; + Socket = Core.Library.Common.Network.Socket.Connect(Others.Constant.SERVER_IPADRESS, Others.Constant.SERVER_PORT); + if (Socket != null && Socket.Connected) + { + // 发送连接请求 + if (Socket.Send(SocketMessageType.Connect) == SocketResult.Success) + { + // 接收连接回应 + if (Receiving() == SocketMessageType.Connect) + { + Main?.UpdateUI(MainControllerSet.Connected); + return ConnectResult.Success; + } + } + Socket?.Close(); + return ConnectResult.CanNotConnect; + } + } + } + } + catch (Exception e) + { + Main?.GetMessage(e.GetStackTrace(), false); + } + + return ConnectResult.ConnectFailed; + } + + public void StartReceiving() + { + ReceivingTask = Task.Factory.StartNew(() => + { + Thread.Sleep(100); + while (Socket != null && Socket.Connected) + { + Receiving(); + } + }); + Socket?.StartReceiving(ReceivingTask); + } + + public bool Close() + { + try + { + if (Socket != null) + { + Socket.Close(); + Socket = null; + } + if (ReceivingTask != null && !ReceivingTask.IsCompleted) + { + ReceivingTask.Wait(1); + ReceivingTask = null; + } + } + catch (Exception e) + { + Main.GetMessage(e.GetStackTrace(), false); + return false; + } + return true; + } + + private string[] GetServerMessage() + { + if (Socket != null && Socket.Connected) + { + return Socket.Receive(); + } + return new string[2] { SocketSet.Unknown, "" }; + } + + private SocketMessageType Receiving() + { + if (Socket is null) return SocketMessageType.Unknown; + SocketMessageType result = SocketMessageType.Unknown; + try + { + string[] ServerMessage = GetServerMessage(); + string type = ServerMessage[0]; + string msg = ServerMessage[1]; + switch (type) + { + case SocketSet.GetNotice: + result = SocketMessageType.GetNotice; + Config.FunGame_Notice = msg; + break; + case SocketSet.Connect: + result = SocketMessageType.Connect; + string[] strings = msg.Split(';'); + string ServerName = strings[0]; + string ServerNotice = strings[1]; + Config.FunGame_ServerName = ServerName; + Config.FunGame_Notice = ServerNotice; + Main?.GetMessage($"已连接服务器:{ServerName}。\n\n********** 服务器公告 **********\n\n{ServerNotice}\n\n"); + // 设置等待登录的黄灯 + Main?.UpdateUI(MainControllerSet.WaitLoginAndSetYellow); + break; + case SocketSet.Login: + break; + case SocketSet.CheckLogin: + break; + case SocketSet.Logout: + break; + case SocketSet.Disconnect: + break; + case SocketSet.Unknown: + default: + break; + } + } + catch (Exception e) + { + Main?.GetMessage(e.GetStackTrace(), false); + } + return result; + } + } +} diff --git a/FunGame.Desktop/Models/UI/RegisterModel.cs b/FunGame.Desktop/Model/RegisterModel.cs similarity index 100% rename from FunGame.Desktop/Models/UI/RegisterModel.cs rename to FunGame.Desktop/Model/RegisterModel.cs diff --git a/FunGame.Desktop/Models/UI/RoomSettingModel.cs b/FunGame.Desktop/Model/RoomSettingModel.cs similarity index 100% rename from FunGame.Desktop/Models/UI/RoomSettingModel.cs rename to FunGame.Desktop/Model/RoomSettingModel.cs diff --git a/FunGame.Desktop/Models/UI/StoreModel.cs b/FunGame.Desktop/Model/StoreModel.cs similarity index 100% rename from FunGame.Desktop/Models/UI/StoreModel.cs rename to FunGame.Desktop/Model/StoreModel.cs diff --git a/FunGame.Desktop/Models/UI/UserCenterModel.cs b/FunGame.Desktop/Model/UserCenterModel.cs similarity index 100% rename from FunGame.Desktop/Models/UI/UserCenterModel.cs rename to FunGame.Desktop/Model/UserCenterModel.cs diff --git a/FunGame.Desktop/Models/UI/MainModel.cs b/FunGame.Desktop/Models/UI/MainModel.cs deleted file mode 100644 index 7d27e9d..0000000 --- a/FunGame.Desktop/Models/UI/MainModel.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Milimoe.FunGame.Desktop.Model -{ - public class MainModel - { - } -} diff --git a/FunGame.Desktop/Models/Utility/SocketModel.cs b/FunGame.Desktop/Models/Utility/SocketModel.cs deleted file mode 100644 index 41567b2..0000000 --- a/FunGame.Desktop/Models/Utility/SocketModel.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Milimoe.FunGame.Desktop.Model -{ - public class SocketModel - { - - } -} diff --git a/FunGame.Desktop/Others/Config.cs b/FunGame.Desktop/Others/Config.cs index f43d9b2..44dfbf2 100644 --- a/FunGame.Desktop/Others/Config.cs +++ b/FunGame.Desktop/Others/Config.cs @@ -21,6 +21,7 @@ namespace Milimoe.FunGame.Desktop.Others public static bool Match_Team { get; set; } = false; // 团队模式选项 public static bool Match_HasPass { get; set; } = false; // 密码房间选项 public static string FunGame_Roomid { get; set; } = "-1"; // 房间号 + public static string FunGame_ServerName { get; set; } = ""; // 服务器名称 public static string FunGame_Notice { get; set; } = ""; // 公告 } } diff --git a/FunGame.Desktop/Others/Constant.cs b/FunGame.Desktop/Others/Constant.cs index 5547575..8f58196 100644 --- a/FunGame.Desktop/Others/Constant.cs +++ b/FunGame.Desktop/Others/Constant.cs @@ -9,30 +9,31 @@ using Milimoe.FunGame.Core.Library.Constant; namespace Milimoe.FunGame.Desktop.Others { - public static class Constant + public class MainControllerSet + { + public const string SetGreen = ".set green"; + public const string SetGreenAndPing = ".set greenandping"; + public const string SetRed = ".set red"; + public const string SetYellow = ".set yellow"; + public const string WaitConnectAndSetYellow = ".waitconnect .set yellow"; + public const string WaitLoginAndSetYellow = ".waitlogin .set yellow"; + public const string Disconnect = ".disconnect"; + public const string Disconnected = ".disconnected"; + public const string LogOut = ".logout"; + public const string LogIn = ".login"; + public const string SetUser = ".set user"; + public const string Connected = ".connected"; + public const string Connect = ".connect"; + public const string GetServerConnection = ".getserverconnection"; + public const string Close = ".close"; + } + + public class Constant { /** * Game Configs */ - public static FunGameEnum.FunGame FunGameType { get; } = FunGameEnum.FunGame.FunGame_Desktop; - public static ReflectionHelper ReflectionHelper { get; } = new(); - - /** - * SocketHelper Configs - */ - public const string SocketHelper_SetGreen = "-SocketHelper .set green"; - public const string SocketHelper_SetGreenAndPing = "-SocketHelper .set greenandping"; - public const string SocketHelper_SetRed = "-SocketHelper .set red"; - public const string SocketHelper_SetYellow = "-SocketHelper .set yellow"; - public const string SocketHelper_WaitConnectAndSetYellow = "-SocketHelper .waitconnect .set yellow"; - public const string SocketHelper_WaitLoginAndSetYellow = "-SocketHelper .waitlogin .set yellow"; - public const string SocketHelper_Disconnect = "-SocketHelper .disconnect"; - public const string SocketHelper_Disconnected = "-SocketHelper .disconnected"; - public const string SocketHelper_LogOut = "-SocketHelper .logout"; - public const string SocketHelper_GetUser = "-SocketHelper .get user"; - public const string SocketHelper_SetUser = "-SocketHelper .set user"; - public const string SocketHelper_SetNotice = "-SocketHelper .set notice"; - public static int SocketHelper_HeartBeatFaileds { get; set; } = 0; + public static int FunGameType { get; } = (int)FunGameEnum.FunGame.FunGame_Desktop; /** * Socket Configs diff --git a/FunGame.Desktop/Properties/Resources.Designer.cs b/FunGame.Desktop/Properties/Resources.Designer.cs index 0fce135..8f425c3 100644 --- a/FunGame.Desktop/Properties/Resources.Designer.cs +++ b/FunGame.Desktop/Properties/Resources.Designer.cs @@ -91,12 +91,22 @@ namespace Milimoe.FunGame.Desktop.Properties { } /// - /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// 查找 System.Byte[] 类型的本地化资源。 /// - internal static System.Drawing.Bitmap logo { + internal static byte[] LanaPixel { + get { + object obj = ResourceManager.GetObject("LanaPixel", resourceCulture); + return ((byte[])(obj)); + } + } + + /// + /// 查找类似于 (图标) 的 System.Drawing.Icon 类型的本地化资源。 + /// + internal static System.Drawing.Icon logo { get { object obj = ResourceManager.GetObject("logo", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); + return ((System.Drawing.Icon)(obj)); } } diff --git a/FunGame.Desktop/Properties/Resources.resx b/FunGame.Desktop/Properties/Resources.resx index 9abaf8d..f59cfd2 100644 --- a/FunGame.Desktop/Properties/Resources.resx +++ b/FunGame.Desktop/Properties/Resources.resx @@ -118,28 +118,31 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + ..\Image\back.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + - ..\images\exit.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\images\red.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\images\send.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + ..\Image\exit.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - ..\images\green.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + ..\Image\green.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - ..\images\back.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\images\min.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + ..\Resources\LanaPixel.ttf;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - ..\Images\logo.ico;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + ..\Image\logo.ico;System.Drawing.Icon, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Image\min.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Image\red.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Image\send.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - ..\Images\yellow.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + ..\Image\yellow.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a \ No newline at end of file diff --git a/FunGame.Desktop/Resources/LanaPixel.ttf b/FunGame.Desktop/Resources/LanaPixel.ttf new file mode 100644 index 0000000..ee30bb8 Binary files /dev/null and b/FunGame.Desktop/Resources/LanaPixel.ttf differ diff --git a/FunGame.Desktop/UI/Main/Main.Designer.cs b/FunGame.Desktop/UI/Main/Main.Designer.cs index 4c45e6b..97cf0e4 100644 --- a/FunGame.Desktop/UI/Main/Main.Designer.cs +++ b/FunGame.Desktop/UI/Main/Main.Designer.cs @@ -1,4 +1,4 @@ -using Milimoe.FunGame.Desktop.Entity.Component; +using Milimoe.FunGame.Desktop.Library.Component; using Milimoe.FunGame.Desktop.Others; namespace Milimoe.FunGame.Desktop.UI @@ -33,7 +33,7 @@ namespace Milimoe.FunGame.Desktop.UI { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Main)); - this.Exit = new FunGame.Desktop.Entity.Component.ExitButton(this.components); + this.Exit = new FunGame.Desktop.Library.Component.ExitButton(this.components); this.Title = new System.Windows.Forms.Label(); this.MinForm = new System.Windows.Forms.Button(); this.Connection = new System.Windows.Forms.Label(); @@ -55,10 +55,10 @@ namespace Milimoe.FunGame.Desktop.UI this.QueryRoom = new System.Windows.Forms.Button(); this.RoomList = new System.Windows.Forms.ListBox(); this.Notice = new System.Windows.Forms.GroupBox(); - this.NoticeText = new FunGame.Desktop.Entity.Component.TextArea(); + this.NoticeText = new FunGame.Desktop.Library.Component.TextArea(); this.InfoBox = new System.Windows.Forms.GroupBox(); - this.TransparentRectControl = new FunGame.Desktop.Entity.Component.TransparentRect(); - this.GameInfo = new FunGame.Desktop.Entity.Component.TextArea(); + this.TransparentRectControl = new FunGame.Desktop.Library.Component.TransparentRect(); + this.GameInfo = new FunGame.Desktop.Library.Component.TextArea(); this.QuitRoom = new System.Windows.Forms.Button(); this.CreateRoom = new System.Windows.Forms.Button(); this.Logout = new System.Windows.Forms.Button(); @@ -433,7 +433,7 @@ namespace Milimoe.FunGame.Desktop.UI this.TransparentRectControl.Name = "TransparentRectControl"; this.TransparentRectControl.Opacity = 125; this.TransparentRectControl.Radius = 20; - this.TransparentRectControl.ShapeBorderStyle = Milimoe.FunGame.Desktop.Entity.Component.TransparentRect.ShapeBorderStyles.ShapeBSNone; + this.TransparentRectControl.ShapeBorderStyle = Milimoe.FunGame.Desktop.Library.Component.TransparentRect.ShapeBorderStyles.ShapeBSNone; this.TransparentRectControl.Size = new System.Drawing.Size(464, 343); this.TransparentRectControl.TabIndex = 2; this.TransparentRectControl.TabStop = false; @@ -637,8 +637,8 @@ namespace Milimoe.FunGame.Desktop.UI private Button Store; private LinkLabel Copyright; private Button StopMatch; - private Entity.Component.TextArea GameInfo; - private Entity.Component.TextArea NoticeText; - private Entity.Component.TransparentRect TransparentRectControl; + private Library.Component.TextArea GameInfo; + private Library.Component.TextArea NoticeText; + private Library.Component.TransparentRect TransparentRectControl; } } \ No newline at end of file diff --git a/FunGame.Desktop/UI/Main/Main.cs b/FunGame.Desktop/UI/Main/Main.cs index 256da08..73d30ca 100644 --- a/FunGame.Desktop/UI/Main/Main.cs +++ b/FunGame.Desktop/UI/Main/Main.cs @@ -5,11 +5,15 @@ using System.Windows.Forms; using System.Net.NetworkInformation; using System.Text; using Milimoe.FunGame.Core.Api.Utility; -using Milimoe.FunGame.Core.Entity; -using Milimoe.FunGame.Desktop.Entity.Component; +using Milimoe.FunGame.Desktop.Library.Component; using Milimoe.FunGame.Desktop.Others; using Milimoe.FunGame.Desktop.Utils; using Milimoe.FunGame.Core.Library.Constant; +using Milimoe.FunGame.Desktop.Controller; +using Milimoe.FunGame.Core.Library.Exception; +using System; +using Milimoe.FunGame.Core.Entity; +using Milimoe.FunGame.Desktop.Model; namespace Milimoe.FunGame.Desktop.UI { @@ -29,7 +33,8 @@ namespace Milimoe.FunGame.Desktop.UI * 定义全局对象 */ private Task? MatchFunGame = null; // 匹配线程 - private SocketHelper? SocketHelper = null; // ScoketHelper + //private MainModel? MainModel = null; + private MainController? MainController = null; /** * 定义委托 @@ -37,8 +42,6 @@ namespace Milimoe.FunGame.Desktop.UI */ Action? StartMatch_Action = null; Action? CreateRoom_Action = null; - Action? SocketHelper_Action = null; - Action? Main_Action = null; public Main() { @@ -55,7 +58,25 @@ namespace Milimoe.FunGame.Desktop.UI SetRoomid("-1"); // 房间号初始化 ShowFunGameInfo(); // 显示FunGame信息 GetFunGameConfig(); // 获取FunGame配置 - if (Others.Config.FunGame_isAutoConnect) GetServerConnection(); // 开始连接服务器 + // 创建一个UI控制器 + MainController = new MainController(this); + Task.Factory.StartNew(() => + { + while (true) + { + if (IsHandleCreated) + { + break; + } + } + // 窗口句柄创建后,进行委托 + void action() + { + if (Config.FunGame_isAutoConnect) + MainController.Do(MainControllerSet.Connected); + } + InvokeUpdateUI(action); + }); } #endregion @@ -63,222 +84,185 @@ namespace Milimoe.FunGame.Desktop.UI #region 公有方法 /// - /// 提供公共方法给SocketHelper + /// 提供公共方法给Controller更新UI /// - /// - /// - /// - /// - public object? GetMessage(SocketHelper SocketHelper, string? msg, bool needTime = false, object[]? objs = null) + /// + /// + /// + /// + public void UpdateUI(string? updatetype, bool time = false, TimeType timetype = TimeType.TimeOnly, object[]? objs = null) { - try + void action() { - if (msg != null) + try { - switch (msg) + if (updatetype != null) { - case Others.Constant.SocketHelper_SetGreen: - Others.Config.FunGame_isRetrying = false; - SocketHelper_Action = (main) => - { + switch (updatetype) + { + case Others.MainControllerSet.SetGreen: + Others.Config.FunGame_isRetrying = false; SetServerStatusLight((int)LightType.Green); SetButtonEnableIfLogon(true, ClientState.Online); - }; - if (InvokeRequired) - BeginInvoke(SocketHelper_Action, this); - else - SocketHelper_Action(this); - Others.Config.FunGame_isConnected = true; - NOW_CONNECTEDRETRY = 0; - break; - case Others.Constant.SocketHelper_SetGreenAndPing: - Others.Config.FunGame_isRetrying = false; - SocketHelper_Action = (main) => - { + Others.Config.FunGame_isConnected = true; + NOW_CONNECTEDRETRY = 0; + break; + + case Others.MainControllerSet.SetGreenAndPing: + Others.Config.FunGame_isRetrying = false; SetServerStatusLight((int)LightType.Green, ping: NetworkUtility.GetServerPing(Others.Constant.SERVER_IPADRESS)); SetButtonEnableIfLogon(true, ClientState.Online); - }; - if (InvokeRequired) - BeginInvoke(SocketHelper_Action, this); - else - SocketHelper_Action(this); - Others.Config.FunGame_isConnected = true; - NOW_CONNECTEDRETRY = 0; - break; - case Others.Constant.SocketHelper_SetYellow: - Others.Config.FunGame_isRetrying = false; - SocketHelper_Action = (main) => - { + Others.Config.FunGame_isConnected = true; + NOW_CONNECTEDRETRY = 0; + break; + + case Others.MainControllerSet.SetYellow: + Others.Config.FunGame_isRetrying = false; SetServerStatusLight((int)LightType.Yellow); SetButtonEnableIfLogon(false, ClientState.WaitConnect); - }; - if (InvokeRequired) - BeginInvoke(SocketHelper_Action, this); - else - SocketHelper_Action(this); - Others.Config.FunGame_isConnected = true; - NOW_CONNECTEDRETRY = 0; - break; - case Others.Constant.SocketHelper_WaitConnectAndSetYellow: - Others.Config.FunGame_isRetrying = false; - SocketHelper_Action = (main) => - { + Others.Config.FunGame_isConnected = true; + NOW_CONNECTEDRETRY = 0; + break; + + case Others.MainControllerSet.WaitConnectAndSetYellow: + Others.Config.FunGame_isRetrying = false; SetServerStatusLight((int)LightType.Yellow); SetButtonEnableIfLogon(false, ClientState.WaitConnect); - }; - if (InvokeRequired) - BeginInvoke(SocketHelper_Action, this); - else - SocketHelper_Action(this); - Others.Config.FunGame_isConnected = true; - NOW_CONNECTEDRETRY = 0; - if (SocketHelper != null && Others.Config.FunGame_isAutoConnect) - { - // 自动连接服务器 - GetServerConnection(); - } - break; - case Others.Constant.SocketHelper_WaitLoginAndSetYellow: - Others.Config.FunGame_isRetrying = false; - SocketHelper_Action = (main) => - { + Others.Config.FunGame_isConnected = true; + NOW_CONNECTEDRETRY = 0; + if (MainController != null && Others.Config.FunGame_isAutoConnect) + { + // 自动连接服务器 + MainController.Do(MainControllerSet.Connected); + } + break; + + case Others.MainControllerSet.WaitLoginAndSetYellow: + Others.Config.FunGame_isRetrying = false; SetServerStatusLight((int)LightType.Yellow, true); SetButtonEnableIfLogon(false, ClientState.WaitLogin); - }; - if (InvokeRequired) - BeginInvoke(SocketHelper_Action, this); - else - SocketHelper_Action(this); - Others.Config.FunGame_isConnected = true; - NOW_CONNECTEDRETRY = 0; - break; - case Others.Constant.SocketHelper_SetRed: - SocketHelper_Action = (main) => - { + Others.Config.FunGame_isConnected = true; + NOW_CONNECTEDRETRY = 0; + break; + + case Others.MainControllerSet.SetRed: SetServerStatusLight((int)LightType.Red); SetButtonEnableIfLogon(false, ClientState.WaitConnect); - }; - if (InvokeRequired) - BeginInvoke(SocketHelper_Action, this); - else - SocketHelper_Action(this); - Others.Config.FunGame_isConnected = false; - break; - case Others.Constant.SocketHelper_Disconnected: - Others.Config.FunGame_isRetrying = false; - Others.Config.FunGame_isConnected = false; - SocketHelper_Action = (main) => - { + Others.Config.FunGame_isConnected = false; + break; + + case Others.MainControllerSet.Disconnected: + Others.Config.FunGame_isRetrying = false; + Others.Config.FunGame_isConnected = false; SetServerStatusLight((int)LightType.Red); SetButtonEnableIfLogon(false, ClientState.WaitConnect); LogoutAccount(); - }; - if (InvokeRequired) - BeginInvoke(SocketHelper_Action, this); - else - SocketHelper_Action(this); - if (Others.Config.FunGame_isAutoRetry && NOW_CONNECTEDRETRY <= MAX_CONNECTEDRETRY) - { - Task.Run(() => + if (Others.Config.FunGame_isAutoRetry && NOW_CONNECTEDRETRY <= MAX_CONNECTEDRETRY) { - Thread.Sleep(5000); - if (Others.Config.FunGame_isAutoRetry) Connect(); // 再次判断是否开启自动重连 - }); - if (needTime) - throw new Exception(DateTimeUtility.GetNowShortTime() + "\nERROR:连接服务器失败,5秒后自动尝试重连。"); - else - throw new Exception("ERROR:连接服务器失败,5秒后自动尝试重连。"); - } - else - if (needTime) - throw new Exception(DateTimeUtility.GetNowShortTime() + "\nERROR:无法连接至服务器,请检查你的网络连接。"); - else - throw new Exception("ERROR:无法连接至服务器,请检查你的网络连接。"); - case Others.Constant.SocketHelper_Disconnect: - Others.Config.FunGame_isAutoRetry = false; - Others.Config.FunGame_isRetrying = false; - Others.Config.FunGame_isAutoConnect = false; - Others.Config.FunGame_isAutoLogin = false; - Others.Config.FunGame_isConnected = false; - SocketHelper_Action = (main) => - { - SetServerStatusLight((int)LightType.Yellow); - SetButtonEnableIfLogon(false, ClientState.WaitConnect); - LogoutAccount(); - }; - if (InvokeRequired) - BeginInvoke(SocketHelper_Action, this); - else - SocketHelper_Action(this); - break; - case Others.Constant.SocketHelper_LogOut: - Others.Config.FunGame_isRetrying = false; - Others.Config.FunGame_isConnected = false; - Others.Config.FunGame_isAutoLogin = false; - SocketHelper_Action = (main) => - { - SetServerStatusLight((int)LightType.Yellow); - SetButtonEnableIfLogon(false, ClientState.WaitConnect); - LogoutAccount(); - }; - if (InvokeRequired) - BeginInvoke(SocketHelper_Action, this); - else - SocketHelper_Action(this); - if (Others.Config.FunGame_isAutoConnect) - { - NOW_CONNECTEDRETRY = -1; - Task.Run(() => - { - Thread.Sleep(1000); - Connect(); - }); - } - break; - case Others.Constant.SocketHelper_GetUser: - if (Usercfg.LoginUser != null) - return Usercfg.LoginUser; - return null; - case Others.Constant.SocketHelper_SetUser: - if (objs != null && objs.Length > 1) - { - if (InvokeRequired) - BeginInvoke(SetLoginUser, objs); - else - SetLoginUser(objs); - } - return null; - case Others.Constant.SocketHelper_SetNotice: - Action action = () => - { - NoticeText.Text = Others.Config.FunGame_Notice; - if (SocketHelper != null && Others.Config.FunGame_isAutoLogin) - { - // 自动登录 - SocketHelper.GetSocketHelperMethod((int)SocketHelperMethod.Login); + Task.Run(() => + { + Thread.Sleep(5000); + if (Others.Config.FunGame_isAutoRetry) MainController?.Do(MainControllerSet.Connect); // 再次判断是否开启自动重连 + }); + if (time) + throw new Exception(DateTimeUtility.GetNowShortTime() + "\nERROR:连接服务器失败,5秒后自动尝试重连。"); + else + throw new Exception("ERROR:连接服务器失败,5秒后自动尝试重连。"); } - }; - if (InvokeRequired) - BeginInvoke(action); - else - action(); - return null; - default: - if (needTime) - WritelnGameInfo(SocketHelper, DateTimeUtility.GetNowShortTime() + msg); - else - WritelnGameInfo(SocketHelper, msg); - return null; + else + if (time) + throw new Exception(DateTimeUtility.GetNowShortTime() + "\nERROR:无法连接至服务器,请检查你的网络连接。"); + else + throw new Exception("ERROR:无法连接至服务器,请检查你的网络连接。"); + + case Others.MainControllerSet.Disconnect: + Others.Config.FunGame_isAutoRetry = false; + Others.Config.FunGame_isRetrying = false; + Others.Config.FunGame_isAutoConnect = false; + Others.Config.FunGame_isAutoLogin = false; + Others.Config.FunGame_isConnected = false; + SetServerStatusLight((int)LightType.Yellow); + SetButtonEnableIfLogon(false, ClientState.WaitConnect); + LogoutAccount(); + break; + + case Others.MainControllerSet.LogOut: + Others.Config.FunGame_isRetrying = false; + Others.Config.FunGame_isConnected = false; + Others.Config.FunGame_isAutoLogin = false; + SetServerStatusLight((int)LightType.Yellow); + SetButtonEnableIfLogon(false, ClientState.WaitConnect); + LogoutAccount(); + if (Others.Config.FunGame_isAutoConnect) + { + NOW_CONNECTEDRETRY = -1; + Task.Run(() => + { + Thread.Sleep(1000); + MainController?.Do(MainControllerSet.Connect); + }); + } + break; + + case Others.MainControllerSet.SetUser: + if (objs != null && objs.Length > 1) + { + SetLoginUser(objs); + } + break; + + case Others.MainControllerSet.Connected: + Action action = () => + { + NoticeText.Text = Others.Config.FunGame_Notice; + if (MainController != null && Others.Config.FunGame_isAutoLogin) + { + // 自动登录 + MainController.Do(MainControllerSet.LogIn); + } + }; + if (InvokeRequired) + BeginInvoke(action); + else + action(); + break; + + default: + break; + } } } - return null; + catch (Exception e) + { + WritelnGameInfo(e.GetStackTrace()); + UpdateUI(Others.MainControllerSet.SetRed); + } } - catch (Exception e) + InvokeUpdateUI(action); + } + + public void GetMessage(string? msg, bool time = true, TimeType timetype = TimeType.TimeOnly) + { + void action() { - WritelnGameInfo(SocketHelper, e.Message != null ? e.Message + "\n" + e.StackTrace : "" + e.StackTrace); - GetMessage(SocketHelper, Others.Constant.SocketHelper_SetRed); - } - return null; + try + { + if (msg == null || msg == "") return; + if (time) + { + WritelnGameInfo(DateTimeUtility.GetDateTimeToString(timetype) + " >> " + msg); + } + else + { + WritelnGameInfo(msg); + } + } + catch (Exception e) + { + WritelnGameInfo(e.GetStackTrace()); + } + }; + InvokeUpdateUI(action); } #endregion @@ -286,111 +270,13 @@ namespace Milimoe.FunGame.Desktop.UI #region 实现 /// - /// 反射获取服务器IP和Port + /// 委托更新UI /// - private void GetServerConnection() + /// + private void InvokeUpdateUI(Action action) { - try - { - string? ipaddress = (string?)Others.Constant.ReflectionHelper.GetFunGameImplValue((int)InterfaceType.IClient, (int)InterfaceMethod.RemoteServerIP); // 获取服务器IP - if (ipaddress != null) - { - string[] s = ipaddress.Split(':'); - if (s != null && s.Length > 1) - { - Others.Constant.SERVER_IPADRESS = s[0]; - Others.Constant.SERVER_PORT = Convert.ToInt32(s[1]); - Connect(); // 连接服务器 - } - else throw new Exception(); - } - else throw new Exception(); - } - catch (Exception e) - { - WritelnGameInfo(">> 查找可用的服务器失败,请重启FunGame。\n" + e.StackTrace); - ShowMessage.ErrorMessage("查找可用的服务器失败!"); - } - } - - /// - /// 在服务器IP获取成功后,尝试连接服务器 - /// - private void Connect() - { - if (Others.Constant.SERVER_IPADRESS.Equals("") || Others.Constant.SERVER_PORT <= 0) - { - ShowMessage.ErrorMessage("查找可用的服务器失败!"); - return; - } - Task.Run(() => - { - while (true) - { - if (IsHandleCreated) - { - // 检查是否创建了窗口句柄,再Invoke委托。 - break; - } - } - Main_Action = (main) => - { - if (!Others.Config.FunGame_isConnected) - { - NOW_CONNECTEDRETRY++; - if (NOW_CONNECTEDRETRY == 0) - WritelnGameInfo(DateTimeUtility.GetNowTime() + " >> 开始连接服务器..."); - else - WritelnGameInfo(DateTimeUtility.GetNowTime() + " >> 第" + NOW_CONNECTEDRETRY + "次重试连接服务器..."); - if (NOW_CONNECTEDRETRY + 1 > MAX_CONNECTEDRETRY) // 判断重连次数是否达到上限 - { - WritelnGameInfo("ERROR:无法连接至服务器,请检查网络并重启游戏再试。"); - return; - } - SocketHelper_Action = (main) => - { - try - { - if (main != null) - { - if (SocketHelper != null) - { - SocketHelper.GetSocketHelperMethod((int)SocketHelperMethod.CloseSocket); - SocketHelper = null; - } - Others.Config.FunGame_isRetrying = true; - Application.DoEvents(); - SocketHelper = new SocketHelper(main); - SocketHelper.GetSocketHelperMethod((int)SocketHelperMethod.CreateSocket); // Invoke -> CreateSocket - } - } - catch - { - - } - }; - Task.Factory.StartNew(() => - { - if (InvokeRequired) - { - BeginInvoke(SocketHelper_Action, main); - } - else - { - SocketHelper_Action(main); - } - }); - } - }; - if (InvokeRequired) - { - Invoke(Main_Action, this); - } - else - { - Main_Action(this); - } - }); + if (InvokeRequired) Invoke(action); + else action(); } /// @@ -413,14 +299,14 @@ namespace Milimoe.FunGame.Desktop.UI } else { - INIHelper.Init(Others.Constant.FunGameType); + INIHelper.Init((FunGameEnum.FunGame)Others.Constant.FunGameType); WritelnGameInfo(">> 首次启动,已自动为你创建配置文件。"); GetFunGameConfig(); } } catch (Exception e) { - WritelnGameInfo(DateTimeUtility.GetNowTime() + e.Message != null ? e.Message + "\n" + e.StackTrace : "" + e.StackTrace); + WritelnGameInfo(e.GetStackTrace()); } } @@ -463,28 +349,6 @@ namespace Milimoe.FunGame.Desktop.UI GameInfo.ScrollToCaret(); } - /// - /// 由SocketHelper委托向消息队列输出一行文字 - /// - /// - /// - private void WritelnGameInfo(SocketHelper SocketHelper, string msg) - { - if (SocketHelper != null && msg.Trim() != "") - { - Action tempAction = new Action(() => - { - GameInfo.Text += msg + "\n"; - GameInfo.SelectionStart = GameInfo.Text.Length - 1; - GameInfo.ScrollToCaret(); - }); - if (this.InvokeRequired) - Invoke(tempAction); - else - tempAction(); - } - } - /// /// 向消息队列输出一行文字 /// @@ -919,7 +783,7 @@ namespace Milimoe.FunGame.Desktop.UI /// private void ShowFunGameInfo() { - WritelnGameInfo(FunGameEnum.GetInfo(Others.Constant.FunGameType)); + WritelnGameInfo(FunGameEnum.GetInfo((FunGameEnum.FunGame)Others.Constant.FunGameType)); } #endregion @@ -935,10 +799,10 @@ namespace Milimoe.FunGame.Desktop.UI { if (ShowMessage.OKCancelMessage("你确定关闭游戏?", "退出") == (int)MessageResult.OK) { - if (SocketHelper != null) + if (MainController != null) { - SocketHelper.GetSocketHelperMethod((int)SocketHelperMethod.CloseSocket); - SocketHelper = null; + MainController.Do(MainControllerSet.Close); + MainController = null; } Environment.Exit(0); } @@ -1105,7 +969,7 @@ namespace Milimoe.FunGame.Desktop.UI { if (ShowMessage.OKCancelMessage("你确定要退出登录吗?", "退出登录") == MessageResult.OK) { - if (SocketHelper == null || !SocketHelper.GetSocketHelperMethod((int)SocketHelperMethod.Logout)) + if (MainController == null || !MainController.Do(MainControllerSet.LogOut)) ShowMessage.WarningMessage("请求无效:退出登录失败!"); } } @@ -1117,8 +981,8 @@ namespace Milimoe.FunGame.Desktop.UI /// private void Login_Click(object sender, EventArgs e) { - if (SocketHelper != null && Others.Config.FunGame_isConnected) - SocketHelper.GetSocketHelperMethod((int)SocketHelperMethod.Login); + if (MainController != null && Others.Config.FunGame_isConnected) + MainController.Do(MainControllerSet.LogIn); else ShowMessage.WarningMessage("请先连接服务器!"); } @@ -1387,7 +1251,7 @@ namespace Milimoe.FunGame.Desktop.UI if (!Others.Config.FunGame_isRetrying) { NOW_CONNECTEDRETRY = -1; - Connect(); + MainController?.Do(MainControllerSet.Connect); } else WritelnGameInfo(">> 你不能在连接服务器的同时重试连接!"); @@ -1396,20 +1260,20 @@ namespace Milimoe.FunGame.Desktop.UI if (!Others.Config.FunGame_isConnected) { NOW_CONNECTEDRETRY = -1; - GetServerConnection(); + MainController?.Do(MainControllerSet.GetServerConnection); } break; case Others.Constant.FunGame_Disconnect: - if (Others.Config.FunGame_isConnected && SocketHelper != null) + if (Others.Config.FunGame_isConnected && MainController != null) { - SocketHelper.GetSocketHelperMethod((int)SocketHelperMethod.Disconnect); + MainController?.Do(MainControllerSet.Disconnect); } break; case Others.Constant.FunGame_DisconnectWhenNotLogin: - if (Others.Config.FunGame_isConnected && SocketHelper != null) + if (Others.Config.FunGame_isConnected && MainController != null) { - SocketHelper.GetSocketHelperMethod((int)SocketHelperMethod.CloseSocket); - GetMessage(SocketHelper, Others.Constant.SocketHelper_Disconnect); + MainController?.Do(MainControllerSet.Close); + UpdateUI(MainControllerSet.Disconnect); WritelnGameInfo(DateTimeUtility.GetNowShortTime() + " >> 你已成功断开与服务器的连接。 "); } break; @@ -1440,7 +1304,7 @@ namespace Milimoe.FunGame.Desktop.UI Others.Constant.SERVER_IPADRESS = ip; Others.Constant.SERVER_PORT = port; NOW_CONNECTEDRETRY = -1; - Connect(); + MainController?.Do(MainControllerSet.Connect); } else if (ErrorType == Core.Library.Constant.ErrorType.IsNotIP) ShowMessage.ErrorMessage("这不是一个IP地址!"); else if (ErrorType == Core.Library.Constant.ErrorType.IsNotPort) ShowMessage.ErrorMessage("这不是一个端口号!\n正确范围:1~65535"); diff --git a/FunGame.Desktop/Utility/SocketHelper.cs b/FunGame.Desktop/Utility/SocketHelper.cs new file mode 100644 index 0000000..5725fcf --- /dev/null +++ b/FunGame.Desktop/Utility/SocketHelper.cs @@ -0,0 +1,410 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Sockets; +using System.Net; +using System.Text; +using System.Threading.Tasks; +using Milimoe.FunGame.Desktop.Library.Component; +using System.ComponentModel.DataAnnotations; +using System.Net.NetworkInformation; +using Milimoe.FunGame.Core.Entity; +using Milimoe.FunGame.Desktop.Others; +using Milimoe.FunGame.Desktop.UI; +using Milimoe.FunGame.Core.Api.Utility; +using Milimoe.FunGame.Core.Api.Factory; +using Milimoe.FunGame.Core.Library.Constant; + +namespace Milimoe.FunGame.Desktop.Utils +{ + public class SocketHelper + { + //private Socket? client; + //private EndPoint? server; + //Main Main; + + //Action? SocketHelper_Action = null; + + //Task? WaitHeartBeat = null; + + //public SocketHelper(Main main) + //{ + // Main = main; + //} + + ///// + ///// 选择SocketHelper分支方法 + ///// + ///// 分支方法ID + //public bool GetSocketHelperMethod(int i) + //{ + // switch (i) + // { + // case (int)SocketHelperMethod.CreateSocket: + // CreateSocket(); + // break; + // case (int)SocketHelperMethod.CloseSocket: + // Close(); + // break; + // case (int)SocketHelperMethod.StartSocketHelper: + // StartSocketHelper(); + // break; + // case (int)SocketHelperMethod.Login: + // if (client != null) + // { + // Send((int)SocketMessageType.CheckLogin, new object[] { Main, client, Factory.New("Mili") }); + // return true; + // } + // return false; + // case (int)SocketHelperMethod.Logout: + // if (client != null && Usercfg.LoginUser != null) + // { + // Send((int)SocketMessageType.Logout, new object[] { Main, client, Usercfg.LoginUser }); + // return true; + // } + // return false; + // case (int)SocketHelperMethod.Disconnect: + // if (client != null) + // { + // Send((int)SocketMessageType.Disconnect, new object[] { Main, client }); + // return true; + // } + // return false; + // } + // return true; + //} + + ///// + ///// 创建客户端专属Socket + ///// + //private void CreateSocket() + //{ + // try + // { + // client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + // server = new IPEndPoint(IPAddress.Parse(Constant.SERVER_IPADRESS), Constant.SERVER_PORT); + // while (true) + // { + // if (!IsConnected()) + // { + // client.Connect(server); + // if (IsConnected()) + // { + // Main.GetMessage(this, MainControllerSet.WaitLoginAndSetYellow); + // break; + // } + // } + // } + // SocketHelper_Action = (main, socket) => + // { + // object? obj = main.GetMessage(this, MainControllerSet.GetUser); + // object[] objs; + // if (obj != null) + // objs = new object[] { main, socket, obj }; + // else + // objs = new object[] { main, socket }; + // if (Send((int)SocketMessageType.GetNotice, objs)) // 接触服务器并获取公告 + // { + // main.GetMessage(this, " >> 连接服务器成功,请登录账号以体验FunGame。", true); + // main.GetMessage(this, MainControllerSet.Connected); + // } + // }; + // Task t = Task.Factory.StartNew(() => + // { + // if (Main.InvokeRequired) + // { + // Main.Invoke(SocketHelper_Action, Main, client); + // } + // else + // { + // SocketHelper_Action(Main, client); + // } + // }); + // } + // catch (Exception e) + // { + // Main.GetMessage(this, MainControllerSet.Disconnected); + // Main.GetMessage(this, e.StackTrace); + // Close(); + // } + //} + + ///// + ///// 判断是否连接成功 + ///// + ///// 连接状态 + //public bool IsConnected() + //{ + // if (client != null) + // return client.Connected; + // return false; + //} + + //private bool Read(object[]? objs = null) + //{ + // Main main = Main; + // Socket? socket = null; + // try + // { + // if (objs != null) + // { + // if (objs.Length > 0) main = (Main)objs[0]; + // if (objs.Length > 1) socket = (Socket)objs[1]; + // } + // else + // { + // main = Main; + // socket = client; + // } + // if (socket != null) + // { + // // 从服务器接收消息 + // byte[] buffer = new byte[2048]; + // int length = socket.Receive(buffer); + // if (length > 0) + // { + // string msg = Constant.DEFAULT_ENCODING.GetString(buffer, 0, length); + // int type = GetType(msg); + // string typestring = EnumHelper.GetSocketTypeName(type); + // string read = GetMessage(msg); + // switch (type) + // { + // case (int)SocketMessageType.GetNotice: + // string[] reads = read.Split(';'); + // Config.FunGame_Notice = reads[1]; + // main.GetMessage(this, " >> 已连接至服务器: " + reads[0] + "。\n\n********** 服务器公告 **********\n\n" + Config.FunGame_Notice + "\n\n", true); + // return true; + // case (int)SocketMessageType.Login: + // break; + // case (int)SocketMessageType.CheckLogin: + // Main.GetMessage(this, MainControllerSet.SetUser, false, objs); + // Main.GetMessage(this, read, true); + // StartSocketHelper(); // 开始创建TCP流 + // return true; + // case (int)SocketMessageType.Logout: + // Main.GetMessage(this, MainControllerSet.SetUser, false, objs); + // Main.GetMessage(this, read, true); + // Main.GetMessage(this, MainControllerSet.LogOut); + // Close(); + // return true; + // case (int)SocketMessageType.Disconnect: + // Main.GetMessage(this, read, true); + // Main.GetMessage(this, MainControllerSet.Disconnect); + // Close(); + // return true; + // case (int)SocketMessageType.HeartBeat: + // if (WaitHeartBeat != null && !WaitHeartBeat.IsCompleted) WaitHeartBeat.Wait(1); + // //Constant.SocketHelper_HeartBeatFaileds = 0; + // main.GetMessage(this, MainControllerSet.SetGreenAndPing); + // return true; + // } + // main.GetMessage(this, read); + // return true; + // } + // else + // throw new Exception("ERROR:未收到任何来自服务器的信息,与服务器连接可能丢失。"); + // } + // else + // { + // main.GetMessage(this, MainControllerSet.Disconnected); + // throw new Exception("ERROR:服务器连接失败。"); + // } + // } + // catch (Exception e) + // { + // main.GetMessage(this, MainControllerSet.Disconnected); + // main.GetMessage(this, e.Message != null ? e.Message + "\n" + e.StackTrace : "" + e.StackTrace); + // Close(); + // } + // return false; + //} + + //private bool Send(int i, object[]? objs = null) + //{ + // Main main = Main; + // Socket? socket = null; + // try + // { + // if (objs != null) + // { + // if (objs.Length > 0) main = (Main)objs[0]; + // if (objs.Length > 1) socket = (Socket)objs[1]; + // } + // else + // { + // main = Main; + // socket = client; + // } + // if (socket != null) + // { + // string msg = ""; + // SocketMessageType type = (SocketMessageType)i; + // // 发送消息给服务器端 + // switch (type) + // { + // case SocketMessageType.GetNotice: + // msg = MakeMessage(type, "获取公告"); + // if (Send(msg, socket) > 0) + // { + // return Read(objs); + // } + // else + // throw new Exception("ERROR:消息未送达服务器,与服务器连接可能丢失。"); + // case SocketMessageType.Login: + // break; + // case SocketMessageType.CheckLogin: + // User user; + // if (objs != null && objs.Length > 2) + // { + // user = (User)objs[2]; + // msg = MakeMessage(type, user.Userame); + // } + // else + // { + // Config.FunGame_isAutoRetry = false; + // throw new Exception("ERROR: 请登录账号。"); + // } + // break; + // case SocketMessageType.Logout: + // if (objs != null && objs.Length > 2) + // { + // user = (User)objs[2]; + // msg = MakeMessage(type, user.Userame); + // if (Send(msg, socket) > 0) + // return true; + // } + // return false; + // case SocketMessageType.Disconnect: + // msg = MakeMessage(type, "断开连接"); + // if (Send(msg, socket) > 0) + // return true; + // return false; + // case SocketMessageType.HeartBeat: + // msg = MakeMessage(type, "心跳检测"); + // if (Send(msg, socket) > 0) + // { + // WaitHeartBeat = Task.Run(() => + // { + // Thread.Sleep(4000); + // AddHeartBeatFaileds(main); + // }); + // return true; + // } + // AddHeartBeatFaileds(main); + // return false; + // default: + // return false; + // } + // if (Send(msg, socket) > 0) + // { + // return Read(objs); + // } + // else + // throw new Exception("ERROR:消息未送达服务器,与服务器连接可能丢失。"); + // } + // else + // { + // main.GetMessage(this, MainControllerSet.Disconnected); + // throw new Exception("ERROR:服务器连接失败。"); + // } + // } + // catch (Exception e) + // { + // CatchException(main, e, false); + // } + // return false; + //} + + //private int Send(string msg, Socket socket) + //{ + // byte[] buffer = Constant.DEFAULT_ENCODING.GetBytes(msg); + // int length = socket.Send(buffer); + // return length; + //} + + //private void CatchException(Main main, Exception e, bool isDisconnected) + //{ + // if (isDisconnected) + // main.GetMessage(this, MainControllerSet.Disconnected); + // else + // main.GetMessage(this, MainControllerSet.SetRed); + // main.GetMessage(this, e.Message != null ? e.Message + "\n" + e.StackTrace : "" + e.StackTrace); + // Close(); + //} + + //private void AddHeartBeatFaileds(Main main) + //{ + // // 超过三次没回应心跳,服务器连接失败。 + // try + // { + // //MainControllerSet.HeartBeatFaileds++; + // //if (MainControllerSet.HeartBeatFaileds >= 3) + // // throw new Exception("ERROR:服务器连接失败。"); + // } + // catch (Exception e) + // { + // CatchException(main, e, true); + // } + //} + + //private int GetType(string msg) + //{ + // int index = msg.IndexOf(';') - 1; + // if (index > 0) + // return Convert.ToInt32(msg[..index]); + // else + // return Convert.ToInt32(msg[..1]); + //} + + //private string GetMessage(string msg) + //{ + // int index = msg.IndexOf(';') + 1; + // return msg[index..]; + //} + + //private string MakeMessage(SocketMessageType type, string msg) + //{ + // return (int)type + ";" + msg; + //} + + //private void Close() + //{ + // if (client != null) + // { + // client.Close(); + // client = null; + // } + // if (server != null) + // { + // server = null; + // } + //} + + //private void StartSocketHelper() + //{ + // Task HeartBeatStream = Task.Factory.StartNew(CreateSendHeartBeatStream); + // Task StreamReader = Task.Factory.StartNew(CreateStreamReader); + //} + + //private void CreateSendHeartBeatStream() + //{ + // Thread.Sleep(100); + // Main.GetMessage(this, "Creating: SendHeartBeatStream...OK"); + // while (IsConnected()) + // { + // Send((int)SocketMessageType.HeartBeat); // 发送心跳包 + // Thread.Sleep(20000); + // } + //} + + //private void CreateStreamReader() + //{ + // Thread.Sleep(100); + // Main.GetMessage(this, "Creating: StreamReader...OK"); + // while (IsConnected()) + // { + // Read(); + // } + //} + } +} diff --git a/FunGame.Desktop/Utils/SocketHelper.cs b/FunGame.Desktop/Utils/SocketHelper.cs deleted file mode 100644 index 183a72f..0000000 --- a/FunGame.Desktop/Utils/SocketHelper.cs +++ /dev/null @@ -1,410 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Sockets; -using System.Net; -using System.Text; -using System.Threading.Tasks; -using FunGame.Desktop.Models.Component; -using System.ComponentModel.DataAnnotations; -using System.Net.NetworkInformation; -using Milimoe.FunGame.Core.Entity; -using Milimoe.FunGame.Desktop.Others; -using Milimoe.FunGame.Desktop.UI; -using Milimoe.FunGame.Core.Api.Utility; -using Milimoe.FunGame.Core.Api.Factory; -using Milimoe.FunGame.Core.Library.Constant; - -namespace Milimoe.FunGame.Desktop.Utils -{ - public class SocketHelper - { - private Socket? client; - private EndPoint? server; - Main Main; - - Action? SocketHelper_Action = null; - - Task? WaitHeartBeat = null; - - public SocketHelper(Main main) - { - Main = main; - } - - /// - /// 选择SocketHelper分支方法 - /// - /// 分支方法ID - public bool GetSocketHelperMethod(int i) - { - switch (i) - { - case (int)SocketHelperMethod.CreateSocket: - CreateSocket(); - break; - case (int)SocketHelperMethod.CloseSocket: - Close(); - break; - case (int)SocketHelperMethod.StartSocketHelper: - StartSocketHelper(); - break; - case (int)SocketHelperMethod.Login: - if (client != null) - { - Send((int)SocketMessageType.CheckLogin, new object[] { Main, client, FactoryHelper.New("Mili") }); - return true; - } - return false; - case (int)SocketHelperMethod.Logout: - if (client != null && Usercfg.LoginUser != null) - { - Send((int)SocketMessageType.Logout, new object[] { Main, client, Usercfg.LoginUser }); - return true; - } - return false; - case (int)SocketHelperMethod.Disconnect: - if (client != null) - { - Send((int)SocketMessageType.Disconnect, new object[] { Main, client }); - return true; - } - return false; - } - return true; - } - - /// - /// 创建客户端专属Socket - /// - private void CreateSocket() - { - try - { - client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - server = new IPEndPoint(IPAddress.Parse(Constant.SERVER_IPADRESS), Constant.SERVER_PORT); - while (true) - { - if (!IsConnected()) - { - client.Connect(server); - if (IsConnected()) - { - Main.GetMessage(this, Constant.SocketHelper_WaitLoginAndSetYellow); - break; - } - } - } - SocketHelper_Action = (main, socket) => - { - object? obj = main.GetMessage(this, Constant.SocketHelper_GetUser); - object[] objs; - if (obj != null) - objs = new object[] { main, socket, obj }; - else - objs = new object[] { main, socket }; - if (Send((int)SocketMessageType.GetNotice, objs)) // 接触服务器并获取公告 - { - main.GetMessage(this, " >> 连接服务器成功,请登录账号以体验FunGame。", true); - main.GetMessage(this, Constant.SocketHelper_SetNotice); - } - }; - Task t = Task.Factory.StartNew(() => - { - if (Main.InvokeRequired) - { - Main.Invoke(SocketHelper_Action, Main, client); - } - else - { - SocketHelper_Action(Main, client); - } - }); - } - catch (Exception e) - { - Main.GetMessage(this, Constant.SocketHelper_Disconnected); - Main.GetMessage(this, e.StackTrace); - Close(); - } - } - - /// - /// 判断是否连接成功 - /// - /// 连接状态 - public bool IsConnected() - { - if (client != null) - return client.Connected; - return false; - } - - private bool Read(object[]? objs = null) - { - Main main = Main; - Socket? socket = null; - try - { - if (objs != null) - { - if (objs.Length > 0) main = (Main)objs[0]; - if (objs.Length > 1) socket = (Socket)objs[1]; - } - else - { - main = Main; - socket = client; - } - if (socket != null) - { - // 从服务器接收消息 - byte[] buffer = new byte[2048]; - int length = socket.Receive(buffer); - if (length > 0) - { - string msg = Constant.DEFAULT_ENCODING.GetString(buffer, 0, length); - int type = GetType(msg); - string typestring = EnumHelper.GetSocketTypeName(type); - string read = GetMessage(msg); - switch (type) - { - case (int)SocketMessageType.GetNotice: - string[] reads = read.Split(';'); - Config.FunGame_Notice = reads[1]; - main.GetMessage(this, " >> 已连接至服务器: " + reads[0] + "。\n\n********** 服务器公告 **********\n\n" + Config.FunGame_Notice + "\n\n", true); - return true; - case (int)SocketMessageType.Login: - break; - case (int)SocketMessageType.CheckLogin: - Main.GetMessage(this, Constant.SocketHelper_SetUser, false, objs); - Main.GetMessage(this, read, true); - StartSocketHelper(); // 开始创建TCP流 - return true; - case (int)SocketMessageType.Logout: - Main.GetMessage(this, Constant.SocketHelper_SetUser, false, objs); - Main.GetMessage(this, read, true); - Main.GetMessage(this, Constant.SocketHelper_LogOut); - Close(); - return true; - case (int)SocketMessageType.Disconnect: - Main.GetMessage(this, read, true); - Main.GetMessage(this, Constant.SocketHelper_Disconnect); - Close(); - return true; - case (int)SocketMessageType.HeartBeat: - if (WaitHeartBeat != null && !WaitHeartBeat.IsCompleted) WaitHeartBeat.Wait(1); - Constant.SocketHelper_HeartBeatFaileds = 0; - main.GetMessage(this, Constant.SocketHelper_SetGreenAndPing); - return true; - } - main.GetMessage(this, read); - return true; - } - else - throw new Exception("ERROR:未收到任何来自服务器的信息,与服务器连接可能丢失。"); - } - else - { - main.GetMessage(this, Constant.SocketHelper_Disconnected); - throw new Exception("ERROR:服务器连接失败。"); - } - } - catch (Exception e) - { - main.GetMessage(this, Constant.SocketHelper_Disconnected); - main.GetMessage(this, e.Message != null ? e.Message + "\n" + e.StackTrace : "" + e.StackTrace); - Close(); - } - return false; - } - - private bool Send(int i, object[]? objs = null) - { - Main main = Main; - Socket? socket = null; - try - { - if (objs != null) - { - if (objs.Length > 0) main = (Main)objs[0]; - if (objs.Length > 1) socket = (Socket)objs[1]; - } - else - { - main = Main; - socket = client; - } - if (socket != null) - { - string msg = ""; - SocketMessageType type = (SocketMessageType)i; - // 发送消息给服务器端 - switch (type) - { - case SocketMessageType.GetNotice: - msg = MakeMessage(type, "获取公告"); - if (Send(msg, socket) > 0) - { - return Read(objs); - } - else - throw new Exception("ERROR:消息未送达服务器,与服务器连接可能丢失。"); - case SocketMessageType.Login: - break; - case SocketMessageType.CheckLogin: - User user; - if (objs != null && objs.Length > 2) - { - user = (User)objs[2]; - msg = MakeMessage(type, user.Userame); - } - else - { - Config.FunGame_isAutoRetry = false; - throw new Exception("ERROR: 请登录账号。"); - } - break; - case SocketMessageType.Logout: - if (objs != null && objs.Length > 2) - { - user = (User)objs[2]; - msg = MakeMessage(type, user.Userame); - if (Send(msg, socket) > 0) - return true; - } - return false; - case SocketMessageType.Disconnect: - msg = MakeMessage(type, "断开连接"); - if (Send(msg, socket) > 0) - return true; - return false; - case SocketMessageType.HeartBeat: - msg = MakeMessage(type, "心跳检测"); - if (Send(msg, socket) > 0) - { - WaitHeartBeat = Task.Run(() => - { - Thread.Sleep(4000); - AddHeartBeatFaileds(main); - }); - return true; - } - AddHeartBeatFaileds(main); - return false; - default: - return false; - } - if (Send(msg, socket) > 0) - { - return Read(objs); - } - else - throw new Exception("ERROR:消息未送达服务器,与服务器连接可能丢失。"); - } - else - { - main.GetMessage(this, Constant.SocketHelper_Disconnected); - throw new Exception("ERROR:服务器连接失败。"); - } - } - catch (Exception e) - { - CatchException(main, e, false); - } - return false; - } - - private int Send(string msg, Socket socket) - { - byte[] buffer = Constant.DEFAULT_ENCODING.GetBytes(msg); - int length = socket.Send(buffer); - return length; - } - - private void CatchException(Main main, Exception e, bool isDisconnected) - { - if (isDisconnected) - main.GetMessage(this, Constant.SocketHelper_Disconnected); - else - main.GetMessage(this, Constant.SocketHelper_SetRed); - main.GetMessage(this, e.Message != null ? e.Message + "\n" + e.StackTrace : "" + e.StackTrace); - Close(); - } - - private void AddHeartBeatFaileds(Main main) - { - // 超过三次没回应心跳,服务器连接失败。 - try - { - Constant.SocketHelper_HeartBeatFaileds++; - if (Constant.SocketHelper_HeartBeatFaileds >= 3) - throw new Exception("ERROR:服务器连接失败。"); - } - catch (Exception e) - { - CatchException(main, e, true); - } - } - - private int GetType(string msg) - { - int index = msg.IndexOf(';') - 1; - if (index > 0) - return Convert.ToInt32(msg[..index]); - else - return Convert.ToInt32(msg[..1]); - } - - private string GetMessage(string msg) - { - int index = msg.IndexOf(';') + 1; - return msg[index..]; - } - - private string MakeMessage(SocketMessageType type, string msg) - { - return (int)type + ";" + msg; - } - - private void Close() - { - if (client != null) - { - client.Close(); - client = null; - } - if (server != null) - { - server = null; - } - } - - private void StartSocketHelper() - { - Task HeartBeatStream = Task.Factory.StartNew(CreateSendHeartBeatStream); - Task StreamReader = Task.Factory.StartNew(CreateStreamReader); - } - - private void CreateSendHeartBeatStream() - { - Thread.Sleep(100); - Main.GetMessage(this, "Creating: SendHeartBeatStream...OK"); - while (IsConnected()) - { - Send((int)SocketMessageType.HeartBeat); // 发送心跳包 - Thread.Sleep(20000); - } - } - - private void CreateStreamReader() - { - Thread.Sleep(100); - Main.GetMessage(this, "Creating: StreamReader...OK"); - while (IsConnected()) - { - Read(); - } - } - } -}