From 493e16b9c5b16c81854b3e2c1a2e22d40e74298c Mon Sep 17 00:00:00 2001 From: sheychen Date: Sat, 12 Nov 2016 12:33:10 +0100 Subject: [PATCH] Creation du protocol (WIP) Creation d'un protocol (en cours) --- AssemblyInfoCommon.cs | 8 +- Galactic Colors Control Common/Binary.cs | 125 +++++ Galactic Colors Control Common/Common.cs | 42 +- .../Galactic Colors Control Common.csproj | 6 + .../Properties/AssemblyInfo.cs | 9 +- .../Protocol/Data.cs | 40 ++ .../Protocol/EventData.cs | 37 ++ .../Protocol/RequestData.cs | 35 ++ .../Protocol/RequestResult.cs | 14 + .../Protocol/ResultData.cs | 47 ++ Galactic Colors Control Console/Program.cs | 16 +- .../Properties/AssemblyInfo.cs | 9 +- Galactic Colors Control GUI/Game1.cs | 210 ++++++-- Galactic Colors Control GUI/OpenTK.dll.config | 36 +- Galactic Colors Control GUI/Program.cs | 4 +- .../Properties/AssemblyInfo.cs | 9 +- Galactic Colors Control GUI/Utilities.cs | 4 +- Galactic Colors Control Server/App.config | 8 +- Galactic Colors Control Server/Client.cs | 4 +- .../Commands/BroadcastCommand.cs | 26 + .../Commands/ClearCommand.cs | 22 +- .../Commands/Client/CountCommand.cs | 11 +- .../Commands/Client/KickCommand.cs | 34 +- .../Commands/Client/ListCommand.cs | 33 +- .../Commands/Client/StatusCommand.cs | 31 +- .../Commands/ConnectCommand.cs | 53 +- .../Commands/ExitCommand.cs | 11 +- .../Commands/HelpCommand.cs | 44 +- .../Commands/ICommand.cs | 7 +- .../Commands/LogLevelCommand.cs | 14 +- .../Commands/Manager.cs | 74 ++- .../Commands/Party/PartyClientCommand.cs | 25 +- .../Commands/Party/PartyCloseCommand.cs | 30 +- .../Commands/Party/PartyCreateCommand.cs | 64 +-- .../Commands/Party/PartyJoinCommand.cs | 92 ++-- .../Commands/Party/PartyKickCommand.cs | 41 +- .../Commands/Party/PartyLeaveCommand.cs | 32 +- .../Commands/Party/PartyListCommand.cs | 17 +- .../Commands/Party/PartyOpenCommand.cs | 30 +- .../Commands/Party/PartyPasswordCommand.cs | 35 +- .../Commands/Party/PartyStatusCommand.cs | 23 +- .../Commands/Party/PartyStopCommand.cs | 27 +- .../Commands/PingCommand.cs | 12 +- .../Commands/SayCommand.cs | 34 ++ .../Commands/Server/ServerCloseCommand.cs | 24 +- .../Commands/Server/ServerOpenCommand.cs | 24 +- .../Commands/Server/ServerStatusCommand.cs | 24 +- .../Commands/Server/ServerStopCommand.cs | 11 +- .../Commands/TimeCommand.cs | 12 +- Galactic Colors Control Server/Config.cs | 17 +- .../ConfigSchema.xsd | 2 +- .../Galactic Colors Control Server.csproj | 2 + Galactic Colors Control Server/Logger.cs | 73 ++- Galactic Colors Control Server/Party.cs | 6 +- Galactic Colors Control Server/Program.cs | 470 +++++++++--------- .../Properties/AssemblyInfo.cs | 9 +- Galactic Colors Control Server/Utilities.cs | 189 +++---- Galactic Colors Control.sln | 10 +- Galactic Colors Control/App.config | 8 +- Galactic Colors Control/Program.cs | 154 +++--- .../Properties/AssemblyInfo.cs | 7 +- Readme.md | 2 +- 62 files changed, 1456 insertions(+), 1073 deletions(-) create mode 100644 Galactic Colors Control Common/Binary.cs create mode 100644 Galactic Colors Control Common/Protocol/Data.cs create mode 100644 Galactic Colors Control Common/Protocol/EventData.cs create mode 100644 Galactic Colors Control Common/Protocol/RequestData.cs create mode 100644 Galactic Colors Control Common/Protocol/RequestResult.cs create mode 100644 Galactic Colors Control Common/Protocol/ResultData.cs create mode 100644 Galactic Colors Control Server/Commands/BroadcastCommand.cs create mode 100644 Galactic Colors Control Server/Commands/SayCommand.cs diff --git a/AssemblyInfoCommon.cs b/AssemblyInfoCommon.cs index 611a11f..dc9abee 100644 --- a/AssemblyInfoCommon.cs +++ b/AssemblyInfoCommon.cs @@ -1,9 +1,7 @@ using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; //Common AssemblyInfo -// Les informations générales relatives à un assembly dépendent de +// Les informations générales relatives à un assembly dépendent de // l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations // associées à un assembly. [assembly: AssemblyCompany("sheychen")] @@ -12,11 +10,11 @@ using System.Runtime.InteropServices; // Les informations de version pour un assembly se composent des quatre valeurs suivantes : // // Version principale -// Version secondaire +// Version secondaire // Numéro de build // Révision // -// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut +// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut // en utilisant '*', comme indiqué ci-dessous : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.1.1")] diff --git a/Galactic Colors Control Common/Binary.cs b/Galactic Colors Control Common/Binary.cs new file mode 100644 index 0000000..0de67f7 --- /dev/null +++ b/Galactic Colors Control Common/Binary.cs @@ -0,0 +1,125 @@ +using System; +using System.Linq; +using System.Text; + +namespace Galactic_Colors_Control_Common +{ + public static class Binary + { + public static bool ToBool(ref byte[] bytes) + { + byte[] data = new byte[1]; + data = bytes.Take(1).ToArray(); + RemoveFirst(ref bytes, 1); + return data[1] == 1 ? true : false; + } + + public static byte[] FromBool(bool x) + { + return x ? new byte[1] { 1 } : new byte[1] { 0 }; + } + + public static string ToString(ref byte[] bytes) + { + int len = ToInt(ref bytes); + string text = Encoding.ASCII.GetString(bytes.Take(len).ToArray()); + RemoveFirst(ref bytes, len); + return text; + } + + public static byte[] FromString(string text) + { + byte[] data = Encoding.ASCII.GetBytes(text); + return AddBytes(FromInt(data.Length), data); + } + + public static int ToInt(ref byte[] bytes) + { + if (bytes == null) + return -1; + + if (bytes.Length < 4) + return -1; + + byte[] data = new byte[4]; + data = bytes.Take(4).ToArray(); + data.Reverse(); + RemoveFirst(ref bytes, 4); + return BitConverter.ToInt32(data, 0); + } + + public static byte[] FromInt(int x) + { + byte[] data = new byte[4]; + data = BitConverter.GetBytes(x); + return data; + } + + public static string[] ToStringArray(ref byte[] bytes) + { + int len = ToInt(ref bytes); + if (len < 1 || len > 10000) + return new string[0]; + + string[] data = new string[len]; + for (int i = 0; i < len; i++) + { + data[i] = ToString(ref bytes); + } + return data; + } + + public static byte[] FromStringArray(string[] array) + { + if (array == null) + return new byte[0]; + + byte[] data = FromInt(array.Length); + for (int i = 0; i < array.Length; i++) + { + data = AddBytes(data, FromString(array[i])); + } + return data; + } + + public static int[] ToIntArray(ref byte[] bytes) + { + int len = ToInt(ref bytes); + int[] data = new int[len]; + for (int i = 0; i < len; i++) + { + data[i] = ToInt(ref bytes); + } + return data; + } + + public static byte[] FromIntArray(int[] array) + { + byte[] data = FromInt(array.Length); + for (int i = 0; i < array.Length; i++) + { + data = AddBytes(data, FromInt(array[i])); + } + return data; + } + + public static byte[] AddBytes(params byte[][] arguments) + { + byte[] res = new byte[arguments.Sum(a => a.Length)]; + int offset = 0; + for (int i = 0; i < arguments.Length; i++) + { + Buffer.BlockCopy(arguments[i], 0, res, offset, arguments[i].Length); + offset += arguments[i].Length; + } + return res; + } + + public static void RemoveFirst(ref byte[] bytes, int count) + { + byte[] newbytes = new byte[bytes.Length - count]; + newbytes = bytes.Skip(count).ToArray(); + bytes = newbytes; + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Common/Common.cs b/Galactic Colors Control Common/Common.cs index 97708c3..8c63ca2 100644 --- a/Galactic Colors Control Common/Common.cs +++ b/Galactic Colors Control Common/Common.cs @@ -1,13 +1,45 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Galactic_Colors_Control_Common { public static class Common { - public enum dataType { message, data }; + public static string[] Strings(params string[] args) + { + return args; + } + + public static string ArrayToString(string[] array) + { + string text = ""; + if (array != null) + { + foreach (string str in array) + { + text += (str + Environment.NewLine); + } + } + return text; + } + + public static string ArrayToString(int[] array) + { + string text = ""; + foreach (int i in array) + { + text += (i.ToString() + Environment.NewLine); + } + return text; + } + + public static string[] SplitArgs(string text) + { + return text.Split('"') + .Select((element, index) => index % 2 == 0 + ? element.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) + : new string[] { element }) + .SelectMany(element => element).ToArray(); + } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Common/Galactic Colors Control Common.csproj b/Galactic Colors Control Common/Galactic Colors Control Common.csproj index 1c29985..3455210 100644 --- a/Galactic Colors Control Common/Galactic Colors Control Common.csproj +++ b/Galactic Colors Control Common/Galactic Colors Control Common.csproj @@ -47,8 +47,14 @@ Properties\AssemblyInfoCommon.cs + + + + + + - - - - - - - + + + + + + + \ No newline at end of file diff --git a/Galactic Colors Control GUI/Program.cs b/Galactic Colors Control GUI/Program.cs index 7360770..2a68843 100644 --- a/Galactic Colors Control GUI/Program.cs +++ b/Galactic Colors Control GUI/Program.cs @@ -11,10 +11,10 @@ namespace Galactic_Colors_Control_GUI /// The main entry point for the application. /// [STAThread] - static void Main() + private static void Main() { using (var game = new Game1()) game.Run(); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control GUI/Properties/AssemblyInfo.cs b/Galactic Colors Control GUI/Properties/AssemblyInfo.cs index 1ad66d6..a5affe2 100644 --- a/Galactic Colors Control GUI/Properties/AssemblyInfo.cs +++ b/Galactic Colors Control GUI/Properties/AssemblyInfo.cs @@ -1,8 +1,7 @@ using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Galactic Colors Control GUI")] @@ -12,10 +11,10 @@ using System.Runtime.InteropServices; [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("606d35be-02e8-4a7e-978e-04c2aca6ccd7")] +[assembly: Guid("606d35be-02e8-4a7e-978e-04c2aca6ccd7")] \ No newline at end of file diff --git a/Galactic Colors Control GUI/Utilities.cs b/Galactic Colors Control GUI/Utilities.cs index c4f6be1..40ae3b0 100644 --- a/Galactic Colors Control GUI/Utilities.cs +++ b/Galactic Colors Control GUI/Utilities.cs @@ -4,7 +4,7 @@ using System.IO; namespace Galactic_Colors_Control_GUI { - static class Utilities + internal static class Utilities { /// /// Load Texture2D from files @@ -38,4 +38,4 @@ namespace Galactic_Colors_Control_GUI } } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/App.config b/Galactic Colors Control Server/App.config index d1428ad..5035d4f 100644 --- a/Galactic Colors Control Server/App.config +++ b/Galactic Colors Control Server/App.config @@ -1,6 +1,6 @@ - - - - + + + + \ No newline at end of file diff --git a/Galactic Colors Control Server/Client.cs b/Galactic Colors Control Server/Client.cs index 12a0522..b20ad5f 100644 --- a/Galactic Colors Control Server/Client.cs +++ b/Galactic Colors Control Server/Client.cs @@ -1,6 +1,4 @@ -using System.Net.Sockets; - -namespace Galactic_Colors_Control_Server +namespace Galactic_Colors_Control_Server { public class Client { diff --git a/Galactic Colors Control Server/Commands/BroadcastCommand.cs b/Galactic Colors Control Server/Commands/BroadcastCommand.cs new file mode 100644 index 0000000..b3df2ff --- /dev/null +++ b/Galactic Colors Control Server/Commands/BroadcastCommand.cs @@ -0,0 +1,26 @@ +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; + +namespace Galactic_Colors_Control_Server.Commands +{ + public class BroadcastCommand : ICommand + { + public string DescText { get { return "Sends message to all clients."; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } } + public string HelpText { get { return "Use 'broadcast [text]' to send message to all clients."; } } + public bool IsClient { get { return false; } } + public bool IsClientSide { get { return false; } } + public bool IsNoConnect { get { return false; } } + public bool IsServer { get { return true; } } + public int maxArgs { get { return 1; } } + public int minArgs { get { return 1; } } + public string Name { get { return "broadcast"; } } + + public RequestResult Execute(string[] args, Socket soc, bool server = false) + { + Utilities.Broadcast(new EventData(EventTypes.ChatMessage, Common.Strings("Server : " + args[1]))); + return new RequestResult(ResultTypes.OK); + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/ClearCommand.cs b/Galactic Colors Control Server/Commands/ClearCommand.cs index 9d204d1..d423891 100644 --- a/Galactic Colors Control Server/Commands/ClearCommand.cs +++ b/Galactic Colors Control Server/Commands/ClearCommand.cs @@ -1,4 +1,6 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +9,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "clear"; } } public string DescText { get { return "Clears the console screen."; } } - public string HelpText { get { return "Use /clear to execute Console.Clear()."; } } + public string HelpText { get { return "Use 'clear' to execute Console.Clear()."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -16,10 +18,18 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { - Console.Clear(); - Console.Write(">"); + if (server) + { + Console.Clear(); + Console.Write(">"); + return new RequestResult(ResultTypes.OK); + } + else + { + return new RequestResult(ResultTypes.Error, Common.Strings("Client Side")); + } } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Client/CountCommand.cs b/Galactic Colors Control Server/Commands/Client/CountCommand.cs index 54e5d3e..1a32726 100644 --- a/Galactic Colors Control Server/Commands/Client/CountCommand.cs +++ b/Galactic Colors Control Server/Commands/Client/CountCommand.cs @@ -1,4 +1,5 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "count"; } } public string DescText { get { return "Counts connected clients."; } } - public string HelpText { get { return "Use /client count to show connected clients count and size"; } } + public string HelpText { get { return "Use 'client count' to show connected clients count and size"; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.client; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -16,9 +17,9 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { - Utilities.Return(Program.clients.Count + "/" + Program.config.size, soc, server); + return new RequestResult(ResultTypes.OK, Common.Strings(Program.clients.Count.ToString(), Program.config.size.ToString())); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Client/KickCommand.cs b/Galactic Colors Control Server/Commands/Client/KickCommand.cs index 58d1256..6b1e0aa 100644 --- a/Galactic Colors Control Server/Commands/Client/KickCommand.cs +++ b/Galactic Colors Control Server/Commands/Client/KickCommand.cs @@ -1,7 +1,5 @@ using Galactic_Colors_Control_Common; -using System; -using System.Collections.Generic; -using System.Linq; +using Galactic_Colors_Control_Common.Protocol; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -10,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "kick"; } } public string DescText { get { return "Kicks selected client."; } } - public string HelpText { get { return "Use /client kick [username] to kick client from server."; } } + public string HelpText { get { return "Use 'client kick [username] ' to kick client from server."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.client; } } public bool IsServer { get { return true; } } public bool IsClient { get { return false; } } @@ -19,29 +17,27 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 1; } } public int maxArgs { get { return 2; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { Socket target = null; - foreach(Socket client in Program.clients.Keys) + foreach (Socket client in Program.clients.Keys) { - if(Utilities.GetName(client) == args[2]) { target = client; } + if (Utilities.GetName(client) == args[2]) { target = client; } } - if (target != null) + if (target == null) + return new RequestResult(ResultTypes.Error, Common.Strings("Can't find")); + + Logger.Write(args[2] + " was kick by server.", Logger.logType.info, Logger.logConsole.show); + if (args.Length > 2) { - Logger.Write(args[2] + " was kick by server.", Logger.logType.info); - if (args.Length > 2) - { - Utilities.Send(target, "/kick " + args[3], Common.dataType.message); - Logger.Write("because" + args[2], Logger.logType.debug); - } - else { - Utilities.Send(target, "/kick", Common.dataType.message); - } + Utilities.Send(target, new EventData(EventTypes.ServerKick, Common.Strings(args[3]))); + Logger.Write("because" + args[3], Logger.logType.debug); } else { - Utilities.Return("Can't find " + args[2], soc, server); + Utilities.Send(target, new EventData(EventTypes.ServerKick)); } + return new RequestResult(ResultTypes.OK); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Client/ListCommand.cs b/Galactic Colors Control Server/Commands/Client/ListCommand.cs index 2b97c76..dbea879 100644 --- a/Galactic Colors Control Server/Commands/Client/ListCommand.cs +++ b/Galactic Colors Control Server/Commands/Client/ListCommand.cs @@ -1,4 +1,5 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "list"; } } public string DescText { get { return "Lists connected clients."; } } - public string HelpText { get { return "Use /client list to display all connected client username or IP."; } } + public string HelpText { get { return "Use 'client list' to display all connected client username or IP."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.client; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -16,15 +17,29 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { - string text = " "; - foreach (Socket socket in Program.clients.Keys) + if (server) { - text += (Utilities.GetName(socket) + ", "); + string text = " "; + foreach (Socket socket in Program.clients.Keys) + { + text += (Utilities.GetName(socket) + ", "); + } + text = text.Remove(text.Length - 2, 2); + return new RequestResult(ResultTypes.OK, Common.Strings(text)); + } + else + { + string[] data = new string[Program.clients.Count]; + int i = 0; + foreach (Socket socket in Program.clients.Keys) + { + data[i] = (Utilities.GetName(socket) + ", "); + i++; + } + return new RequestResult(ResultTypes.OK, data); } - text = text.Remove(text.Length - 2, 2); - Utilities.Return(text, soc, server); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Client/StatusCommand.cs b/Galactic Colors Control Server/Commands/Client/StatusCommand.cs index e6a3271..54ef8dc 100644 --- a/Galactic Colors Control Server/Commands/Client/StatusCommand.cs +++ b/Galactic Colors Control Server/Commands/Client/StatusCommand.cs @@ -1,4 +1,5 @@ using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; using System; using System.Net; using System.Net.Sockets; @@ -9,37 +10,33 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "status"; } } public string DescText { get { return "Get client status."; } } - public string HelpText { get { return "Use /client status [username] to show client status."; } } + public string HelpText { get { return "Use 'client status [username]' to show client status."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.client; } } public bool IsServer { get { return true; } } public bool IsClient { get { return false; } } public bool IsClientSide { get { return false; } } - public bool IsNoConnect { get { return true; } } + public bool IsNoConnect { get { return false; } } public int minArgs { get { return 1; } } public int maxArgs { get { return 1; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { Socket target = null; foreach (Socket client in Program.clients.Keys) { if (Utilities.GetName(client) == args[2]) { target = client; } } - if (target != null) + if (target == null) + return new RequestResult(ResultTypes.Error, Common.Strings("Can't find")); + + string text = ""; + text += ("Name : " + Utilities.GetName(target) + Environment.NewLine); + text += ("IP : " + ((IPEndPoint)target.LocalEndPoint).Address.ToString() + Environment.NewLine); + if (Program.clients[target].party != null) { - string text = ""; - text += ("Name : " + Utilities.GetName(target) + Environment.NewLine); - text += ("IP : " + ((IPEndPoint)target.LocalEndPoint).Address.ToString() + Environment.NewLine); - if(Program.clients[target].party != null) - { - text += ("Party : " + Program.clients[target].party + Environment.NewLine); - } - Utilities.ConsoleWrite(text); - } - else - { - Utilities.Return("Can't find " + args[2], soc, server); + text += ("Party : " + Program.clients[target].party + Environment.NewLine); } + return new RequestResult(ResultTypes.OK, Common.Strings(text)); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/ConnectCommand.cs b/Galactic Colors Control Server/Commands/ConnectCommand.cs index 8de0284..7e2ed4d 100644 --- a/Galactic Colors Control Server/Commands/ConnectCommand.cs +++ b/Galactic Colors Control Server/Commands/ConnectCommand.cs @@ -1,7 +1,7 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; using System.Net; using System.Net.Sockets; -using Galactic_Colors_Control_Common; namespace Galactic_Colors_Control_Server.Commands { @@ -9,7 +9,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "connect"; } } public string DescText { get { return "Gets an username."; } } - public string HelpText { get { return "Use /connect [username] to start identification"; } } + public string HelpText { get { return "Use 'connect [username]' to start identification"; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } } public bool IsServer { get { return false; } } public bool IsClient { get { return true; } } @@ -18,34 +18,29 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 1; } } public int maxArgs { get { return 1; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { - if (!Utilities.IsConnect(soc)) + if (Utilities.IsConnect(soc)) + return new RequestResult(ResultTypes.Error, Common.Strings("Connected")); + + if (args[1].Length < 3) + return new RequestResult(ResultTypes.Error, Common.Strings("Too Short")); + + Logger.Write("Identifiaction request from " + Utilities.GetName(soc), Logger.logType.debug); + bool allreadyconnected = false; + args[1] = args[1][0].ToString().ToUpper()[0] + args[1].Substring(1); + foreach (Client client in Program.clients.Values) { - Logger.Write("Identifiaction request from " + Utilities.GetName(soc), Logger.logType.debug); - bool allreadyconnected = false; - foreach(Client client in Program.clients.Values) - { - if(client.pseudo == args[1]) { allreadyconnected = true; break; } - } - if (!allreadyconnected) - { - Program.clients[soc].status = 0; - //args[1] = args[1][0].ToString().ToUpper()[0] + args[1].Substring(1); - Program.clients[soc].pseudo = args[1]; - Utilities.Send(soc, "/connected", Common.dataType.message); - Utilities.Broadcast(args[1] + " joined the server", Common.dataType.message); - Logger.Write("Identified as " + Utilities.GetName(soc) + " form " + ((IPEndPoint)soc.LocalEndPoint).Address.ToString(), Logger.logType.info); - } - else - { - Utilities.Send(soc, "/allreadytaken", Common.dataType.message); - } - } - else - { - Utilities.Send(soc, "You are allready " + Utilities.GetName(soc), Common.dataType.message); + if (client.pseudo == args[1]) { allreadyconnected = true; break; } } + if (allreadyconnected) + return new RequestResult(ResultTypes.Error, Common.Strings("Taken")); + + Program.clients[soc].status = 0; + Program.clients[soc].pseudo = args[1]; + Utilities.Broadcast(new EventData(EventTypes.ServerJoin, Common.Strings(args[1]))); + Logger.Write("Identified as " + Utilities.GetName(soc) + " form " + ((IPEndPoint)soc.LocalEndPoint).Address.ToString(), Logger.logType.info); + return new RequestResult(ResultTypes.OK, Common.Strings(args[1])); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/ExitCommand.cs b/Galactic Colors Control Server/Commands/ExitCommand.cs index cea265e..b473af9 100644 --- a/Galactic Colors Control Server/Commands/ExitCommand.cs +++ b/Galactic Colors Control Server/Commands/ExitCommand.cs @@ -1,5 +1,5 @@ using Galactic_Colors_Control_Common; -using System; +using Galactic_Colors_Control_Common.Protocol; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -8,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "exit"; } } public string DescText { get { return "Leave the server."; } } - public string HelpText { get { return "Use /exit to stop actual program."; } } + public string HelpText { get { return "Use 'exit' to stop actual program."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } } public bool IsServer { get { return false; } } public bool IsClient { get { return true; } } @@ -17,7 +17,7 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { soc.Shutdown(SocketShutdown.Both); Logger.Write("Client disconnected from " + Utilities.GetName(soc), Logger.logType.info); @@ -25,8 +25,9 @@ namespace Galactic_Colors_Control_Server.Commands bool connected = Program.clients[soc].status != -1; soc.Close(); Program.clients.Remove(soc); - if (connected) { Utilities.Broadcast(username + " leave the server", Common.dataType.message); } + if (connected) { Utilities.Broadcast(new EventData(EventTypes.ServerLeave, Common.Strings(username))); } Logger.Write("Size: " + Program.clients.Count + "/" + Program.config.size, Logger.logType.debug); + return new RequestResult(ResultTypes.OK); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/HelpCommand.cs b/Galactic Colors Control Server/Commands/HelpCommand.cs index 9b3c502..b410a07 100644 --- a/Galactic Colors Control Server/Commands/HelpCommand.cs +++ b/Galactic Colors Control Server/Commands/HelpCommand.cs @@ -1,4 +1,6 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; @@ -9,7 +11,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "help"; } } public string DescText { get { return "Shows the help."; } } - public string HelpText { get { return "Use /help [command] to display command help. (-all for full help)"; } } + public string HelpText { get { return "Use 'help [command]' to display command help. ('hell -all' for full help)"; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -18,7 +20,7 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 2; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { bool isGroup = false; bool isAll = false; @@ -33,7 +35,7 @@ namespace Galactic_Colors_Control_Server.Commands List list = new List(); foreach (ICommand com in Manager.commands) { - if(Manager.CanAccess(com, soc, server)) + if (Manager.CanAccess(com, soc, server)) { if (!isGroup || (isGroup && com.Group == (Manager.CommandGroup)Enum.Parse(typeof(Manager.CommandGroup), args[1]))) { @@ -42,14 +44,14 @@ namespace Galactic_Colors_Control_Server.Commands } } } - list.Sort((x,y) => x.Group.CompareTo(y.Group)); - string text = "Use /help [command] for more informations." + Environment.NewLine + "Available commands:" + Environment.NewLine; + list.Sort((x, y) => x.Group.CompareTo(y.Group)); + string text = "Use 'help [command]' for more informations." + Environment.NewLine + "Available commands:" + Environment.NewLine; Manager.CommandGroup actualGroup = 0; foreach (ICommand com in list) { - if(com.Group != actualGroup) + if (com.Group != actualGroup) { - text += (Environment.NewLine + " " + com.Group.ToString() + Environment.NewLine + ((isGroup || isAll) ? "" : (" Use /help " + com.Group.ToString()))); + text += (Environment.NewLine + " " + com.Group.ToString() + Environment.NewLine + ((isGroup || isAll) ? "" : (" Use 'help " + com.Group.ToString() + "'"))); actualGroup = com.Group; } if ((!(isGroup || isAll) && com.Group == 0) || (isGroup || isAll)) @@ -57,28 +59,20 @@ namespace Galactic_Colors_Control_Server.Commands text += (" " + (com.Group != 0 ? new string(' ', 4) : "") + com.Name + new string(' ', maxLen - com.Name.Length - (com.Group == 0 ? 0 : 4)) + " : " + com.DescText + Environment.NewLine); } } - Utilities.Return(text, soc, server); + return new RequestResult(ResultTypes.OK, Common.Strings(text)); } else { ICommand command = null; args = args.Skip(1).ToArray(); - if (Manager.TryGetCommand(args, ref command)) - { - if (Manager.CanAccess(command, soc, server)) - { - Utilities.Return(command.HelpText, soc, server); - } - else - { - Utilities.Return("Any help for " + Manager.CommandToString(args), soc, server); - } - } - else - { - Utilities.Return("Any help for " + Manager.CommandToString(args), soc, server); - } + if (!Manager.TryGetCommand(args, ref command)) + return new RequestResult(ResultTypes.Error, Common.Strings("Any Command")); + + if (!Manager.CanAccess(command, soc, server)) + return new RequestResult(ResultTypes.Error, Common.Strings("Any Command")); + + return new RequestResult(ResultTypes.OK, Common.Strings(command.HelpText)); } } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/ICommand.cs b/Galactic Colors Control Server/Commands/ICommand.cs index d7fbffb..f68f293 100644 --- a/Galactic Colors Control Server/Commands/ICommand.cs +++ b/Galactic Colors Control Server/Commands/ICommand.cs @@ -1,4 +1,5 @@ -using System.Net.Sockets; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands { @@ -15,6 +16,6 @@ namespace Galactic_Colors_Control_Server.Commands int minArgs { get; } int maxArgs { get; } - void Execute(string[] args, Socket soc = null, bool server = false); + RequestResult Execute(string[] args, Socket soc = null, bool server = false); } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/LogLevelCommand.cs b/Galactic Colors Control Server/Commands/LogLevelCommand.cs index 9244ba4..f5cb6ed 100644 --- a/Galactic Colors Control Server/Commands/LogLevelCommand.cs +++ b/Galactic Colors Control Server/Commands/LogLevelCommand.cs @@ -1,4 +1,6 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +9,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "loglevel"; } } public string DescText { get { return "Change console loglevel."; } } - public string HelpText { get { return "Use /loglevel [loglevel] to change Loglevel."; } } + public string HelpText { get { return "Use 'loglevel [loglevel]' to change Loglevel. (dev ,debug, info, warm, error, fatal)"; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } } public bool IsServer { get { return true; } } public bool IsClient { get { return false; } } @@ -16,16 +18,16 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 1; } } public int maxArgs { get { return 1; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { if (Enum.TryParse(args[1], true, out Program.config.logLevel)) { - Utilities.ConsoleWrite("LogLevel: " + Program.config.logLevel.ToString()); + return new RequestResult(ResultTypes.OK, Common.Strings(Program.config.logLevel.ToString())); } else { - Utilities.ConsoleWrite("Incorrect argument (debug, info, important, error, fatal)"); + return new RequestResult(ResultTypes.Error, Common.Strings("Incorrect argument")); } } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Manager.cs b/Galactic Colors Control Server/Commands/Manager.cs index 1554015..a0defc2 100644 --- a/Galactic Colors Control Server/Commands/Manager.cs +++ b/Galactic Colors Control Server/Commands/Manager.cs @@ -1,4 +1,6 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; @@ -9,7 +11,10 @@ namespace Galactic_Colors_Control_Server.Commands public class Manager { public static List commands { get; private set; } = new List(); - public enum CommandGroup { root, server, party, client} + + public enum CommandGroup { root, server, party, client } + + private static RequestResult AnyCommand = new RequestResult(ResultTypes.Error, Common.Strings("Any Command")); /// /// Find all ICommand and add them to commands @@ -31,52 +36,39 @@ namespace Galactic_Colors_Control_Server.Commands /// command with args /// Sender socket /// Is server? - public static void Execute(string[] args, Socket soc = null, bool server = false) + public static RequestResult Execute(string[] args, Socket soc = null, bool server = false) { ICommand command = null; - if (TryGetCommand(args, ref command)) - { - if (CanAccess(command, soc, server)) - { - if (!server && command.IsClientSide) - { - Utilities.Return("It's a client side command", soc, server); - } - else - { - if (args.Length - (command.Group == 0 ? 0 : 1) > command.minArgs) - { - if (args.Length - (command.Group == 0 ? 1 : 2) <= command.maxArgs) - { - command.Execute(args, soc, server); - } - else - { - Utilities.Return("Command " + CommandToString(command) + " require at most " + command.maxArgs + " argument(s).", soc, server); - } - } + if (!TryGetCommand(args, ref command)) + return AnyCommand; - else - { - Utilities.Return("Command " + CommandToString(command) + " require at least " + command.minArgs + " argument(s).", soc, server); - } - } - } - else - { - Utilities.Return("Unknown command : " + CommandToString(args), soc, server); - } - } - else + if (!CanAccess(command, soc, server)) + return AnyCommand; + + if (!server && command.IsClientSide) + return new RequestResult(ResultTypes.Error, Common.Strings("Client Side")); + + if (args.Length - (command.Group == 0 ? 0 : 1) <= command.minArgs) + return new RequestResult(ResultTypes.Error, new string[2] { "Too Short", command.minArgs.ToString() }); + + if (args.Length - (command.Group == 0 ? 1 : 2) > command.maxArgs) + return new RequestResult(ResultTypes.Error, new string[2] { "Too Long", command.maxArgs.ToString() }); + + try { - Utilities.Return("Unknown command : " + CommandToString(args), soc, server); + return command.Execute(args, soc, server); + } + catch (Exception e) + { + Logger.Write("Command " + args[0] + " Exception : " + e.Message, Logger.logType.error); + return new RequestResult(ResultTypes.Error, Common.Strings("Execute Exception")); } } public static string CommandToString(ICommand command) { string text = ""; - if(command.Group != 0) { text += (command.Group.ToString() + " "); } + if (command.Group != 0) { text += (command.Group.ToString() + " "); } text += command.Name; return text; } @@ -90,7 +82,7 @@ namespace Galactic_Colors_Control_Server.Commands if (args.Length > 0) { string text = ""; - foreach(string arg in args) + foreach (string arg in args) { text += (arg + " "); } @@ -151,7 +143,7 @@ namespace Galactic_Colors_Control_Server.Commands { if (command.IsClient) { - if(!Utilities.IsConnect(soc)) + if (!Utilities.IsConnect(soc)) { return command.IsNoConnect; } @@ -167,4 +159,4 @@ namespace Galactic_Colors_Control_Server.Commands } } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyClientCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyClientCommand.cs index ac60f20..4077030 100644 --- a/Galactic Colors Control Server/Commands/Party/PartyClientCommand.cs +++ b/Galactic Colors Control Server/Commands/Party/PartyClientCommand.cs @@ -1,4 +1,5 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "client"; } } public string DescText { get { return "Lists party clients."; } } - public string HelpText { get { return "Use /party client to show party clients list."; } } + public string HelpText { get { return "Use 'party client' to show party clients list."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -16,18 +17,20 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { int partyId = -1; - if (Utilities.AccessParty(ref partyId, false, soc, server)) + if (!Utilities.AccessParty(ref partyId, args, false, soc, server)) + return new RequestResult(ResultTypes.Error, Common.Strings("Access")); + + string[] data = new string[Program.parties[partyId].clients.Count]; + int i = 0; + foreach (Socket client in Program.parties[partyId].clients) { - string text = " "; - foreach(Socket client in Program.parties[partyId].clients) - { - text += (Utilities.GetName(client) + Environment.NewLine + " "); - } - Utilities.Return(text, soc, server); + data[i] = Utilities.GetName(client); + i++; } + return new RequestResult(ResultTypes.OK, data); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyCloseCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyCloseCommand.cs index 5591d62..a0f71c5 100644 --- a/Galactic Colors Control Server/Commands/Party/PartyCloseCommand.cs +++ b/Galactic Colors Control Server/Commands/Party/PartyCloseCommand.cs @@ -1,4 +1,6 @@ -using System.Net.Sockets; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands { @@ -6,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "close"; } } public string DescText { get { return "Closes party."; } } - public string HelpText { get { return "Use /party close to close party for join."; } } + public string HelpText { get { return "Use 'party close' to close party for join."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -15,21 +17,17 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { int partyId = -1; - if (Utilities.AccessParty(ref partyId, true,soc, server)) - { - if (Program.parties[partyId].open) - { - Program.parties[partyId].open = false; - Utilities.Return("Party closed", soc, server); - } - else - { - Utilities.Return("Party allready close", soc, server); - } - } + if (!Utilities.AccessParty(ref partyId, args, true, soc, server)) + return new RequestResult(ResultTypes.Error, Common.Strings("Access")); + + if (!Program.parties[partyId].open) + return new RequestResult(ResultTypes.Error, Common.Strings("Allready")); + + Program.parties[partyId].open = false; + return new RequestResult(ResultTypes.OK); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyCreateCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyCreateCommand.cs index a194712..f37a2f5 100644 --- a/Galactic Colors Control Server/Commands/Party/PartyCreateCommand.cs +++ b/Galactic Colors Control Server/Commands/Party/PartyCreateCommand.cs @@ -1,4 +1,6 @@ -using System.Net.Sockets; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands { @@ -6,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "create"; } } public string DescText { get { return "Create new party."; } } - public string HelpText { get { return "Use /party create [name] [size] to create new party."; } } + public string HelpText { get { return "Use 'party create [name] [size]' to create new party."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -15,48 +17,32 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 2; } } public int maxArgs { get { return 2; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { - if (server || (!server && Program.clients[soc].partyID == -1)) + if (!server && Program.clients[soc].partyID != -1) + return new RequestResult(ResultTypes.Error, Common.Strings("Allready")); + + int size; + if (!int.TryParse(args[3], out size)) + return new RequestResult(ResultTypes.Error, Common.Strings("Format")); + + if (size < 1) + return new RequestResult(ResultTypes.Error, Common.Strings("Too Small")); + + if (size > Program.config.size) + return new RequestResult(ResultTypes.Error, Common.Strings("Too Big")); + + Program.AddParty(new Party(args[2], size, Utilities.GetName(soc))); + Logger.Write("Party " + args[2] + " create with " + size + " slots as " + Program.GetPartyID(false), Logger.logType.info); + if (server) { - int size; - if (int.TryParse(args[3], out size)) - { - if (size > 0) - { - if (size <= Program.config.size) - { - Logger.Write("Party " + args[2] + " create with " + size + " slots as " + Program.partyID, Logger.logType.info); - Program.AddParty(new Party(args[2], size, Utilities.GetName(soc))); - if (server) - { - Program.selectedParty = Program.partyID-1; - } - else - { - Program.clients[soc].partyID = Program.partyID-1; - Utilities.Return("Party " + args[2] + " create with " + size + " slots as " + (Program.partyID-1), soc, server); - } - } - else - { - Utilities.Return("Too big size", soc, server); - } - } - else - { - Utilities.Return("Too small size", soc, server); - } - } - else - { - Utilities.Return("Incorrect argument " + args[3], soc, server); - } + Program.selectedParty = Program.GetPartyID(false); } else { - Utilities.Return("Allready in a party.", soc, server); + Program.clients[soc].partyID = Program.GetPartyID(false); } + return new RequestResult(ResultTypes.OK, new string[3] { args[2], size.ToString(), (Program.GetPartyID(false)).ToString() }); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyJoinCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyJoinCommand.cs index c259c51..f072f4b 100644 --- a/Galactic Colors Control Server/Commands/Party/PartyJoinCommand.cs +++ b/Galactic Colors Control Server/Commands/Party/PartyJoinCommand.cs @@ -1,4 +1,6 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +9,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "join"; } } public string DescText { get { return "Join a party."; } } - public string HelpText { get { return "Use /party join [id] to join a party."; } } + public string HelpText { get { return "Use 'party join [id] ' to join a party."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -16,66 +18,44 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 1; } } public int maxArgs { get { return 2; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { if ((server && Program.selectedParty == -1) || (!server && Program.clients[soc].partyID == -1)) + return new RequestResult(ResultTypes.Error, Common.Strings("Allready")); + + int id; + if (!int.TryParse(args[2], out id)) + return new RequestResult(ResultTypes.Error, Common.Strings("Any Party")); + + if (!Program.parties.ContainsKey(id)) + return new RequestResult(ResultTypes.Error, Common.Strings("Can't Find")); + + Party party = Program.parties[id]; + if (args.Length == 3) { - int id; - if (int.TryParse(args[2], out id)) - { - if (Program.parties.ContainsKey(id)) - { - Party party = Program.parties[id]; - if (args.Length == 3) - { - Array.Resize(ref args, 4); - args[3] = ""; - } - if (server || (!server && party.TestPassword(args[3]))) - { - if(server) - { - Program.selectedParty = id; - } - else - { - if(party.open) - { - if (party.clients.Count < party.size) - { - Program.clients[soc].partyID = id; - Utilities.BroadcastParty(Utilities.GetName(soc) + " join the party", Galactic_Colors_Control_Common.Common.dataType.message, id); - } - else - { - Utilities.Return("Party is full", soc, server); - } - } - else - { - Utilities.Return("Party close", soc, server); - } - } - } - else - { - Utilities.Return("Wrong party password", soc, server); - } - } - else - { - Utilities.Return("Can't find party " + id, soc, server); - } - } - else - { - Utilities.Return("Incorrect argument " + args[3], soc, server); - } + Array.Resize(ref args, 4); + args[3] = ""; + } + if (!server && !party.TestPassword(args[3])) + return new RequestResult(ResultTypes.Error, Common.Strings("Password")); + + if (server) + { + Program.selectedParty = id; + return new RequestResult(ResultTypes.OK); } else { - Utilities.Return("Allready in a party.", soc, server); + if (!party.open) + return new RequestResult(ResultTypes.Error, Common.Strings("Close")); + + if (party.clients.Count + 1 > party.size) + return new RequestResult(ResultTypes.Error, Common.Strings("Full")); + + Program.clients[soc].partyID = id; + Utilities.BroadcastParty(new EventData(EventTypes.PartyJoin, Common.Strings(Utilities.GetName(soc))), id); + return new RequestResult(ResultTypes.OK); } } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyKickCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyKickCommand.cs index 7d76903..2b85bf3 100644 --- a/Galactic Colors Control Server/Commands/Party/PartyKickCommand.cs +++ b/Galactic Colors Control Server/Commands/Party/PartyKickCommand.cs @@ -1,4 +1,5 @@ using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "kick"; } } public string DescText { get { return "Kick player from party."; } } - public string HelpText { get { return "Use /party kick [name] to kick palyer from party"; } } + public string HelpText { get { return "Use 'party kick [name] ' to kick palyer from party"; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -16,34 +17,22 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 1; } } public int maxArgs { get { return 2; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { int partyId = -1; - if (Utilities.AccessParty(ref partyId, true, soc, server)) + if (Utilities.AccessParty(ref partyId, args, true, soc, server)) + return new RequestResult(ResultTypes.Error, Common.Strings("Access")); + + Socket target = null; + foreach (Socket client in Program.parties[partyId].clients) { - Socket target = null; - foreach (Socket client in Program.parties[partyId].clients) - { - if (Utilities.GetName(client) == args[2]) { target = client; } - } - if (target != null) - { - Utilities.BroadcastParty(args[2] + " was kick", Common.dataType.message, partyId); - if (args.Length > 3) - { - Utilities.Send(target, "/party kick " + args[3], Common.dataType.message); - } - else - { - Utilities.Send(target, "/party kick", Common.dataType.message); - } - Manager.Execute(new string[2] { "party", "leave" },target,false); - } - else - { - Utilities.Return("Can't find " + args[2] + "in party", soc, server); - } + if (Utilities.GetName(client) == args[2]) { target = client; } } + if (target == null) + return new RequestResult(ResultTypes.Error, Common.Strings("Can't find")); + + Utilities.Send(target, new EventData(EventTypes.PartyKick, args.Length > 3 ? Common.Strings(args[2]) : null)); + return Manager.Execute(new string[2] { "party", "leave" }, target, false); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyLeaveCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyLeaveCommand.cs index aa65bf7..8bfe734 100644 --- a/Galactic Colors Control Server/Commands/Party/PartyLeaveCommand.cs +++ b/Galactic Colors Control Server/Commands/Party/PartyLeaveCommand.cs @@ -1,4 +1,6 @@ -using System.Net.Sockets; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands { @@ -6,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "leave"; } } public string DescText { get { return "Leave party."; } } - public string HelpText { get { return "Use /party leave to leave current party"; } } + public string HelpText { get { return "Use 'party leave' to leave current party"; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -15,28 +17,26 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { if (server) { Program.selectedParty = -1; + return new RequestResult(ResultTypes.OK); } else { int partyId = -1; - if (Utilities.AccessParty(ref partyId, false, soc, server)) - { - if (!Program.parties[partyId].IsOwner(Utilities.GetName(soc))) - { - Utilities.BroadcastParty(Utilities.GetName(soc) + " leave the party", Galactic_Colors_Control_Common.Common.dataType.message, partyId); - Program.clients[soc].partyID = -1; - } - else - { - Utilities.Return("Owner can't leave party. Look for /party stop", soc, server); - } - } + if (Utilities.AccessParty(ref partyId, args, false, soc, server)) + return new RequestResult(ResultTypes.Error, Common.Strings("Access")); + + if (Program.parties[partyId].IsOwner(Utilities.GetName(soc))) + return new RequestResult(ResultTypes.Error, Common.Strings("Owner")); + + Program.clients[soc].partyID = -1; + Utilities.BroadcastParty(new EventData(EventTypes.PartyLeave, Common.Strings(Utilities.GetName(soc))), partyId); + return new RequestResult(ResultTypes.OK); } } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyListCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyListCommand.cs index 27c486c..5f259fd 100644 --- a/Galactic Colors Control Server/Commands/Party/PartyListCommand.cs +++ b/Galactic Colors Control Server/Commands/Party/PartyListCommand.cs @@ -1,4 +1,5 @@ -using System; +using Galactic_Colors_Control_Common.Protocol; +using System; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "list"; } } public string DescText { get { return "Shows parties list."; } } - public string HelpText { get { return "Use /party list to show parties list."; } } + public string HelpText { get { return "Use 'party list' to show parties list."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -16,15 +17,17 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { - string text = " "; + string[] text = new string[Program.parties.Keys.Count]; + int i = 0; foreach (int key in Program.parties.Keys) { Party party = Program.parties[key]; - text += (key + " : " + party.name + " : " + party.count + "/" + party.size + " : " + (party.open ? (party.isPrivate ? "private" : "open") : "close") + Environment.NewLine + " "); + text[i] = (key + " : " + party.name + " : " + party.count + "/" + party.size + " : " + (party.open ? (party.isPrivate ? "private" : "open") : "close") + Environment.NewLine + " "); + i++; } - Utilities.Return(text, soc, server); + return new RequestResult(ResultTypes.OK, text); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyOpenCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyOpenCommand.cs index 627b9c2..8a08c3b 100644 --- a/Galactic Colors Control Server/Commands/Party/PartyOpenCommand.cs +++ b/Galactic Colors Control Server/Commands/Party/PartyOpenCommand.cs @@ -1,4 +1,6 @@ -using System.Net.Sockets; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands { @@ -6,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "open"; } } public string DescText { get { return "Opens party."; } } - public string HelpText { get { return "Use /party open to open party for join."; } } + public string HelpText { get { return "Use 'party open' to open party for join."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -15,21 +17,17 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { int partyId = -1; - if (Utilities.AccessParty(ref partyId, true, soc, server)) - { - if (!Program.parties[partyId].open) - { - Program.parties[partyId].open = true; - Utilities.Return("Party opened", soc, server); - } - else - { - Utilities.Return("Party allready open", soc, server); - } - } + if (Utilities.AccessParty(ref partyId, args, true, soc, server)) + return new RequestResult(ResultTypes.Error, Common.Strings("Access")); + + if (Program.parties[partyId].open) + return new RequestResult(ResultTypes.Error, Common.Strings("Allready")); + + Program.parties[partyId].open = true; + return new RequestResult(ResultTypes.OK); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyPasswordCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyPasswordCommand.cs index e613d65..7ed01a1 100644 --- a/Galactic Colors Control Server/Commands/Party/PartyPasswordCommand.cs +++ b/Galactic Colors Control Server/Commands/Party/PartyPasswordCommand.cs @@ -1,4 +1,6 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +9,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "password"; } } public string DescText { get { return "Set party password."; } } - public string HelpText { get { return "Use /party password [newPass] [oldPass] to set party private with password."; } } + public string HelpText { get { return "Use 'party password [newPass] ' to set party private with password."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -16,25 +18,22 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 1; } } public int maxArgs { get { return 2; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { int partyId = -1; - if (Utilities.AccessParty(ref partyId, true, soc, server)) + if (Utilities.AccessParty(ref partyId, args, true, soc, server)) + return new RequestResult(ResultTypes.Error, Common.Strings("Access")); + + if (args.Length == 3) { - if (args.Length == 3) - { - Array.Resize(ref args, 4); - args[3] = ""; - } - if (Program.parties[partyId].SetPassword(args[2],args[3])) - { - Utilities.Return("Password changed", soc, server); - } - else - { - Utilities.Return("Can't change password", soc, server); - } + Array.Resize(ref args, 4); + args[3] = ""; } + + if (!Program.parties[partyId].SetPassword(args[2], args[3])) + return new RequestResult(ResultTypes.Error, Common.Strings("Can't Change")); + + return new RequestResult(ResultTypes.OK); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyStatusCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyStatusCommand.cs index c4cfa92..cde3708 100644 --- a/Galactic Colors Control Server/Commands/Party/PartyStatusCommand.cs +++ b/Galactic Colors Control Server/Commands/Party/PartyStatusCommand.cs @@ -1,4 +1,6 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +9,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "status"; } } public string DescText { get { return "Shows party status."; } } - public string HelpText { get { return "Use /party status to show party status."; } } + public string HelpText { get { return "Use 'party status' to show party status."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -16,18 +18,25 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { int partyId = -1; - if (Utilities.AccessParty(ref partyId, false, soc, server)) + if (!Utilities.AccessParty(ref partyId, args, false, soc, server)) + return new RequestResult(ResultTypes.Error, Common.Strings("Access")); + + Party party = Program.parties[partyId]; + if (server) { - Party party = Program.parties[partyId]; string text = ""; text += ("Name: " + party.name + Environment.NewLine); text += ("Count: " + party.count + "/" + party.size + Environment.NewLine); text += ("Status: " + (party.isPrivate ? "private" : (party.open ? "open" : "close"))); - Utilities.Return(text,soc,server); + return new RequestResult(ResultTypes.OK, Common.Strings(text)); + } + else + { + return new RequestResult(ResultTypes.OK, new string[4] { party.name, party.count.ToString(), party.size.ToString(), (party.isPrivate ? "private" : (party.open ? "open" : "close")) }); } } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyStopCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyStopCommand.cs index 1a9d7fe..dfd5d52 100644 --- a/Galactic Colors Control Server/Commands/Party/PartyStopCommand.cs +++ b/Galactic Colors Control Server/Commands/Party/PartyStopCommand.cs @@ -1,4 +1,6 @@ -using System.Net.Sockets; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands { @@ -6,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "stop"; } } public string DescText { get { return "Stop party."; } } - public string HelpText { get { return "Use /party stop to stop current party"; } } + public string HelpText { get { return "Use 'party stop' to stop current party"; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -15,19 +17,20 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { int partyId = -1; - if (Utilities.AccessParty(ref partyId, true, soc, server)) + if (!Utilities.AccessParty(ref partyId, args, true, soc, server)) + return new RequestResult(ResultTypes.Error, Common.Strings("Access")); + + foreach (Socket client in Program.parties[partyId].clients) { - foreach(Socket client in Program.parties[partyId].clients) - { - Manager.Execute(new string[4] { "party","kick",Utilities.GetName(client),"stop_party" } ,soc,server); - } - Logger.Write("Party " + Program.parties[partyId].name + " closed", Logger.logType.info); - if(Program.selectedParty == partyId) { Program.selectedParty = -1; } - Program.parties.Remove(partyId); + Manager.Execute(new string[4] { "party", "kick", Utilities.GetName(client), "stop_party" }, soc, server); } + Logger.Write("Party " + Program.parties[partyId].name + " closed", Logger.logType.info, server ? Logger.logConsole.show : Logger.logConsole.normal); + if (Program.selectedParty == partyId) { Program.selectedParty = -1; } + Program.parties.Remove(partyId); + return new RequestResult(ResultTypes.OK); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/PingCommand.cs b/Galactic Colors Control Server/Commands/PingCommand.cs index 6f1ed09..6f7b0ee 100644 --- a/Galactic Colors Control Server/Commands/PingCommand.cs +++ b/Galactic Colors Control Server/Commands/PingCommand.cs @@ -1,4 +1,6 @@ -using System.Net.Sockets; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands { @@ -6,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "ping"; } } public string DescText { get { return "Clears the console screen."; } } - public string HelpText { get { return "Use /ping to display our ping."; } } + public string HelpText { get { return "Use 'ping' to display our ping."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } } public bool IsServer { get { return false; } } public bool IsClient { get { return true; } } @@ -15,9 +17,9 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { - + return new RequestResult(ResultTypes.Error, Common.Strings("Client Side")); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/SayCommand.cs b/Galactic Colors Control Server/Commands/SayCommand.cs new file mode 100644 index 0000000..14008d8 --- /dev/null +++ b/Galactic Colors Control Server/Commands/SayCommand.cs @@ -0,0 +1,34 @@ +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; + +namespace Galactic_Colors_Control_Server.Commands +{ + public class SayCommand : ICommand + { + public string Name { get { return "say"; } } + public string DescText { get { return "Said something."; } } + public string HelpText { get { return "Use 'say [text]' to said something."; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } } + public bool IsServer { get { return true; } } + public bool IsClient { get { return true; } } + public bool IsClientSide { get { return false; } } + public bool IsNoConnect { get { return false; } } + public int minArgs { get { return 1; } } + public int maxArgs { get { return 1; } } + + public RequestResult Execute(string[] args, Socket soc, bool server = false) + { + if (args[1].Length == 0) + return new RequestResult(ResultTypes.Error, Common.Strings("Any Message")); + + if (!Utilities.IsConnect(soc)) + return new RequestResult(ResultTypes.Error, Common.Strings("Must Be Connected")); + + int party = -1; + party = Utilities.GetParty(soc); + Utilities.BroadcastParty(new EventData(EventTypes.ChatMessage, Common.Strings(Utilities.GetName(soc) + " : " + args[1])), party); + return new RequestResult(ResultTypes.OK); + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Server/ServerCloseCommand.cs b/Galactic Colors Control Server/Commands/Server/ServerCloseCommand.cs index 0b5d95e..9cd624f 100644 --- a/Galactic Colors Control Server/Commands/Server/ServerCloseCommand.cs +++ b/Galactic Colors Control Server/Commands/Server/ServerCloseCommand.cs @@ -1,4 +1,5 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "close"; } } public string DescText { get { return "Close server."; } } - public string HelpText { get { return "Use /server close to close server for connections"; } } + public string HelpText { get { return "Use 'server close' to close server for connections"; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.server; } } public bool IsServer { get { return true; } } public bool IsClient { get { return false; } } @@ -16,17 +17,14 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { - if (Program._open) - { - Program._open = false; - Logger.Write("Server closed", Logger.logType.warm); - } - else - { - Utilities.ConsoleWrite("Server allready close"); - } + if (!Program._open) + return new RequestResult(ResultTypes.Error, Common.Strings("Allready")); + + Program._open = false; + Logger.Write("Server closed", Logger.logType.warm, Logger.logConsole.show); + return new RequestResult(ResultTypes.OK); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Server/ServerOpenCommand.cs b/Galactic Colors Control Server/Commands/Server/ServerOpenCommand.cs index 4d26763..aef73bc 100644 --- a/Galactic Colors Control Server/Commands/Server/ServerOpenCommand.cs +++ b/Galactic Colors Control Server/Commands/Server/ServerOpenCommand.cs @@ -1,4 +1,5 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "open"; } } public string DescText { get { return "Open server."; } } - public string HelpText { get { return "Use /server open to open server for connections"; } } + public string HelpText { get { return "Use 'server open' to open server for connections"; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.server; } } public bool IsServer { get { return true; } } public bool IsClient { get { return false; } } @@ -16,17 +17,14 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { - if (!Program._open) - { - Program._open = true; - Logger.Write("Server opened", Logger.logType.warm); - } - else - { - Utilities.ConsoleWrite("Server allready open"); - } + if (Program._open) + return new RequestResult(ResultTypes.Error, Common.Strings("Allready")); + + Program._open = true; + Logger.Write("Server opened", Logger.logType.warm, Logger.logConsole.show); + return new RequestResult(ResultTypes.OK); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Server/ServerStatusCommand.cs b/Galactic Colors Control Server/Commands/Server/ServerStatusCommand.cs index a7ecc9e..947a515 100644 --- a/Galactic Colors Control Server/Commands/Server/ServerStatusCommand.cs +++ b/Galactic Colors Control Server/Commands/Server/ServerStatusCommand.cs @@ -1,4 +1,5 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "status"; } } public string DescText { get { return "Shows server status."; } } - public string HelpText { get { return "Use /server status to display server actual status."; } } + public string HelpText { get { return "Use 'server status' to display server actual status."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.server; } } public bool IsServer { get { return true; } } public bool IsClient { get { return false; } } @@ -16,18 +17,13 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { - if (Program._open) - { - Utilities.ConsoleWrite("Server : open", ConsoleColor.Green); - } - else - { - Utilities.ConsoleWrite("Server : close", ConsoleColor.Red); - } - Utilities.ConsoleWrite("Clients : " + Program.clients.Count + "/" + Program.config.size); - Utilities.ConsoleWrite("Parties : " + Program.parties.Count); + string text = ""; + text += "Server : " + (Program._open ? "open" : "close"); + text += "Clients : " + Program.clients.Count + "/" + Program.config.size; + text += "Parties : " + Program.parties.Count; + return new RequestResult(ResultTypes.OK, Common.Strings(text)); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Server/ServerStopCommand.cs b/Galactic Colors Control Server/Commands/Server/ServerStopCommand.cs index 73550b0..02ef516 100644 --- a/Galactic Colors Control Server/Commands/Server/ServerStopCommand.cs +++ b/Galactic Colors Control Server/Commands/Server/ServerStopCommand.cs @@ -1,5 +1,4 @@ -using Galactic_Colors_Control_Common; -using System; +using Galactic_Colors_Control_Common.Protocol; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -8,7 +7,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "stop"; } } public string DescText { get { return "Stop the server."; } } - public string HelpText { get { return "Use /server stop to completly stop server."; } } + public string HelpText { get { return "Use 'server stop' to completly stop server."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.server; } } public bool IsServer { get { return true; } } public bool IsClient { get { return false; } } @@ -17,10 +16,10 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { Program._run = false; - Utilities.ConsoleWrite("Stop server"); + return new RequestResult(ResultTypes.OK); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/TimeCommand.cs b/Galactic Colors Control Server/Commands/TimeCommand.cs index fd307f7..4a34ab2 100644 --- a/Galactic Colors Control Server/Commands/TimeCommand.cs +++ b/Galactic Colors Control Server/Commands/TimeCommand.cs @@ -1,4 +1,6 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +9,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "time"; } } public string DescText { get { return "Gives server time."; } } - public string HelpText { get { return "Use /time to display server time. (format is server dependent)"; } } + public string HelpText { get { return "Use 'time' to display server time."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -16,9 +18,9 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { - Utilities.Return(DateTime.Now.ToLongTimeString(), soc, server); + return new RequestResult(ResultTypes.OK, Common.Strings(DateTime.Now.ToLongTimeString())); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Config.cs b/Galactic Colors Control Server/Config.cs index af16ae7..948647f 100644 --- a/Galactic Colors Control Server/Config.cs +++ b/Galactic Colors Control Server/Config.cs @@ -1,9 +1,5 @@ using System; -using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; @@ -16,8 +12,8 @@ namespace Galactic_Colors_Control_Server public Logger.logType logLevel = Logger.logType.info; public int port = 25001; public int size = 20; - public ConsoleColor[] logForeColor = new ConsoleColor[5] {ConsoleColor.Gray , ConsoleColor.White, ConsoleColor.Yellow, ConsoleColor.Red, ConsoleColor.White}; - public ConsoleColor[] logBackColor = new ConsoleColor[5] { ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Red }; + public ConsoleColor[] logForeColor = new ConsoleColor[6] { ConsoleColor.DarkGray, ConsoleColor.Gray, ConsoleColor.White, ConsoleColor.Yellow, ConsoleColor.Red, ConsoleColor.White }; + public ConsoleColor[] logBackColor = new ConsoleColor[6] { ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Red }; /// /// Load config from xml file @@ -41,6 +37,7 @@ namespace Galactic_Colors_Control_Server else { Logger.Write("Old config in Config.xml.old", Logger.logType.warm); + File.Delete(AppDomain.CurrentDomain.BaseDirectory + "Config.xml.old"); File.Move(AppDomain.CurrentDomain.BaseDirectory + "Config.xml", AppDomain.CurrentDomain.BaseDirectory + "Config.xml.old"); config.Save(); } @@ -51,6 +48,7 @@ namespace Galactic_Colors_Control_Server config.Save(); } if (Program._debug) { config.logLevel = Logger.logType.debug; } + if (Program._dev) { config.logLevel = Logger.logType.dev; } return config; } @@ -60,12 +58,13 @@ namespace Galactic_Colors_Control_Server public void Save() { XmlSerializer xs = new XmlSerializer(typeof(Config)); - if (Program._debug) { logLevel = Logger.logType.info; } + if (Program._debug || Program._dev) { logLevel = Logger.logType.info; } using (StreamWriter st = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "Config.xml")) { - xs.Serialize(st,this); + xs.Serialize(st, this); }; if (Program._debug) { logLevel = Logger.logType.debug; } + if (Program._dev) { logLevel = Logger.logType.dev; } } /// @@ -114,4 +113,4 @@ namespace Galactic_Colors_Control_Server return isCorrect; } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/ConfigSchema.xsd b/Galactic Colors Control Server/ConfigSchema.xsd index 7e1457f..80af477 100644 --- a/Galactic Colors Control Server/ConfigSchema.xsd +++ b/Galactic Colors Control Server/ConfigSchema.xsd @@ -24,4 +24,4 @@ - + \ No newline at end of file diff --git a/Galactic Colors Control Server/Galactic Colors Control Server.csproj b/Galactic Colors Control Server/Galactic Colors Control Server.csproj index 7243d67..b89d988 100644 --- a/Galactic Colors Control Server/Galactic Colors Control Server.csproj +++ b/Galactic Colors Control Server/Galactic Colors Control Server.csproj @@ -59,6 +59,8 @@ + + diff --git a/Galactic Colors Control Server/Logger.cs b/Galactic Colors Control Server/Logger.cs index fb66c4b..3c84d79 100644 --- a/Galactic Colors Control Server/Logger.cs +++ b/Galactic Colors Control Server/Logger.cs @@ -4,14 +4,16 @@ using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; -using System.Reflection; using System.Threading; namespace Galactic_Colors_Control_Server { public class Logger { - public enum logType { debug, info, warm, error, fatal } + public enum logType { dev, debug, info, warm, error, fatal } + + public enum logConsole { normal, show, hide } + private static List toWriteLogs = new List(); private static string logPath; public static Thread Updater; @@ -21,11 +23,13 @@ namespace Galactic_Colors_Control_Server { public string text; public logType type; + public logConsole console; - public Log(string p1, logType p2) + public Log(string p1, logType p2, logConsole p3 = logConsole.normal) { text = p1; type = p2; + console = p3; } } @@ -34,15 +38,16 @@ namespace Galactic_Colors_Control_Server /// public static void Initialise() { - if (!Directory.Exists(Program.config.logPath)) { + if (!Directory.Exists(Program.config.logPath)) + { Directory.CreateDirectory(Program.config.logPath); - Write("Log Directory Created" ,logType.info); + Write("Log Directory Created", logType.info); } else { //Sort old logs string[] files = Directory.GetFiles(Program.config.logPath); - foreach(string file in files) + foreach (string file in files) { if (Path.GetExtension(file) == ".log") { @@ -55,7 +60,7 @@ namespace Galactic_Colors_Control_Server int y; int m; int d; - if(int.TryParse(new string(name.Take(4).ToArray()), out y) && int.TryParse(new string(name.Skip(5).Take(2).ToArray()), out m) && int.TryParse(new string(name.Skip(8).Take(2).ToArray()), out d)) + if (int.TryParse(new string(name.Take(4).ToArray()), out y) && int.TryParse(new string(name.Skip(5).Take(2).ToArray()), out m) && int.TryParse(new string(name.Skip(8).Take(2).ToArray()), out d)) { if (!Directory.Exists(Program.config.logPath + "/" + y + "/" + m + "/" + d)) { @@ -69,7 +74,7 @@ namespace Galactic_Colors_Control_Server } } int i = 0; - while(File.Exists(Program.config.logPath + "/" + DateTime.UtcNow.ToString("yyyy-MM-dd-", CultureInfo.InvariantCulture) + i + ".log")) { i++; } + while (File.Exists(Program.config.logPath + "/" + DateTime.UtcNow.ToString("yyyy-MM-dd-", CultureInfo.InvariantCulture) + i + ".log")) { i++; } logPath = Program.config.logPath + "/" + DateTime.UtcNow.ToString("yyyy-MM-dd-", CultureInfo.InvariantCulture) + i + ".log"; Write("Log path:" + logPath, logType.debug); Updater = new Thread(new ThreadStart(UpdaterLoop)); @@ -81,9 +86,10 @@ namespace Galactic_Colors_Control_Server /// /// Log text /// Log status - public static void Write(string text, logType type) + /// Server display modifier + public static void Write(string text, logType type, logConsole console = logConsole.normal) { - Write(new Log(text, type)); + Write(new Log(text, type, console)); } /// @@ -92,15 +98,12 @@ namespace Galactic_Colors_Control_Server /// Log struct public static void Write(Log log) { - if (log.type != logType.debug || Program.config.logLevel == logType.debug) + if (Program.config.logLevel == logType.debug || Program.config.logLevel == logType.dev) { - if(Program._debug) - { - //Add Source Method - log.text = "[" + new StackTrace().GetFrame(2).GetMethod().Name + "]: " + log.text; - } - toWriteLogs.Add(log); + //Add Source Method + log.text = "[" + new StackTrace().GetFrame(2).GetMethod().Name + "]: " + log.text; } + toWriteLogs.Add(log); } /// @@ -110,18 +113,36 @@ namespace Galactic_Colors_Control_Server { while (_run || toWriteLogs.Count > 0) { - while(toWriteLogs.Count > 0) + while (toWriteLogs.Count > 0) { Log log = toWriteLogs[0]; - File.AppendAllText(logPath,DateTime.UtcNow.ToString("[yyyy-MM-dd]", CultureInfo.InvariantCulture) + " [" + log.type.ToString().ToUpper() + "]: " + log.text + Environment.NewLine); - if(log.type >= Program.config.logLevel) { - Console.BackgroundColor = Program.config.logBackColor[(int)log.type]; - Console.ForegroundColor = Program.config.logForeColor[(int)log.type]; - Console.Write("\b"); - Console.WriteLine(DateTime.UtcNow.ToString("[yyyy-MM-dd]", CultureInfo.InvariantCulture) + ": " + log.text); - Utilities.ConsoleResetColor(); - Console.Write(">"); + if (log.type >= Program.config.logLevel) + { + File.AppendAllText(logPath, DateTime.UtcNow.ToString("[yyyy-MM-dd]", CultureInfo.InvariantCulture) + " [" + log.type.ToString().ToUpper() + "]: " + log.text + Environment.NewLine); + if (log.console != logConsole.hide) + { + Console.BackgroundColor = Program.config.logBackColor[(int)log.type]; + Console.ForegroundColor = Program.config.logForeColor[(int)log.type]; + Console.Write("\b"); + Console.WriteLine(DateTime.UtcNow.ToString("[yyyy-MM-dd]", CultureInfo.InvariantCulture) + ": " + log.text); + Utilities.ConsoleResetColor(); + Console.Write(">"); + } } + //TODO reactive show logger + /* + else + { + if(log.console == logConsole.show) + { + Console.BackgroundColor = Program.config.logBackColor[(int)log.type]; + Console.ForegroundColor = Program.config.logForeColor[(int)log.type]; + Console.Write("\b"); + Console.WriteLine(DateTime.UtcNow.ToString("[yyyy-MM-dd]", CultureInfo.InvariantCulture) + ": " + log.text); + Utilities.ConsoleResetColor(); + Console.Write(">"); + } + }*/ toWriteLogs.Remove(log); } Thread.Sleep(200); diff --git a/Galactic Colors Control Server/Party.cs b/Galactic Colors Control Server/Party.cs index 37b2c2d..70f5846 100644 --- a/Galactic Colors Control Server/Party.cs +++ b/Galactic Colors Control Server/Party.cs @@ -28,7 +28,7 @@ namespace Galactic_Colors_Control_Server { if (isPrivate) { - return (password == pass) ; + return (password == pass); } else { @@ -62,9 +62,9 @@ namespace Galactic_Colors_Control_Server get { List list = new List(); - foreach(Socket soc in Program.clients.Keys) + foreach (Socket soc in Program.clients.Keys) { - if(Program.clients[soc].party == this) { list.Add(soc); } + if (Program.clients[soc].party == this) { list.Add(soc); } } return list; } diff --git a/Galactic Colors Control Server/Program.cs b/Galactic Colors Control Server/Program.cs index aec660d..b8d26dc 100644 --- a/Galactic Colors Control Server/Program.cs +++ b/Galactic Colors Control Server/Program.cs @@ -1,274 +1,258 @@ using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Reflection; -using System.Text; +using System.Threading; namespace Galactic_Colors_Control_Server { - internal class Program - { - private const int BUFFER_SIZE = 2048; - private static readonly Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - public static bool _debug = false; - public static bool _run = true; - public static bool _open = true; - private static readonly byte[] buffer = new byte[BUFFER_SIZE]; + internal class Program + { + private const int BUFFER_SIZE = 2048; + private static readonly Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - public static Dictionary clients { get; private set; } = new Dictionary(); + public static bool _debug = false; + public static bool _dev = false; - public static int partyID = 0; - public static Dictionary parties { get; private set; } = new Dictionary(); - public static int selectedParty = -1; + public static bool _run = true; + public static bool _open = true; + private static readonly byte[] buffer = new byte[BUFFER_SIZE]; - public static Config config = new Config(); + public static Dictionary clients { get; private set; } = new Dictionary(); - /// - /// Server Main thread - /// - private static void Main(string[] args) - { - Console.Title = "Galactic Colors Control Server"; - Logger.Write("Galactic Colors Control Server " + Assembly.GetEntryAssembly().GetName().Version.ToString(), Logger.logType.fatal); - if (args.Length > 0) - { - switch (args[0]) - { - case "--debug": - _debug = true; - Logger.Write("SERVER IS IN DEBUG MODE !", Logger.logType.error); - break; + private static int partyID = 0; - default: - Utilities.ConsoleWrite("Use --debug or any argument"); - break; - } - } - if(Type.GetType("Mono.Runtime") != null) { Logger.Write("Using Mono", Logger.logType.warm); } - Console.Write(">"); - SetupServer(); - ConsoleLoop(); - CloseAllSockets(); - } + public static Dictionary parties { get; private set; } = new Dictionary(); + public static int selectedParty = -1; - /// - /// Initialise server and start threads. - /// - private static void SetupServer() - { - config = config.Load(); - Logger.Initialise(); - Commands.Manager.Load(); - Logger.Write("Setting up server on *:" + config.port, Logger.logType.warm); - Logger.Write("Size:" + config.size, Logger.logType.debug); - serverSocket.Bind(new IPEndPoint(IPAddress.Any, config.port)); - serverSocket.Listen(0); - serverSocket.BeginAccept(AcceptCallback, null); - Logger.Write("Server setup complete", Logger.logType.info); - } + public static Config config = new Config(); + public static Thread CheckConnected = new Thread(CheckConnectedLoop); - /// - /// Wait console commands and execute them. - /// - private static void ConsoleLoop() - { - while (_run) - { - string ConsoleInput = Console.ReadLine(); - Console.Write(">"); - ExecuteMessage(ConsoleInput, null, true); - ConsoleInput = null; - } - } + /// + /// Server Main thread + /// + private static void Main(string[] args) + { + Console.Title = "Galactic Colors Control Server"; + Logger.Write("Galactic Colors Control Server " + Assembly.GetEntryAssembly().GetName().Version.ToString(), Logger.logType.fatal); + if (args.Length > 0) + { + switch (args[0]) + { + case "--debug": + _debug = true; + Logger.Write("SERVER IS IN DEBUG MODE !", Logger.logType.error, Logger.logConsole.show); + break; - /// - /// Close all connected client. - /// - private static void CloseAllSockets() - { - Logger.Write("Stoping server", Logger.logType.warm); - config.Save(); - foreach (Socket socket in clients.Keys) - { - socket.Shutdown(SocketShutdown.Both); - Logger.Write("Shutdown " + Utilities.GetName(socket),Logger.logType.debug); - } - serverSocket.Close(); - Logger.Write("Server stoped", Logger.logType.info); - Logger._run = false; - Logger.Updater.Join(); - } + case "--dev": + _dev = true; + Logger.Write("SERVER IS IN DEV MODE !", Logger.logType.error, Logger.logConsole.show); + break; - /// - /// Wait a client and check if is correct - /// - private static void AcceptCallback(IAsyncResult AR) - { - Socket socket; + default: + Utilities.ConsoleWrite("Use --debug or --dev"); + break; + } + } + if (Type.GetType("Mono.Runtime") != null) { Logger.Write("Using Mono", Logger.logType.warm); } + Console.Write(">"); + SetupServer(); + ConsoleLoop(); + CloseAllSockets(); + } - try - { - socket = serverSocket.EndAccept(AR); - } - catch (ObjectDisposedException) // I cannot seem to avoid this (on exit when properly closing sockets) - { - return; - } - if (_open) - { - if (clients.Count < config.size) - { - AddClient(socket); - } - else - { - Logger.Write("Client can't join from " + ((IPEndPoint)socket.LocalEndPoint).Address.ToString() + " no more space", Logger.logType.warm); - Utilities.Send(socket, "/kick can't_join_no_more_space", Common.dataType.message); - socket.Close(); - } - } - else - { - Logger.Write("Client can't join from " + ((IPEndPoint)socket.LocalEndPoint).Address.ToString() + " server closed", Logger.logType.info); - Utilities.Send(socket, "/kick can't_join_server_closed", Common.dataType.message); - socket.Close(); - } - serverSocket.BeginAccept(AcceptCallback, null); - } + /// + /// Initialise server and start threads. + /// + private static void SetupServer() + { + config = config.Load(); + Logger.Initialise(); + Commands.Manager.Load(); + Logger.Write("Setting up server on *:" + config.port, Logger.logType.warm); + Logger.Write("Size:" + config.size, Logger.logType.debug); + serverSocket.Bind(new IPEndPoint(IPAddress.Any, config.port)); + serverSocket.Listen(0); + serverSocket.BeginAccept(AcceptCallback, null); + CheckConnected.Start(); + Logger.Write("Server setup complete", Logger.logType.info); + } - /// - /// Add client and initialise receive - /// - private static void AddClient(Socket socket) - { - Client client = new Client(); - clients.Add(socket, client); - socket.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, socket); - Logger.Write("Client connection from " + Utilities.GetName(socket), Logger.logType.info); - Logger.Write("Size: " + clients.Count + "/" + config.size, Logger.logType.debug); - if (clients.Count >= config.size) - { - Logger.Write("Server full", Logger.logType.warm); - } - } + /// + /// Wait console commands and execute them. + /// + private static void ConsoleLoop() + { + while (_run) + { + string ConsoleInput = Console.ReadLine(); + Console.Write(">"); + string[] args = Common.SplitArgs(ConsoleInput); + Utilities.ConsoleWrite(new ResultData(-1, Commands.Manager.Execute(args, null, true)).ToSmallString()); + ConsoleInput = null; + } + } - /// - /// Wait a client commands and execute them - /// - private static void ReceiveCallback(IAsyncResult AR) - { - Socket current = (Socket)AR.AsyncState; - int received; + /// + /// Close all connected client. + /// + private static void CloseAllSockets() + { + Logger.Write("Stoping server", Logger.logType.warm, Logger.logConsole.show); + Utilities.Broadcast(new EventData(EventTypes.ServerKick, Common.Strings("Close"))); + config.Save(); + foreach (Socket socket in clients.Keys) + { + socket.Shutdown(SocketShutdown.Both); + Logger.Write("Shutdown " + Utilities.GetName(socket), Logger.logType.debug); + } + serverSocket.Close(); + CheckConnected.Join(2000); + Logger.Write("Server stoped", Logger.logType.info); + Logger._run = false; + Logger.Updater.Join(); + } - try - { - received = current.EndReceive(AR); - } - catch (SocketException) - { - Logger.Write("Client forcefully disconnected from " + Utilities.GetName(current) + " : SocketException", Logger.logType.info); - string username = Utilities.GetName(current); - bool connected = clients[current].status != -1; - Logger.Write("Size: " + clients.Count + "/" + config.size, Logger.logType.debug); - current.Close(); // Don't shutdown because the socket may be disposed and its disconnected anyway. - clients.Remove(current); - if (connected) { Utilities.Broadcast(username + " leave the server", Common.dataType.message); } - return; - } + /// + /// Wait a client and check if is correct + /// + private static void AcceptCallback(IAsyncResult AR) + { + Socket socket; + try + { + socket = serverSocket.EndAccept(AR); + } + catch (ObjectDisposedException) + { + return; + } + if (_open) + { + if (clients.Count < config.size) + { + AddClient(socket); + } + else + { + Logger.Write("Client can't join from " + ((IPEndPoint)socket.LocalEndPoint).Address.ToString() + " no more space", Logger.logType.warm); + Utilities.Send(socket, new EventData(EventTypes.ServerKick, Common.Strings("Space"))); + socket.Close(); + } + } + else + { + Logger.Write("Client can't join from " + ((IPEndPoint)socket.LocalEndPoint).Address.ToString() + " server closed", Logger.logType.info); + Utilities.Send(socket, new EventData(EventTypes.ServerKick, Common.Strings("Close"))); + socket.Close(); + } + serverSocket.BeginAccept(AcceptCallback, null); + } - var data = new byte[received]; - Array.Copy(buffer, data, received); + /// + /// Add client and initialise receive + /// + private static void AddClient(Socket socket) + { + Client client = new Client(); + clients.Add(socket, client); + socket.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, socket); + Logger.Write("Client connection from " + Utilities.GetName(socket), Logger.logType.info); + Logger.Write("Size: " + clients.Count + "/" + config.size, Logger.logType.dev); + if (clients.Count >= config.size) + { + Logger.Write("Server full", Logger.logType.warm, Logger.logConsole.show); + } + } - //Server crash on command Exception - //try { - byte[] type = new byte[4]; - type = data.Take(4).ToArray(); - type.Reverse(); - Common.dataType dtype = (Common.dataType)BitConverter.ToInt32(type, 0); - byte[] bytes = null; - bytes = data.Skip(4).ToArray(); - switch (dtype) - { - case Common.dataType.message: - string text = Encoding.ASCII.GetString(bytes); - ExecuteMessage(text, current); - break; + /// + /// Wait a client commands and execute them + /// + private static void ReceiveCallback(IAsyncResult AR) + { + Socket current = (Socket)AR.AsyncState; + int received; - case Common.dataType.data: - Console.WriteLine("data"); - break; + try + { + received = current.EndReceive(AR); + } + catch (SocketException) + { + Logger.Write("Client forcefully disconnected from " + Utilities.GetName(current) + " : SocketException", Logger.logType.info); + string username = Utilities.GetName(current); + bool connected = clients[current].status != -1; + Logger.Write("Size: " + clients.Count + "/" + config.size, Logger.logType.debug); + current.Close(); // Don't shutdown because the socket may be disposed and its disconnected anyway. + clients.Remove(current); + if (connected) { Utilities.Broadcast(new EventData(EventTypes.ServerLeave, Common.Strings(username))); } + return; + } - default: - Logger.Write("Unknow type data form" + Utilities.GetName(current), Logger.logType.error); - break; - } + var data = new byte[received]; + Array.Copy(buffer, data, received); - if (clients.ContainsKey(current)) { current.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, current); } - /*} - catch (Exception) { - Logger.Write(Utilities.GetName(current) + " : ReceiveException", Logger.logType.info); - //if (clients.ContainsKey(current)) { clients.Remove(current); } - }*/ - } + Data packet = Data.FromBytes(ref data); + if (packet != null) + { + switch (packet.GetType().Name) + { + case "RequestData": + RequestData req = (RequestData)packet; + Utilities.Send(current, new ResultData(req.id, Commands.Manager.Execute(req.args, current))); + break; - /// - /// Execute send command - /// Command - /// Sender socket - /// Is sender server? - /// - private static void ExecuteMessage(string text, Socket soc = null, bool server = false) - { - if (text.Length > 0) - { - if (text[0] == '/') - { - text = text.Substring(1); - text = text.ToLower(); - string[] array = text.Split(new char[1] { ' ' }, 4, StringSplitOptions.RemoveEmptyEntries); - if (array.Length > 0) - { - Commands.Manager.Execute(array, soc, server); - } - else - { - Utilities.Return("Any command",soc , server); - } - } - else - { - if (!Utilities.IsConnect(soc)) - { - Utilities.Send(soc, "Only identified clients can talk.", Common.dataType.message); - } - else - { - int party = -1; - if (server) - { - party = selectedParty; - } - else - { - party = clients[soc].partyID; - } - Utilities.BroadcastParty(Utilities.GetName(soc) + " : " + text, Common.dataType.message, party); - } - } - } - } + default: + Logger.Write("Wrong packet from " + Utilities.GetName(current), Logger.logType.error); + break; + } + } + else + { + Logger.Write("Wrong packet from " + Utilities.GetName(current), Logger.logType.error); + } - /// - /// Add new party with index - /// - /// Party to add - public static void AddParty(Party party) - { - parties.Add(partyID, party); - partyID++; - } - } + if (clients.ContainsKey(current)) { current.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, current); } + } + + private static void CheckConnectedLoop() + { + while (_run) + { + foreach (Socket current in clients.Keys.ToArray()) + { + if ((current.Poll(10, SelectMode.SelectRead) && current.Available == 0) || !current.Connected) + { + string username = Utilities.GetName(current); + Logger.Write("Client forcefully disconnected from " + username + " : NotConnected", Logger.logType.info); + bool connected = clients[current].status != -1; + Logger.Write("Size: " + clients.Count + "/" + config.size, Logger.logType.debug); + current.Close(); // Don't shutdown because the socket may be disposed and its disconnected anyway. + clients.Remove(current); + if (connected) { Utilities.Broadcast(new EventData(EventTypes.ServerLeave, Common.Strings(username))); } + } + Thread.Sleep(200); + } + } + } + + /// + /// Add new party with index + /// + /// Party to add + public static void AddParty(Party party) + { + parties.Add(GetPartyID(), party); + } + + public static int GetPartyID(bool indent = true) + { + if (indent) { partyID++; } + return partyID; + } + } } \ No newline at end of file diff --git a/Galactic Colors Control Server/Properties/AssemblyInfo.cs b/Galactic Colors Control Server/Properties/AssemblyInfo.cs index 044e06f..de5bf71 100644 --- a/Galactic Colors Control Server/Properties/AssemblyInfo.cs +++ b/Galactic Colors Control Server/Properties/AssemblyInfo.cs @@ -1,8 +1,7 @@ using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -// Les informations générales relatives à un assembly dépendent de +// Les informations générales relatives à un assembly dépendent de // l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations // associées à un assembly. [assembly: AssemblyTitle("Galactic Colors Control Server")] @@ -12,10 +11,10 @@ using System.Runtime.InteropServices; [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] -// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly -// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de +// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly +// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de // COM, affectez la valeur true à l'attribut ComVisible sur ce type. [assembly: ComVisible(false)] // Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM -[assembly: Guid("9e3af4e1-88c6-4139-a15c-b4f633e80612")] +[assembly: Guid("9e3af4e1-88c6-4139-a15c-b4f633e80612")] \ No newline at end of file diff --git a/Galactic Colors Control Server/Utilities.cs b/Galactic Colors Control Server/Utilities.cs index da89b06..78d4bae 100644 --- a/Galactic Colors Control Server/Utilities.cs +++ b/Galactic Colors Control Server/Utilities.cs @@ -1,14 +1,11 @@ -using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; using System; -using System.IO; using System.Net; using System.Net.Sockets; -using System.Runtime.Serialization.Formatters.Binary; -using System.Text; namespace Galactic_Colors_Control_Server { - class Utilities + internal class Utilities { /// /// Check if socket is connect @@ -16,22 +13,14 @@ namespace Galactic_Colors_Control_Server /// Client socket public static bool IsConnect(Socket soc) { - if(soc == null) - { + if (soc == null) return true; - } - else - { - if (Program.clients.ContainsKey(soc)) - { - return Program.clients[soc].status != -1; - } - else - { - Logger.Write("IsConnect : Unknown client", Logger.logType.error); - return true; - } - } + + if (Program.clients.ContainsKey(soc)) + return Program.clients[soc].status != -1; + + Logger.Write("IsConnect : Unknown client", Logger.logType.error); + return false; } /// @@ -41,23 +30,23 @@ namespace Galactic_Colors_Control_Server /// Name public static string GetName(Socket soc) { - if (soc != null) - { - if (Program.clients.ContainsKey(soc)) - { - string res = Program.clients[soc].pseudo; - if (res == "") { res = ((IPEndPoint)soc.LocalEndPoint).Address.ToString(); } - return res; - } - else - { - return "?"; - } - } - else - { + if (soc == null) return "Server"; - } + + if (!Program.clients.ContainsKey(soc)) + return "?"; + + string res = Program.clients[soc].pseudo; + if (res == "") { res = ((IPEndPoint)soc.LocalEndPoint).Address.ToString(); } + return res; + } + + public static int GetParty(Socket soc) + { + if (soc == null) + return Program.selectedParty; + + return Program.clients[soc].partyID; } /// @@ -91,40 +80,23 @@ namespace Galactic_Colors_Control_Server /// /// Target socket /// Data to send - /// Type of data - public static void Send(Socket soc, object data, Common.dataType dtype) + public static void Send(Socket soc, Data packet) { - /* - Format: - 0-3: dataType - 4-x: data - */ - byte[] type = new byte[4]; - type = BitConverter.GetBytes((int)dtype); - byte[] bytes = null; - switch (dtype) + if (soc.Connected) { - case Common.dataType.message: - bytes = Encoding.ASCII.GetBytes((string)data); - break; - - case Common.dataType.data: - BinaryFormatter bf = new BinaryFormatter(); - using (MemoryStream ms = new MemoryStream()) + try + { + soc.Send(packet.ToBytes()); + if (Program.config.logLevel == Logger.logType.dev) { - bf.Serialize(ms, data); - bytes = ms.ToArray(); + Logger.Write("Send to " + GetName(soc) + " : " + packet.ToLongString(), Logger.logType.dev); } - break; - - default: - bytes = new byte[] { 1 }; - break; + } + catch (Exception e) + { + Logger.Write("Send exception to " + GetName(soc) + " : " + e.Message, Logger.logType.error); + } } - byte[] final = new byte[type.Length + bytes.Length]; - type.CopyTo(final, 0); - bytes.CopyTo(final, type.Length); - soc.Send(final); } /// @@ -132,13 +104,14 @@ namespace Galactic_Colors_Control_Server /// /// Data to send /// Type of data - public static void Broadcast(object data, Common.dataType dtype) + /// Message to display for server + public static void Broadcast(Data packet) { foreach (Socket soc in Program.clients.Keys) { - Send(soc, data, dtype); + Send(soc, packet); } - if (dtype == Common.dataType.message) { ConsoleWrite((string)data); } + ConsoleWrite(packet.ToSmallString()); } /// @@ -147,33 +120,38 @@ namespace Galactic_Colors_Control_Server /// Data to send /// Type of data /// Id of the party - public static void BroadcastParty(object data, Common.dataType dtype, int party) + /// Message to display for server + public static void BroadcastParty(Data data, int party) { - foreach(Socket soc in Program.clients.Keys) + foreach (Socket soc in Program.clients.Keys) { if (Program.clients[soc].partyID == party) { - Send(soc, data, dtype); + Send(soc, data); } } - if (dtype == Common.dataType.message) { if (Program.selectedParty == party) { ConsoleWrite((string)data); } } + if (Program.selectedParty == party) + { + ConsoleWrite(data.ToSmallString()); + } } /// /// Send or display if server /// - /// Text to send + /// Text to display if server + /// Data to send if client /// Target socket /// Is server? - public static void Return(string message, Socket soc = null, bool server = false) + public static void Return(Data data, Socket soc = null, bool server = false) { if (server) { - ConsoleWrite(message); + ConsoleWrite(data.ToSmallString()); } else { - Send(soc, message, Common.dataType.message); + Send(soc, data); } } @@ -185,60 +163,39 @@ namespace Galactic_Colors_Control_Server /// Target socket /// Is server? /// Can access? - public static bool AccessParty(ref int partyId, bool needOwn, Socket soc = null, bool server = false) + public static bool AccessParty(ref int partyId, string[] args, bool needOwn, Socket soc = null, bool server = false) { if (server) { - if(Program.selectedParty != -1) + if (Program.selectedParty == -1) + return false; + + if (Program.parties.ContainsKey(Program.selectedParty)) { - if (Program.parties.ContainsKey(Program.selectedParty)) - { - partyId = Program.selectedParty; - return true; - } - else - { - Logger.Write("Can't find party " + Program.selectedParty, Logger.logType.error); - Program.selectedParty = -1; - return false; - } + partyId = Program.selectedParty; + return true; } else { - ConsoleWrite("Join a party before"); + Program.selectedParty = -1; return false; } } else { - if(Program.clients[soc].partyID != -1) - { - if (Program.parties.ContainsKey(Program.clients[soc].partyID)) - { - if (Program.parties[Program.clients[soc].partyID].IsOwner(GetName(soc)) || !needOwn) - { - partyId = Program.clients[soc].partyID; - return true; - } - else - { - Send(soc, "You are not owner", Common.dataType.message); - return false; - } - } - else - { - Send(soc, "Can't find party " + Program.clients[soc].partyID, Common.dataType.message); - Program.clients[soc].partyID = -1; - return false; - } - } - else - { - Send(soc, "Join a party before", Common.dataType.message); + if (Program.clients[soc].partyID == -1) return false; + + if (!Program.parties.ContainsKey(Program.clients[soc].partyID)) + return false; + + if (Program.parties[Program.clients[soc].partyID].IsOwner(GetName(soc)) || !needOwn) + { + partyId = Program.clients[soc].partyID; + return true; } + else { return false; } } } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control.sln b/Galactic Colors Control.sln index 2b7c6f0..89b466b 100644 --- a/Galactic Colors Control.sln +++ b/Galactic Colors Control.sln @@ -27,6 +27,12 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Common", "Common", "{75A0AD AssemblyInfoCommon.cs = AssemblyInfoCommon.cs EndProjectSection EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{4E46A1CB-6F9C-4E4E-8A9A-D62DAB09FF64}" + ProjectSection(SolutionItems) = preProject + License.md = License.md + Readme.md = Readme.md + EndProjectSection +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -35,8 +41,8 @@ Global Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {9E3AF4E1-88C6-4139-A15C-B4F633E80612}.Debug|Any CPU.ActiveCfg = Release|Any CPU - {9E3AF4E1-88C6-4139-A15C-B4F633E80612}.Debug|Any CPU.Build.0 = Release|Any CPU + {9E3AF4E1-88C6-4139-A15C-B4F633E80612}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9E3AF4E1-88C6-4139-A15C-B4F633E80612}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E3AF4E1-88C6-4139-A15C-B4F633E80612}.Debug|x86.ActiveCfg = Debug|Any CPU {9E3AF4E1-88C6-4139-A15C-B4F633E80612}.Debug|x86.Build.0 = Debug|Any CPU {9E3AF4E1-88C6-4139-A15C-B4F633E80612}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/Galactic Colors Control/App.config b/Galactic Colors Control/App.config index d1428ad..5035d4f 100644 --- a/Galactic Colors Control/App.config +++ b/Galactic Colors Control/App.config @@ -1,6 +1,6 @@ - - - - + + + + \ No newline at end of file diff --git a/Galactic Colors Control/Program.cs b/Galactic Colors Control/Program.cs index 20cb0f4..52f66b7 100644 --- a/Galactic Colors Control/Program.cs +++ b/Galactic Colors Control/Program.cs @@ -1,13 +1,10 @@ -using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; using System; using System.Collections.Generic; -using System.IO; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; -using System.Runtime.Serialization.Formatters.Binary; -using System.Text; using System.Threading; namespace Galactic_Colors_Control @@ -25,6 +22,7 @@ namespace Galactic_Colors_Control public bool isRunning { get { return _run; } } public List Output = new List(); + private int RequestId = 0; private Thread RecieveThread; @@ -66,14 +64,14 @@ namespace Galactic_Colors_Control } catch (Exception e) { - Output.Add(e.Message); PORT = 0; + Output.Add(e.Message); return null; } } else { - Output.Add("Incorrect port"); + Output.Add("Incorrect Port"); return null; } } @@ -129,9 +127,9 @@ namespace Galactic_Colors_Control /// public void ExitHost() { - Send("/exit", Common.dataType.message); // Tell the server we are exiting + Send(new RequestData(GetRequestId(), new string[1] { "exit" }));// Tell the server we are exiting _run = false; - RecieveThread.Join(); + RecieveThread.Join(2000); ClientSocket.Shutdown(SocketShutdown.Both); ClientSocket.Close(); Output.Add("Bye"); @@ -155,7 +153,27 @@ namespace Galactic_Colors_Control break; default: - Send(request, Common.dataType.message); + //TODO add key and send error here + if (request.Length > 0) + { + if (request[0] == '/') + { + request = request.Substring(1); + string[] array = request.Split(new char[1] { ' ' }, 4, StringSplitOptions.RemoveEmptyEntries); + if (array.Length > 0) + { + Send(new RequestData(GetRequestId(), array)); + } + else + { + Output.Add("Any Command"); + } + } + else + { + Send(new RequestData(GetRequestId(), new string[2] { "say", request })); + } + } break; } } @@ -177,32 +195,11 @@ namespace Galactic_Colors_Control } } - private void Send(object data, Common.dataType dtype) + private void Send(Data packet) { - byte[] type = new byte[4]; - type = BitConverter.GetBytes((int)dtype); - byte[] bytes = null; - switch (dtype) - { - case Common.dataType.message: - bytes = Encoding.ASCII.GetBytes((string)data); - break; - - case Common.dataType.data: - BinaryFormatter bf = new BinaryFormatter(); - using (MemoryStream ms = new MemoryStream()) - { - bf.Serialize(ms, data); - bytes = ms.ToArray(); - } - break; - } - byte[] final = new byte[type.Length + bytes.Length]; - type.CopyTo(final, 0); - bytes.CopyTo(final, type.Length); try { - ClientSocket.Send(final); + ClientSocket.Send(packet.ToBytes()); } catch { @@ -234,79 +231,40 @@ namespace Galactic_Colors_Control _errorCount = 0; var data = new byte[received]; Array.Copy(buffer, data, received); - byte[] type = new byte[4]; - type = data.Take(4).ToArray(); - type.Reverse(); - Common.dataType dtype = (Common.dataType)BitConverter.ToInt32(type, 0); - byte[] bytes = null; - bytes = data.Skip(4).ToArray(); - switch (dtype) + + Data packet = Data.FromBytes(ref data); + if (packet != null) { - case Common.dataType.message: - string text = Encoding.ASCII.GetString(bytes); - if (text[0] == '/') - { - text = text.Substring(1); - text = text.ToLower(); - string[] array = text.Split(new char[1] { ' ' }, 4, StringSplitOptions.RemoveEmptyEntries); - switch (array[0]) - { - case "connected": - Output.Add("Identifiaction succes"); - break; + switch (packet.GetType().Name) + { + case "EventData": + EventData eve = (EventData)packet; + Output.Add(eve.ToSmallString()); + break; - case "allreadytaken": - Output.Add("Username Allready Taken"); - break; + case "ResultData": + ResultData res = (ResultData)packet; + Output.Add(res.ToSmallString()); + break; - case "kick": - if (array.Length > 1) - { - Output.Add("Kick : " + array[1]); - } - else - { - Output.Add("Kick by server"); - } - _run = false; - break; - - case "party": - if (array[1] == "kick") - { - if (array.Length > 2) - { - Output.Add("Kick from party : " + array[2]); - } - else - { - Output.Add("Kick from party"); - } - } - else - { - Output.Add("Unknown action from server"); - } - break; - - default: - Output.Add("Unknown action from server"); - break; - } - } - else - { - Output.Add(text); - } - break; - - case Common.dataType.data: - Console.WriteLine("data"); - break; + default: + Output.Add("Wrong packet"); + break; + } + } + else + { + Output.Add("Wrong packet"); } Thread.Sleep(200); } Output.Add("/*exit*/"); } + + public int GetRequestId(bool indent = true) + { + if (indent) { RequestId++; } + return RequestId; + } } } \ No newline at end of file diff --git a/Galactic Colors Control/Properties/AssemblyInfo.cs b/Galactic Colors Control/Properties/AssemblyInfo.cs index 3e1c97a..f868a8a 100644 --- a/Galactic Colors Control/Properties/AssemblyInfo.cs +++ b/Galactic Colors Control/Properties/AssemblyInfo.cs @@ -1,8 +1,7 @@ using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -// Les informations générales relatives à un assembly dépendent de +// Les informations générales relatives à un assembly dépendent de // l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations // associées à un assembly. [assembly: AssemblyTitle("Galactic Colors Control")] @@ -12,8 +11,8 @@ using System.Runtime.InteropServices; [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] -// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly -// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de +// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly +// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de // COM, affectez la valeur true à l'attribut ComVisible sur ce type. [assembly: ComVisible(false)] diff --git a/Readme.md b/Readme.md index 5374633..84cb47f 100644 --- a/Readme.md +++ b/Readme.md @@ -21,7 +21,7 @@ sudo apt-get install libopenal-dev mono-runtime * Galactic_Colors_Control_Console.exe => Client without GUI * Galactic_Colors_Control_GUI.exe => Client -* Galactic_Colors_Control_Server.exe => Server (Use --debug for DEBUG MODE) +* Galactic_Colors_Control_Server.exe => Server (Use --debug for DEBUG MODE or --dev at your risks) Linux ```