From 00504d65da183f2b8247d4e53807eac1c14c7cae Mon Sep 17 00:00:00 2001 From: Mili Date: Mon, 21 Nov 2022 23:43:51 +0800 Subject: [PATCH] =?UTF-8?q?=E5=B0=81=E8=A3=85=E6=9C=8D=E5=8A=A1=E5=99=A8So?= =?UTF-8?q?cket?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- FunGame.Core/Api/Utility/Factory.cs | 16 +- FunGame.Core/Interface/Base/ISocket.cs | 34 ++++ .../Library/Common/Network/ClientSocket.cs | 82 ++++++++ .../Library/Common/Network/JsonObject.cs | 35 ++++ .../Library/Common/Network/ServerSocket.cs | 77 ++++++++ FunGame.Core/Library/Common/Network/Socket.cs | 15 +- FunGame.Core/Service/SocketManager.cs | 183 ++++++++++++++---- FunGame.Core/Service/ThreadManager.cs | 27 +++ FunGame.Desktop/FunGame.Desktop.csproj | 6 +- FunGame.Desktop/{Image => Images}/back.jpg | Bin FunGame.Desktop/{Image => Images}/exit.png | Bin FunGame.Desktop/{Image => Images}/green.png | Bin FunGame.Desktop/{Image => Images}/logo.ico | Bin FunGame.Desktop/{Image => Images}/min.png | Bin FunGame.Desktop/{Image => Images}/red.png | Bin FunGame.Desktop/{Image => Images}/send.png | Bin FunGame.Desktop/{Image => Images}/yellow.png | Bin FunGame.Desktop/Model/MainModel.cs | 121 +++++++++--- FunGame.Desktop/Others/Constant.cs | 2 +- FunGame.Desktop/Others/Usercfg.cs | 4 +- FunGame.Desktop/Properties/Resources.resx | 16 +- FunGame.Desktop/UI/Main/Main.cs | 27 +-- 22 files changed, 539 insertions(+), 106 deletions(-) create mode 100644 FunGame.Core/Interface/Base/ISocket.cs create mode 100644 FunGame.Core/Library/Common/Network/ClientSocket.cs create mode 100644 FunGame.Core/Library/Common/Network/JsonObject.cs create mode 100644 FunGame.Core/Library/Common/Network/ServerSocket.cs rename FunGame.Desktop/{Image => Images}/back.jpg (100%) rename FunGame.Desktop/{Image => Images}/exit.png (100%) rename FunGame.Desktop/{Image => Images}/green.png (100%) rename FunGame.Desktop/{Image => Images}/logo.ico (100%) rename FunGame.Desktop/{Image => Images}/min.png (100%) rename FunGame.Desktop/{Image => Images}/red.png (100%) rename FunGame.Desktop/{Image => Images}/send.png (100%) rename FunGame.Desktop/{Image => Images}/yellow.png (100%) diff --git a/FunGame.Core/Api/Utility/Factory.cs b/FunGame.Core/Api/Utility/Factory.cs index f8642b0..cf5b50a 100644 --- a/FunGame.Core/Api/Utility/Factory.cs +++ b/FunGame.Core/Api/Utility/Factory.cs @@ -16,11 +16,11 @@ namespace Milimoe.FunGame.Core.Api.Utility /// Entity类 /// 构造函数的参数 /// - public static object? GetInstance(params object[]? objs) + public static T? GetInstance(params object[]? objs) { - if (!IsEntity()) return null; + if (!IsEntity()) return default; object? instance = null; - if (objs is null || objs.Length == 0) return instance; + if (objs is null || objs.Length == 0) return (T?)instance; if (typeof(T) == typeof(Entity.User)) { instance = Api.Factory.UserFactory.GetInstance("Mili"); @@ -29,7 +29,7 @@ namespace Milimoe.FunGame.Core.Api.Utility { } - return instance; + return (T?)instance; } /// @@ -41,11 +41,11 @@ namespace Milimoe.FunGame.Core.Api.Utility /// Entity类 /// 构造函数的参数 /// - public static object New(params object[]? objs) + public static T New(params object[]? objs) { object instance = General.EntityInstance; - if (!IsEntity()) return instance; - if (objs is null || objs.Length == 0) return instance; + if (!IsEntity()) return (T)instance; + if (objs is null || objs.Length == 0) return (T)instance; if (typeof(T) == typeof(Entity.User)) { instance = Api.Factory.UserFactory.GetInstance("Mili"); @@ -54,7 +54,7 @@ namespace Milimoe.FunGame.Core.Api.Utility { } - return instance; + return (T)instance; } /// diff --git a/FunGame.Core/Interface/Base/ISocket.cs b/FunGame.Core/Interface/Base/ISocket.cs new file mode 100644 index 0000000..7f4c775 --- /dev/null +++ b/FunGame.Core/Interface/Base/ISocket.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Milimoe.FunGame.Core.Library.Common.Network; +using Milimoe.FunGame.Core.Library.Constant; + +namespace Milimoe.FunGame.Core.Interface.Base +{ + public interface ISocket + { + public System.Net.Sockets.Socket Instance { get; } + public int Runtime { get; } + public string ServerIP { get; } + public int ServerPort { get; } + public string ServerName { get; } + public string ServerNotice { get; } + public int HeartBeatFaileds { get; } + public bool Connected + { + get + { + return Instance != null && Instance.Connected; + } + } + public bool Receiving { get; } + public bool SendingHeartBeat { get; } + public SocketResult Send(SocketMessageType type, params object[] objs); + public object[] Receive(); + public void Close(); + public void StartReceiving(Task t); + } +} diff --git a/FunGame.Core/Library/Common/Network/ClientSocket.cs b/FunGame.Core/Library/Common/Network/ClientSocket.cs new file mode 100644 index 0000000..b617695 --- /dev/null +++ b/FunGame.Core/Library/Common/Network/ClientSocket.cs @@ -0,0 +1,82 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Milimoe.FunGame.Core.Interface.Base; +using Milimoe.FunGame.Core.Library.Constant; +using Milimoe.FunGame.Core.Service; + +namespace Milimoe.FunGame.Core.Library.Common.Network +{ + public class ClientSocket : ISocket + { + public System.Net.Sockets.Socket Instance { get; } + public int Runtime { get; } = (int)SocketRuntimeType.Server; + public string ServerIP { get; } = ""; + public int ServerPort { get; } = 0; + public string ServerName { get; } = ""; + public string ServerNotice { get; } = ""; + public string ClientIP { get; } = ""; + public string ClientName { get; private set; } = ""; + public int HeartBeatFaileds { get; private set; } = 0; + public bool Connected + { + get + { + return Instance != null && Instance.Connected; + } + } + public bool Receiving { get; private set; } = false; + public bool SendingHeartBeat { get; private set; } = false; + + private Task? ReceivingTask; + + public ClientSocket(System.Net.Sockets.Socket Instance, int ServerPort, string ClientIP, string ClientName) + { + this.Instance= Instance; + this.ServerPort = ServerPort; + this.ClientIP = ClientIP; + this.ClientName = ClientName; + } + + public void Close() + { + StopReceiving(); + Instance?.Close(); + } + + public object[] Receive() + { + object[] result = SocketManager.Receive(Instance); + if (result.Length != 2) throw new System.Exception("收到错误的返回信息。"); + return result; + } + + public SocketResult Send(SocketMessageType type, params object[] objs) + { + if (Instance != null) + { + if (SocketManager.Send(Instance, type, objs) == SocketResult.Success) + { + return SocketResult.Success; + } + else return SocketResult.Fail; + } + return SocketResult.NotSent; + } + + public void StartReceiving(Task t) + { + Receiving = true; + ReceivingTask = t; + } + + public void StopReceiving() + { + Receiving = false; + ReceivingTask?.Wait(1); + ReceivingTask = null; + } + } +} diff --git a/FunGame.Core/Library/Common/Network/JsonObject.cs b/FunGame.Core/Library/Common/Network/JsonObject.cs new file mode 100644 index 0000000..1c8ce9b --- /dev/null +++ b/FunGame.Core/Library/Common/Network/JsonObject.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using Milimoe.FunGame.Core.Library.Constant; + +namespace Milimoe.FunGame.Core.Library.Common.Network +{ + [Serializable] + internal class JsonObject + { + internal SocketMessageType MessageType { get; } = SocketMessageType.Unknown; + internal object[] Parameters { get; } + internal string JsonString { get; } + + internal JsonObject(SocketMessageType MessageType, object[] Parameters) + { + this.MessageType = MessageType; + this.Parameters = Parameters; + this.JsonString = JsonSerializer.Serialize(this); + } + + internal static string GetString(SocketMessageType MessageType, object[] Parameters) + { + return new JsonObject(MessageType, Parameters).JsonString; + } + + internal static JsonObject? GetObject(string JsonString) + { + return JsonSerializer.Deserialize(JsonString); + } + } +} diff --git a/FunGame.Core/Library/Common/Network/ServerSocket.cs b/FunGame.Core/Library/Common/Network/ServerSocket.cs new file mode 100644 index 0000000..7df6131 --- /dev/null +++ b/FunGame.Core/Library/Common/Network/ServerSocket.cs @@ -0,0 +1,77 @@ +using Milimoe.FunGame.Core.Interface.Base; +using Milimoe.FunGame.Core.Library.Constant; +using Milimoe.FunGame.Core.Service; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Milimoe.FunGame.Core.Library.Common.Network +{ + public class ServerSocket : ISocket + { + public System.Net.Sockets.Socket Instance { get; } + public int Runtime { get; } = (int)SocketRuntimeType.Server; + public string ServerIP { get; } = ""; + public int ServerPort { get; } = 0; + public string ServerName { get; } = ""; + public string ServerNotice { get; } = ""; + public int HeartBeatFaileds { get; private set; } = 0; + public bool Connected + { + get + { + return Instance != null && Instance.Connected; + } + } + public bool Receiving { get; private set; } = false; + public bool SendingHeartBeat { get; private set; } = false; + + private ServerSocket(System.Net.Sockets.Socket Instance, int ServerPort) + { + this.Instance = Instance; + this.ServerPort = ServerPort; + } + + public ServerSocket StartListening(int Port = 22222, int MaxConnection = 20) + { + System.Net.Sockets.Socket? socket = SocketManager.StartListening(Port, MaxConnection); + if (socket != null) return new ServerSocket(socket, Port); + else throw new System.Exception("无法创建监听,请重新启动服务器再试。"); + } + + public ClientSocket Accept() + { + object[] result = SocketManager.Accept(); + if (result != null && result.Length == 2) + { + string ClientIP = (string)result[0]; + System.Net.Sockets.Socket Client = (System.Net.Sockets.Socket)result[1]; + return new ClientSocket(Client, ServerPort, ClientIP, ClientIP); + } + throw new System.Exception("无法获取客户端信息。"); + } + + public SocketResult Send(SocketMessageType type, params object[] objs) + { + throw new System.Exception("监听Socket不能用于发送信息。"); + } + + public object[] Receive() + { + throw new System.Exception("监听Socket不能用于接收信息。"); + } + + public void Close() + { + Instance?.Close(); + } + + public void StartReceiving(Task t) + { + throw new System.Exception("监听Socket不能用于接收信息。"); + } + } +} diff --git a/FunGame.Core/Library/Common/Network/Socket.cs b/FunGame.Core/Library/Common/Network/Socket.cs index c8b0086..14da2ab 100644 --- a/FunGame.Core/Library/Common/Network/Socket.cs +++ b/FunGame.Core/Library/Common/Network/Socket.cs @@ -12,7 +12,7 @@ using Milimoe.FunGame.Core.Interface.Base; namespace Milimoe.FunGame.Core.Library.Common.Network { - public class Socket + public class Socket : ISocket { public System.Net.Sockets.Socket Instance { get; } public int Runtime { get; } = (int)SocketRuntimeType.Client; @@ -49,12 +49,12 @@ namespace Milimoe.FunGame.Core.Library.Common.Network if (socket != null) return new Socket(socket, IP, Port); else throw new System.Exception("连接到服务器失败。"); } - - public SocketResult Send(SocketMessageType type, string msg = "") + + public SocketResult Send(SocketMessageType type, params object[] objs) { if (Instance != null) { - if (SocketManager.Send(type, msg) == SocketResult.Success) + if (SocketManager.Send(type, objs) == SocketResult.Success) { return SocketResult.Success; } @@ -63,10 +63,11 @@ namespace Milimoe.FunGame.Core.Library.Common.Network return SocketResult.NotSent; } - public string[] Receive() + public object[] Receive() { - string[] result = SocketManager.Receive(); - if (result[0] == SocketSet.HeartBeat) + object[] result = SocketManager.Receive(); + if (result.Length != 2) throw new System.Exception("收到错误的返回信息。"); + if ((string)result[0] == SocketSet.HeartBeat) { if (WaitHeartBeatReply != null && !WaitHeartBeatReply.IsCompleted) WaitHeartBeatReply.Wait(1); HeartBeatFaileds = 0; diff --git a/FunGame.Core/Service/SocketManager.cs b/FunGame.Core/Service/SocketManager.cs index f7700e6..6ad909c 100644 --- a/FunGame.Core/Service/SocketManager.cs +++ b/FunGame.Core/Service/SocketManager.cs @@ -7,33 +7,94 @@ using Milimoe.FunGame.Core.Interface.Base; using System.Collections; using System.Net.Sockets; using System.Net; +using System.Text.Json; using Milimoe.FunGame.Core.Library.Constant; namespace Milimoe.FunGame.Core.Service { internal class SocketManager { + /// + /// 客户端专用Socket + /// internal static Socket? Socket { get; private set; } = null; + /// + /// 服务器端专用Socket + /// + internal static Socket? ServerSocket { get; private set; } = null; + + /// + /// 创建服务器监听Socket + /// + /// 监听端口号 + /// 最大连接数量 + /// 服务器端专用Socket + internal static Socket? StartListening(int Port = 22222, int MaxConnection = 20) + { + try + { + ServerSocket = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + IPEndPoint ServerEndPoint = new(IPAddress.Any, Port); + ServerSocket.Bind(ServerEndPoint); + ServerSocket.Listen(MaxConnection); + return ServerSocket; + } + catch + { + ServerSocket?.Close(); + } + return null; + } + + /// + /// 创建一个监听到客户端Socket + /// + /// 客户端IP地址[0]和客户端Socket[1] + internal static object[] Accept() + { + if (ServerSocket is null) return Array.Empty(); + Socket Client; + string ClientIP; + try + { + Client = ServerSocket.Accept(); + IPEndPoint? ClientIPEndPoint = (IPEndPoint?)Client.RemoteEndPoint; + ClientIP = (ClientIPEndPoint != null) ? ClientIPEndPoint.ToString() : "Unknown"; + return new object[] { ClientIP, Client }; + } + catch + { + ServerSocket?.Close(); + } + return Array.Empty(); + } + + /// + /// 创建客户端Socket + /// + /// 服务器IP地址 + /// 服务器监听端口 + /// 客户端专用Socket internal static Socket? Connect(string IP, int Port = 22222) { - Socket? socket = null; + Socket? ClientSocket; EndPoint ServerEndPoint; try { - socket = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + ClientSocket = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ServerEndPoint = new IPEndPoint(IPAddress.Parse(IP), Port); if (ServerEndPoint != null) { while (true) { - if (!socket.Connected) + if (!ClientSocket.Connected) { - socket.Connect(ServerEndPoint); - if (socket.Connected) + ClientSocket.Connect(ServerEndPoint); + if (ClientSocket.Connected) { - Socket = socket; - return socket; + Socket = ClientSocket; + return Socket; } } } @@ -41,16 +102,23 @@ namespace Milimoe.FunGame.Core.Service } catch { - socket?.Close(); + Socket?.Close(); } return null; } - - internal static SocketResult Send(SocketMessageType type, string msg) + + /// + /// 用于服务器端向客户端Socket发送信息 + /// + /// 客户端Socket + /// 通信类型 + /// 参数 + /// 通信结果 + internal static SocketResult Send(Socket ClientSocket, SocketMessageType type, object[] objs) { - if (Socket != null) + if (ClientSocket != null && objs != null && objs.Length > 0) { - if (Socket.Send(General.DEFAULT_ENCODING.GetBytes(MakeMessage(type, msg))) > 0) + if (ClientSocket.Send(General.DEFAULT_ENCODING.GetBytes(Library.Common.Network.JsonObject.GetString(type, objs))) > 0) { return SocketResult.Success; } @@ -59,9 +127,36 @@ namespace Milimoe.FunGame.Core.Service return SocketResult.NotSent; } - internal static string[] Receive() + /// + /// 用于客户端向服务器Socket发送信息 + /// + /// 通信类型 + /// 参数 + /// 通信结果 + internal static SocketResult Send(SocketMessageType type, object[] objs) { - string[] result = new string[2] { GetTypeString(SocketMessageType.Unknown), "" }; + if (objs is null || objs.Length <= 0) + { + objs = new object[] { "" }; + } + if (Socket != null) + { + if (Socket.Send(General.DEFAULT_ENCODING.GetBytes(Library.Common.Network.JsonObject.GetString(type, objs))) > 0) + { + return SocketResult.Success; + } + else return SocketResult.Fail; + } + return SocketResult.NotSent; + } + + /// + /// 用于客户端接收服务器信息 + /// + /// 通信类型[0]和参数[1] + internal static object[] Receive() + { + object[] result = Array.Empty(); if (Socket != null) { // 从服务器接收消息 @@ -70,34 +165,51 @@ namespace Milimoe.FunGame.Core.Service if (length > 0) { string msg = General.DEFAULT_ENCODING.GetString(buffer, 0, length); - result[0] = GetTypeString(GetType(msg)); - result[1] = GetMessage(msg); + Library.Common.Network.JsonObject? json = Library.Common.Network.JsonObject.GetObject(msg); + if (json != null) + { + result[0] = GetTypeString(json.MessageType); + result[1] = json.Parameters; + } return result; } } return result; } - private static int GetType(string msg) + /// + /// 用于服务器接收客户端信息 + /// + /// 客户端Socket + /// 通信类型[0]和参数[1] + internal static object[] Receive(Socket ClientSocket) { - int index = msg.IndexOf(';') - 1; - if (index > 0) - return Convert.ToInt32(msg[..index]); - else - return Convert.ToInt32(msg[..1]); - } - - private static string GetMessage(string msg) - { - int index = msg.IndexOf(';') + 1; - return msg[index..]; - } - - private static string MakeMessage(SocketMessageType type, string msg) - { - return (int)type + ";" + msg; + object[] result = Array.Empty(); + if (ClientSocket != null) + { + // 从客户端接收消息 + byte[] buffer = new byte[2048]; + int length = ClientSocket.Receive(buffer); + if (length > 0) + { + string msg = General.DEFAULT_ENCODING.GetString(buffer, 0, length); + Library.Common.Network.JsonObject? json = Library.Common.Network.JsonObject.GetObject(msg); + if (json != null) + { + result[0] = GetTypeString(json.MessageType); + result[1] = json.Parameters; + } + return result; + } + } + return result; } + /// + /// 将通信类型的枚举转换为字符串 + /// + /// 通信类型 + /// 等效字符串 private static string GetTypeString(SocketMessageType type) { return type switch @@ -112,10 +224,5 @@ namespace Milimoe.FunGame.Core.Service _ => SocketSet.Unknown, }; } - - private static string GetTypeString(int type) - { - return GetTypeString((SocketMessageType)type); - } } } diff --git a/FunGame.Core/Service/ThreadManager.cs b/FunGame.Core/Service/ThreadManager.cs index d4abb68..781a2a1 100644 --- a/FunGame.Core/Service/ThreadManager.cs +++ b/FunGame.Core/Service/ThreadManager.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; @@ -8,6 +9,32 @@ namespace Milimoe.FunGame.Core.Service { internal class ThreadManager { + internal static int MAX_THREAD { get; } = 20; + private ConcurrentDictionary Threads { get; } = new(); + + internal Task this[string name] + { + get + { + return Threads[name]; + } + } + + internal bool Add(string name, Task t) + { + return Threads.TryAdd(name, t); + } + + internal bool Remove(string name) + { + return Threads.TryRemove(name, out _); + } + + internal void Clear() + { + Threads.Clear(); + } + } } diff --git a/FunGame.Desktop/FunGame.Desktop.csproj b/FunGame.Desktop/FunGame.Desktop.csproj index 8860a00..0b9bd75 100644 --- a/FunGame.Desktop/FunGame.Desktop.csproj +++ b/FunGame.Desktop/FunGame.Desktop.csproj @@ -6,7 +6,7 @@ enable true enable - Image\logo.ico + Images\logo.ico logo.ico Milimoe @@ -31,7 +31,7 @@ - + @@ -68,7 +68,7 @@ - + True \ diff --git a/FunGame.Desktop/Image/back.jpg b/FunGame.Desktop/Images/back.jpg similarity index 100% rename from FunGame.Desktop/Image/back.jpg rename to FunGame.Desktop/Images/back.jpg diff --git a/FunGame.Desktop/Image/exit.png b/FunGame.Desktop/Images/exit.png similarity index 100% rename from FunGame.Desktop/Image/exit.png rename to FunGame.Desktop/Images/exit.png diff --git a/FunGame.Desktop/Image/green.png b/FunGame.Desktop/Images/green.png similarity index 100% rename from FunGame.Desktop/Image/green.png rename to FunGame.Desktop/Images/green.png diff --git a/FunGame.Desktop/Image/logo.ico b/FunGame.Desktop/Images/logo.ico similarity index 100% rename from FunGame.Desktop/Image/logo.ico rename to FunGame.Desktop/Images/logo.ico diff --git a/FunGame.Desktop/Image/min.png b/FunGame.Desktop/Images/min.png similarity index 100% rename from FunGame.Desktop/Image/min.png rename to FunGame.Desktop/Images/min.png diff --git a/FunGame.Desktop/Image/red.png b/FunGame.Desktop/Images/red.png similarity index 100% rename from FunGame.Desktop/Image/red.png rename to FunGame.Desktop/Images/red.png diff --git a/FunGame.Desktop/Image/send.png b/FunGame.Desktop/Images/send.png similarity index 100% rename from FunGame.Desktop/Image/send.png rename to FunGame.Desktop/Images/send.png diff --git a/FunGame.Desktop/Image/yellow.png b/FunGame.Desktop/Images/yellow.png similarity index 100% rename from FunGame.Desktop/Image/yellow.png rename to FunGame.Desktop/Images/yellow.png diff --git a/FunGame.Desktop/Model/MainModel.cs b/FunGame.Desktop/Model/MainModel.cs index 4b475d1..8bf2871 100644 --- a/FunGame.Desktop/Model/MainModel.cs +++ b/FunGame.Desktop/Model/MainModel.cs @@ -1,4 +1,5 @@ using Milimoe.FunGame.Core.Api.Utility; +using Milimoe.FunGame.Core.Entity; using Milimoe.FunGame.Core.Library.Common.Event; using Milimoe.FunGame.Core.Library.Constant; using Milimoe.FunGame.Core.Library.Exception; @@ -30,18 +31,41 @@ namespace Milimoe.FunGame.Desktop.Model public bool Login() { + try + { + if (Socket != null && Socket.Send(SocketMessageType.Login, "Mili", "OK") == SocketResult.Success) + return true; + } + catch (Exception e) + { + Main?.GetMessage(e.GetStackTrace()); + } return false; } public bool Logout() { + try + { + //Socket?.Send(SocketMessageType.Logout, ""); + } + catch (Exception e) + { + Main?.GetMessage(e.GetStackTrace()); + } return false; } - public void Disconnect() { - + try + { + Socket?.Send(SocketMessageType.Disconnect, ""); + } + catch (Exception e) + { + Main?.GetMessage(e.GetStackTrace()); + } } public bool GetServerConnection() @@ -85,6 +109,11 @@ namespace Milimoe.FunGame.Desktop.Model } while (true) { + if (Others.Config.FunGame_isRetrying) + { + Main?.GetMessage("正在连接服务器,请耐心等待。"); + return ConnectResult.CanNotConnect; + } if (!Others.Config.FunGame_isConnected) { CurrentRetryTimes++; @@ -104,17 +133,29 @@ namespace Milimoe.FunGame.Desktop.Model // 发送连接请求 if (Socket.Send(SocketMessageType.Connect) == SocketResult.Success) { - // 接收连接回应 - if (Receiving() == SocketMessageType.Connect) + Task t = Task.Factory.StartNew(() => { - Main?.UpdateUI(MainControllerSet.Connected); - return ConnectResult.Success; - } + if (Receiving() == SocketMessageType.Connect) + { + Main?.GetMessage("连接服务器成功,请登录账号以体验FunGame。"); + Main?.UpdateUI(MainControllerSet.Connected); + StartReceiving(); + return ConnectResult.Success; + } + return ConnectResult.ConnectFailed; + }); + t.Wait(5000); + Main?.GetMessage("ERROR: 连接超时,远程服务器没有回应。", false); } Socket?.Close(); - return ConnectResult.CanNotConnect; + return ConnectResult.ConnectFailed; } } + else + { + Main?.GetMessage("已连接至服务器,请勿重复连接。"); + return ConnectResult.CanNotConnect; + } } } catch (Exception e) @@ -125,19 +166,6 @@ namespace Milimoe.FunGame.Desktop.Model 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 @@ -161,13 +189,26 @@ namespace Milimoe.FunGame.Desktop.Model return true; } - private string[] GetServerMessage() + private void StartReceiving() + { + ReceivingTask = Task.Factory.StartNew(() => + { + Thread.Sleep(100); + while (Socket != null && Socket.Connected) + { + Receiving(); + } + }); + Socket?.StartReceiving(ReceivingTask); + } + + private object[] GetServerMessage() { if (Socket != null && Socket.Connected) { return Socket.Receive(); } - return new string[2] { SocketSet.Unknown, "" }; + return new object[2] { SocketSet.Unknown, Array.Empty() }; } private SocketMessageType Receiving() @@ -176,17 +217,21 @@ namespace Milimoe.FunGame.Desktop.Model SocketMessageType result = SocketMessageType.Unknown; try { - string[] ServerMessage = GetServerMessage(); - string type = ServerMessage[0]; - string msg = ServerMessage[1]; + object[] ServerMessage = GetServerMessage(); + string type = (string)ServerMessage[0]; + object[] objs = (object[])ServerMessage[1]; + string msg = ""; switch (type) { case SocketSet.GetNotice: result = SocketMessageType.GetNotice; + if (objs.Length > 0) msg = (string)objs[0]; Config.FunGame_Notice = msg; break; + case SocketSet.Connect: result = SocketMessageType.Connect; + if (objs.Length > 0) msg = (string)objs[0]; string[] strings = msg.Split(';'); string ServerName = strings[0]; string ServerNotice = strings[1]; @@ -196,14 +241,35 @@ namespace Milimoe.FunGame.Desktop.Model // 设置等待登录的黄灯 Main?.UpdateUI(MainControllerSet.WaitLoginAndSetYellow); break; + case SocketSet.Login: + result = SocketMessageType.Login; break; + case SocketSet.CheckLogin: + result = SocketMessageType.CheckLogin; + if (objs.Length > 0) msg = (string)objs[0]; + Main?.GetMessage(msg); + Main?.UpdateUI(MainControllerSet.SetUser, true, TimeType.TimeOnly, new object[] { Factory.New(msg) }); break; + case SocketSet.Logout: break; + case SocketSet.Disconnect: + result = SocketMessageType.Disconnect; + if (objs.Length > 0) msg = (string)objs[0]; + Main?.GetMessage(msg); + Main?.UpdateUI(MainControllerSet.Disconnected); + Close(); break; + + case SocketSet.HeartBeat: + result = SocketMessageType.HeartBeat; + if (Usercfg.LoginUser != null) + Main?.UpdateUI(MainControllerSet.SetGreenAndPing); + break; + case SocketSet.Unknown: default: break; @@ -211,7 +277,10 @@ namespace Milimoe.FunGame.Desktop.Model } catch (Exception e) { + // 报错中断服务器连接 Main?.GetMessage(e.GetStackTrace(), false); + Main?.UpdateUI(MainControllerSet.Disconnected); + Close(); } return result; } diff --git a/FunGame.Desktop/Others/Constant.cs b/FunGame.Desktop/Others/Constant.cs index 8f58196..f39a6cf 100644 --- a/FunGame.Desktop/Others/Constant.cs +++ b/FunGame.Desktop/Others/Constant.cs @@ -40,7 +40,7 @@ namespace Milimoe.FunGame.Desktop.Others */ public static string SERVER_IPADRESS { get; set; } = ""; // 服务器IP地址 public static int SERVER_PORT { get; set; } = 0; // 服务器端口号 - public static Encoding DEFAULT_ENCODING { get; set; } = Encoding.UTF8; + public static Encoding DEFAULT_ENCODING { get; } = Core.Library.Constant.General.DEFAULT_ENCODING; /** * FunGame Configs diff --git a/FunGame.Desktop/Others/Usercfg.cs b/FunGame.Desktop/Others/Usercfg.cs index fe8f912..d679971 100644 --- a/FunGame.Desktop/Others/Usercfg.cs +++ b/FunGame.Desktop/Others/Usercfg.cs @@ -12,7 +12,7 @@ namespace Milimoe.FunGame.Desktop.Others /** * 玩家设定内容 */ - public static User? LoginUser = null; // 已登录的用户 - public static string LoginUserName = ""; // 已登录用户名 + public static User? LoginUser { get; set; } = null; // 已登录的用户 + public static string LoginUserName { get; set; } = ""; // 已登录用户名 } } diff --git a/FunGame.Desktop/Properties/Resources.resx b/FunGame.Desktop/Properties/Resources.resx index f59cfd2..f2aec2b 100644 --- a/FunGame.Desktop/Properties/Resources.resx +++ b/FunGame.Desktop/Properties/Resources.resx @@ -119,30 +119,30 @@ - ..\Image\back.jpg;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 - ..\Image\exit.png;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 - ..\Image\green.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 ..\Resources\LanaPixel.ttf;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - ..\Image\logo.ico;System.Drawing.Icon, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + ..\Images\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 + ..\Images\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 + ..\Images\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\send.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 + ..\Images\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/UI/Main/Main.cs b/FunGame.Desktop/UI/Main/Main.cs index 73d30ca..df2fb9f 100644 --- a/FunGame.Desktop/UI/Main/Main.cs +++ b/FunGame.Desktop/UI/Main/Main.cs @@ -60,6 +60,7 @@ namespace Milimoe.FunGame.Desktop.UI GetFunGameConfig(); // 获取FunGame配置 // 创建一个UI控制器 MainController = new MainController(this); + // 窗口句柄创建后,进行委托 Task.Factory.StartNew(() => { while (true) @@ -69,11 +70,10 @@ namespace Milimoe.FunGame.Desktop.UI break; } } - // 窗口句柄创建后,进行委托 void action() { if (Config.FunGame_isAutoConnect) - MainController.Do(MainControllerSet.Connected); + MainController.Do(MainControllerSet.GetServerConnection); } InvokeUpdateUI(action); }); @@ -90,7 +90,7 @@ namespace Milimoe.FunGame.Desktop.UI /// /// /// - public void UpdateUI(string? updatetype, bool time = false, TimeType timetype = TimeType.TimeOnly, object[]? objs = null) + public void UpdateUI(string? updatetype, bool time = true, TimeType timetype = TimeType.TimeOnly, object[]? objs = null) { void action() { @@ -162,18 +162,19 @@ namespace Milimoe.FunGame.Desktop.UI Task.Run(() => { Thread.Sleep(5000); - if (Others.Config.FunGame_isAutoRetry) MainController?.Do(MainControllerSet.Connect); // 再次判断是否开启自动重连 + if (Others.Config.FunGame_isAutoRetry) MainController?.Do(MainControllerSet.Connect); // 再次判断是否开启自动重连 }); if (time) - throw new Exception(DateTimeUtility.GetNowShortTime() + "\nERROR:连接服务器失败,5秒后自动尝试重连。"); + WritelnGameInfo(DateTimeUtility.GetDateTimeToString(timetype) + "\n连接服务器失败,5秒后自动尝试重连。"); else - throw new Exception("ERROR:连接服务器失败,5秒后自动尝试重连。"); + WritelnGameInfo("连接服务器失败,5秒后自动尝试重连。"); } else if (time) - throw new Exception(DateTimeUtility.GetNowShortTime() + "\nERROR:无法连接至服务器,请检查你的网络连接。"); + WritelnGameInfo(DateTimeUtility.GetDateTimeToString(timetype) + "\n无法连接至服务器,请检查你的网络连接。"); else - throw new Exception("ERROR:无法连接至服务器,请检查你的网络连接。"); + WritelnGameInfo("无法连接至服务器,请检查你的网络连接。"); + break; case Others.MainControllerSet.Disconnect: Others.Config.FunGame_isAutoRetry = false; @@ -199,7 +200,7 @@ namespace Milimoe.FunGame.Desktop.UI Task.Run(() => { Thread.Sleep(1000); - MainController?.Do(MainControllerSet.Connect); + MainController?.Do(MainControllerSet.Connect); }); } break; @@ -292,10 +293,10 @@ namespace Milimoe.FunGame.Desktop.UI string isAutoLogin = INIHelper.ReadINI("Config", "AutoLogin"); if (isAutoConncet != null && !isAutoConncet.Equals("") && (isAutoConncet.Equals("false") || isAutoConncet.Equals("true"))) Others.Config.FunGame_isAutoConnect = Convert.ToBoolean(isAutoConncet); - else throw new Exception("ERROR: 读取配置文件出错,参数格式不正确"); + else throw new Exception("读取配置文件出错,参数格式不正确"); if (isAutoLogin != null && !isAutoLogin.Equals("") && (isAutoLogin.Equals("false") || isAutoLogin.Equals("true"))) Others.Config.FunGame_isAutoLogin = Convert.ToBoolean(isAutoLogin); - else throw new Exception("ERROR: 读取配置文件出错,参数格式不正确"); + else throw new Exception("读取配置文件出错,参数格式不正确"); } else { @@ -1251,7 +1252,7 @@ namespace Milimoe.FunGame.Desktop.UI if (!Others.Config.FunGame_isRetrying) { NOW_CONNECTEDRETRY = -1; - MainController?.Do(MainControllerSet.Connect); + MainController?.Do(MainControllerSet.Connect); } else WritelnGameInfo(">> 你不能在连接服务器的同时重试连接!"); @@ -1304,7 +1305,7 @@ namespace Milimoe.FunGame.Desktop.UI Others.Constant.SERVER_IPADRESS = ip; Others.Constant.SERVER_PORT = port; NOW_CONNECTEDRETRY = -1; - MainController?.Do(MainControllerSet.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");