From 31263f8e0c5027a44a5033c64d4d385d4173f2d3 Mon Sep 17 00:00:00 2001 From: sheychen Date: Mon, 21 Nov 2016 12:46:35 +0100 Subject: [PATCH] Cleaning and Add thread lock --- Galactic Colors Control Common/Binary.cs | 99 ++++++++++++++----- Galactic Colors Control Common/Logger.cs | 11 ++- Galactic Colors Control Common/MultiLang.cs | 2 +- .../Protocol/Data.cs | 12 ++- .../Protocol/EventData.cs | 10 +- .../Protocol/EventDataArgs.cs | 9 +- .../Protocol/Protocol.cs | 2 +- .../Protocol/RequestData.cs | 7 +- .../Protocol/ResultData.cs | 13 ++- Galactic Colors Control Console/Config.cs | 22 ++--- Galactic Colors Control Console/Program.cs | 51 +++++----- Galactic Colors Control GUI/Background.cs | 8 +- Galactic Colors Control GUI/Game.cs | 4 +- Galactic Colors Control GUI/Program.cs | 5 +- .../States/ConnectState.cs | 11 ++- .../States/GameState.cs | 12 ++- .../States/IndentificationState.cs | 18 ++-- .../States/MainMenuState.cs | 12 +-- .../States/OptionsState.cs | 4 +- .../States/PartyCreateState.cs | 16 ++- .../States/PartyState.cs | 24 ++--- Galactic Colors Control GUI/States/State.cs | 4 +- .../States/TitleState.cs | 2 +- .../Commands/ConnectCommand.cs | 7 +- .../Commands/ExitCommand.cs | 9 +- .../Commands/Party/PartyListCommand.cs | 3 +- Galactic Colors Control Server/Party.cs | 1 - Galactic Colors Control Server/Program.cs | 61 ++++++++---- Galactic Colors Control/Program.cs | 62 +++++++++--- 29 files changed, 305 insertions(+), 196 deletions(-) diff --git a/Galactic Colors Control Common/Binary.cs b/Galactic Colors Control Common/Binary.cs index 9d9b905..497e5a5 100644 --- a/Galactic Colors Control Common/Binary.cs +++ b/Galactic Colors Control Common/Binary.cs @@ -9,12 +9,34 @@ namespace Galactic_Colors_Control_Common /// public static class Binary { - public static bool ToBool(ref byte[] bytes) + public static bool TryToBool(ref byte[] bytes, out bool res) { + if (bytes.Length < 1) + { + res = false; + return false; + } + byte[] data = new byte[1]; data = bytes.Take(1).ToArray(); RemoveFirst(ref bytes, 1); - return data[1] == 1 ? true : false; + if (data[1] == 1) + { + res = true; + } + else + { + if (data[1] == 0) + { + res = false; + } + else + { + res = false; + return false; + } + } + return true; } ///1 byte @@ -23,12 +45,19 @@ namespace Galactic_Colors_Control_Common return x ? new byte[1] { 1 } : new byte[1] { 0 }; } - public static string ToString(ref byte[] bytes) + public static bool TryToString(ref byte[] bytes, out string res) { - int len = ToInt(ref bytes); - string text = Encoding.ASCII.GetString(bytes.Take(len).ToArray()); + res = null; + int len; + if (!TryToInt(ref bytes, out len)) + return false; + + if (bytes.Length < len) + return false; + + res = Encoding.ASCII.GetString(bytes.Take(len).ToArray()); RemoveFirst(ref bytes, len); - return text; + return res != null; } ///len(in bytes) + string @@ -38,19 +67,19 @@ namespace Galactic_Colors_Control_Common return AddBytes(FromInt(data.Length), data); } - public static int ToInt(ref byte[] bytes) + public static bool TryToInt(ref byte[] bytes, out int res) { - if (bytes == null) - return -1; + res = int.MinValue; if (bytes.Length < 4) - return -1; + return false; byte[] data = new byte[4]; data = bytes.Take(4).ToArray(); data.Reverse(); + res = BitConverter.ToInt32(data, 0); RemoveFirst(ref bytes, 4); - return BitConverter.ToInt32(data, 0); + return res != int.MinValue; } ///4 bytes @@ -61,18 +90,24 @@ namespace Galactic_Colors_Control_Common return data; } - public static string[] ToStringArray(ref byte[] bytes) + public static bool TryToStringArray(ref byte[] bytes, out string[] data) { - int len = ToInt(ref bytes); - if (len < 1 || len > 10000) - return new string[0]; + data = null; - string[] data = new string[len]; + int len; + if (!TryToInt(ref bytes, out len)) + return false; + + if (len < 1 || len > 10000) + return false; + + data = new string[len]; for (int i = 0; i < len; i++) { - data[i] = ToString(ref bytes); + if (!TryToString(ref bytes, out data[i])) + return false; } - return data; + return data != null; } public static byte[] FromStringArray(string[] array) @@ -88,15 +123,20 @@ namespace Galactic_Colors_Control_Common return data; } - public static int[] ToIntArray(ref byte[] bytes) + public static bool TryToIntArray(ref byte[] bytes, out int[] res) { - int len = ToInt(ref bytes); - int[] data = new int[len]; + res = null; + int len; + if (!TryToInt(ref bytes, out len)) + return false; + + res = new int[len]; for (int i = 0; i < len; i++) { - data[i] = ToInt(ref bytes); + if (!TryToInt(ref bytes, out res[i])) + return false; } - return data; + return res != null; } public static byte[] FromIntArray(int[] array) @@ -123,9 +163,16 @@ namespace Galactic_Colors_Control_Common public static void RemoveFirst(ref byte[] bytes, int count) { - byte[] newbytes = new byte[bytes.Length - count]; - newbytes = bytes.Skip(count).ToArray(); - bytes = newbytes; + if (bytes.Length - count < 0) + { + bytes = new byte[0] { }; + } + else + { + 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/Logger.cs b/Galactic Colors Control Common/Logger.cs index a78c31a..8acba41 100644 --- a/Galactic Colors Control Common/Logger.cs +++ b/Galactic Colors Control Common/Logger.cs @@ -4,15 +4,14 @@ using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; -using System.Text; using System.Threading; -using System.Threading.Tasks; namespace Galactic_Colors_Control_Common { public class Logger { public enum logType { dev, debug, info, warm, error, fatal } + public enum logConsole { normal, show, hide } public struct Log @@ -61,6 +60,7 @@ namespace Galactic_Colors_Control_Common { //Sort old logs string[] files = Directory.GetFiles(logPath); + foreach (string file in files) { if (Path.GetExtension(file) == ".log") @@ -74,6 +74,7 @@ namespace Galactic_Colors_Control_Common 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 (!Directory.Exists(logPath + "/" + y + "/" + m + "/" + d)) @@ -87,6 +88,7 @@ namespace Galactic_Colors_Control_Common } } } + int i = 0; while (File.Exists(logPath + "/" + DateTime.UtcNow.ToString("yyyy-MM-dd-", CultureInfo.InvariantCulture) + i + ".log")) { i++; } logPath = logPath + "/" + DateTime.UtcNow.ToString("yyyy-MM-dd-", CultureInfo.InvariantCulture) + i + ".log"; @@ -141,7 +143,8 @@ namespace Galactic_Colors_Control_Common { while (toWriteLogs.Count > 0) { - Log log = toWriteLogs[0]; + Log log = toWriteLogs[0]; //Saved log -> any lock need + if (log.type >= logLevel) { File.AppendAllText(logPath, DateTime.UtcNow.ToString("[yyyy-MM-dd]", CultureInfo.InvariantCulture) + " [" + log.type.ToString().ToUpper() + "]: " + log.text + Environment.NewLine); @@ -173,4 +176,4 @@ namespace Galactic_Colors_Control_Common Console.Write(">"); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Common/MultiLang.cs b/Galactic Colors Control Common/MultiLang.cs index f2bcd4a..4431d74 100644 --- a/Galactic Colors Control Common/MultiLang.cs +++ b/Galactic Colors Control Common/MultiLang.cs @@ -79,4 +79,4 @@ namespace Galactic_Colors_Control_Common return text; } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Common/Protocol/Data.cs b/Galactic Colors Control Common/Protocol/Data.cs index 59f84e7..3a2fb3c 100644 --- a/Galactic Colors Control Common/Protocol/Data.cs +++ b/Galactic Colors Control Common/Protocol/Data.cs @@ -1,6 +1,4 @@ -using System; - -namespace Galactic_Colors_Control_Common.Protocol +namespace Galactic_Colors_Control_Common.Protocol { /// /// Packet Master Class @@ -8,14 +6,18 @@ namespace Galactic_Colors_Control_Common.Protocol public class Data { public enum DataType { Request, Result, Event }; - + /// /// Create Packet from bytes /// /// row bytes (remove used bytes) public static Data FromBytes(ref byte[] bytes) { - switch ((DataType)Binary.ToInt(ref bytes)) + int type; + if (!Binary.TryToInt(ref bytes, out type)) + return null; + + switch ((DataType)type) { case DataType.Request: return new RequestData(ref bytes); diff --git a/Galactic Colors Control Common/Protocol/EventData.cs b/Galactic Colors Control Common/Protocol/EventData.cs index 7918063..3802b06 100644 --- a/Galactic Colors Control Common/Protocol/EventData.cs +++ b/Galactic Colors Control Common/Protocol/EventData.cs @@ -27,8 +27,14 @@ public EventData(ref byte[] bytes) { - type = (EventTypes)Binary.ToInt(ref bytes); - data = Binary.ToStringArray(ref bytes); + int ntype; + if (!Binary.TryToInt(ref bytes, out ntype)) + return; + + type = (EventTypes)ntype; + + if (!Binary.TryToStringArray(ref bytes, out data)) + return; } public override byte[] ToBytes() diff --git a/Galactic Colors Control Common/Protocol/EventDataArgs.cs b/Galactic Colors Control Common/Protocol/EventDataArgs.cs index e17413b..81304e5 100644 --- a/Galactic Colors Control Common/Protocol/EventDataArgs.cs +++ b/Galactic Colors Control Common/Protocol/EventDataArgs.cs @@ -1,18 +1,15 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Galactic_Colors_Control_Common.Protocol { /// - /// Hide EventData in EventArgs + /// Hide EventData in EventArgs /// for OnEvent Handler /// public class EventDataArgs : EventArgs { private EventData m_Data; + public EventDataArgs(EventData _myData) { m_Data = _myData; @@ -20,4 +17,4 @@ namespace Galactic_Colors_Control_Common.Protocol public EventData Data { get { return m_Data; } } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Common/Protocol/Protocol.cs b/Galactic Colors Control Common/Protocol/Protocol.cs index 8849cf4..be90fe3 100644 --- a/Galactic Colors Control Common/Protocol/Protocol.cs +++ b/Galactic Colors Control Common/Protocol/Protocol.cs @@ -6,4 +6,4 @@ namespace Galactic_Colors_Control_Common.Protocol { public static Version version = new Version(0, 1); //Protocol version } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Common/Protocol/RequestData.cs b/Galactic Colors Control Common/Protocol/RequestData.cs index d686c05..a67b2ab 100644 --- a/Galactic Colors Control Common/Protocol/RequestData.cs +++ b/Galactic Colors Control Common/Protocol/RequestData.cs @@ -16,8 +16,11 @@ public RequestData(ref byte[] bytes) { - id = Binary.ToInt(ref bytes); - args = Binary.ToStringArray(ref bytes); + if (!Binary.TryToInt(ref bytes, out id)) + return; + + if (!Binary.TryToStringArray(ref bytes, out args)) + return; } public override byte[] ToBytes() diff --git a/Galactic Colors Control Common/Protocol/ResultData.cs b/Galactic Colors Control Common/Protocol/ResultData.cs index 137891e..96d6c46 100644 --- a/Galactic Colors Control Common/Protocol/ResultData.cs +++ b/Galactic Colors Control Common/Protocol/ResultData.cs @@ -27,9 +27,16 @@ public ResultData(ref byte[] bytes) { - id = Binary.ToInt(ref bytes); - type = (ResultTypes)Binary.ToInt(ref bytes); - result = Binary.ToStringArray(ref bytes); + if (!Binary.TryToInt(ref bytes, out id)) + return; + + int ntype; + if (!Binary.TryToInt(ref bytes, out ntype)) + return; + + type = (ResultTypes)ntype; + if (!Binary.TryToStringArray(ref bytes, out result)) + return; } public override byte[] ToBytes() diff --git a/Galactic Colors Control Console/Config.cs b/Galactic Colors Control Console/Config.cs index baebf83..7d92b43 100644 --- a/Galactic Colors Control Console/Config.cs +++ b/Galactic Colors Control Console/Config.cs @@ -23,7 +23,7 @@ namespace Galactic_Colors_Control_Console /// Loaded config public Config Load() { - COnsole.logger.Write("Loading config", Logger.logType.info); + Console.logger.Write("Loading config", Logger.logType.info); Config config = new Config(); if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "Config.xml")) { @@ -37,7 +37,7 @@ namespace Galactic_Colors_Control_Console } else { - COnsole.logger.Write("Old config in Config.xml.old", Logger.logType.warm); + Console.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(); @@ -45,11 +45,11 @@ namespace Galactic_Colors_Control_Console } else { - COnsole.logger.Write("Any config file", Logger.logType.error); + Console.logger.Write("Any config file", Logger.logType.error); config.Save(); } - if (COnsole._debug) { config.logLevel = Logger.logType.debug; } - if (COnsole._dev) { config.logLevel = Logger.logType.dev; } + if (Console._debug) { config.logLevel = Logger.logType.debug; } + if (Console._dev) { config.logLevel = Logger.logType.dev; } return config; } @@ -59,13 +59,13 @@ namespace Galactic_Colors_Control_Console public void Save() { XmlSerializer xs = new XmlSerializer(typeof(Config)); - if (COnsole._debug || COnsole._dev) { logLevel = Logger.logType.info; } + if (Console._debug || Console._dev) { logLevel = Logger.logType.info; } using (StreamWriter st = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "Config.xml")) { xs.Serialize(st, this); }; - if (COnsole._debug) { logLevel = Logger.logType.debug; } - if (COnsole._dev) { logLevel = Logger.logType.dev; } + if (Console._debug) { logLevel = Logger.logType.debug; } + if (Console._dev) { logLevel = Logger.logType.dev; } } /// @@ -86,7 +86,7 @@ namespace Galactic_Colors_Control_Console catch (XmlException e) { isCorrect = false; - COnsole.logger.Write("Error: " + e.Message, Logger.logType.error); + Console.logger.Write("Error: " + e.Message, Logger.logType.error); } } @@ -100,14 +100,14 @@ namespace Galactic_Colors_Control_Console d.Validate((o, e) => { - COnsole.logger.Write("Error: " + e.Message, Logger.logType.error); + Console.logger.Write("Error: " + e.Message, Logger.logType.error); isCorrect = false; }); } catch (XmlException e) { isCorrect = false; - COnsole.logger.Write("Error: " + e.Message, Logger.logType.error); + Console.logger.Write("Error: " + e.Message, Logger.logType.error); } } diff --git a/Galactic Colors Control Console/Program.cs b/Galactic Colors Control Console/Program.cs index 7d143cd..88c4dd2 100644 --- a/Galactic Colors Control Console/Program.cs +++ b/Galactic Colors Control Console/Program.cs @@ -1,7 +1,6 @@ using Galactic_Colors_Control; using Galactic_Colors_Control_Common; using Galactic_Colors_Control_Common.Protocol; -using System; using System.Reflection; using System.Threading; @@ -10,7 +9,7 @@ namespace Galactic_Colors_Control_Console /// /// Console Client /// - internal class COnsole + internal class Console { public static bool _debug = false; public static bool _dev = false; @@ -23,14 +22,14 @@ namespace Galactic_Colors_Control_Console private static void Main(string[] args) { - Console.Title = "Galactic Colors Control Client"; //Start display - Console.Write(">"); - logger.Write(Console.Title, Logger.logType.fatal); + System.Console.Title = "Galactic Colors Control Client"; //Start display + System.Console.Write(">"); + logger.Write(System.Console.Title, Logger.logType.fatal); logger.Write("Console " + Assembly.GetEntryAssembly().GetName().Version.ToString(), Logger.logType.error); config = config.Load(); logger.Initialise(config.logPath, config.logBackColor, config.logForeColor, config.logLevel, _debug, _dev); multilang.Load(); - client.OnEvent += new EventHandler(OnEvent); //Set OnEvent function + client.OnEvent += new System.EventHandler(OnEvent); //Set OnEvent function if (args.Length > 0) { switch (args[0]) @@ -54,25 +53,25 @@ namespace Galactic_Colors_Control_Console while (!hostSet) //Request hostname { Thread.Sleep(100); - Common.ConsoleWrite(multilang.Get("EnterHostname", config.lang) +":"); - string host = client.ValidateHost(Console.ReadLine()); + Common.ConsoleWrite(multilang.Get("EnterHostname", config.lang) + ":"); + string host = client.ValidateHost(System.Console.ReadLine()); if (host[0] == '*') { host = host.Substring(1); logger.Write("Validate error " + host, Logger.logType.error); - Common.ConsoleWrite(host, ConsoleColor.Red); + Common.ConsoleWrite(host, System.ConsoleColor.Red); client.ResetHost(); } else { logger.Write("Validate " + host, Logger.logType.info); Common.ConsoleWrite(multilang.Get("Use", config.lang) + " " + host + "? y/n"); - ConsoleKeyInfo c = new ConsoleKeyInfo(); - while (c.Key != ConsoleKey.Y && c.Key != ConsoleKey.N) + System.ConsoleKeyInfo c = new System.ConsoleKeyInfo(); + while (c.Key != System.ConsoleKey.Y && c.Key != System.ConsoleKey.N) { - c = Console.ReadKey(); + c = System.Console.ReadKey(); } - if (c.Key == ConsoleKey.Y) + if (c.Key == System.ConsoleKey.Y) { hostSet = true; } @@ -92,11 +91,11 @@ namespace Galactic_Colors_Control_Console while (!connected) { Common.ConsoleWrite(multilang.Get("Username", config.lang) + ":"); - string username = Console.ReadLine(); + string username = System.Console.ReadLine(); if (username.Length > 3) { ResultData res = client.Request(new string[3] { "connect", username, Protocol.version.ToString() }); - if(res.type == ResultTypes.OK) { connected = true; logger.Write("Identification", Logger.logType.info); } + if (res.type == ResultTypes.OK) { connected = true; logger.Write("Identification", Logger.logType.info); } else { logger.Write("Identification error " + res.result, Logger.logType.info); @@ -111,16 +110,16 @@ namespace Galactic_Colors_Control_Console bool inparty = false; while (!inparty) { - Console.Clear(); + System.Console.Clear(); Common.ConsoleWrite(multilang.GetResultText(client.Request(new string[2] { "party", "list" }), config.lang)); - Common.ConsoleWrite(multilang.Get("Party", config.lang) + ":" + Environment.NewLine + " ( [password] or 'c' for create)"); - string[] data = Common.SplitArgs(Console.ReadLine()); + Common.ConsoleWrite(multilang.Get("Party", config.lang) + ":" + System.Environment.NewLine + " ( [password] or 'c' for create)"); + string[] data = Common.SplitArgs(System.Console.ReadLine()); if (data.Length > 0) { if (data[0] == "c") { Common.ConsoleWrite(" :"); - string[] split = Common.SplitArgs(Console.ReadLine()); + string[] split = Common.SplitArgs(System.Console.ReadLine()); if (split.Length == 2) { ResultData createRes = client.Request(new string[4] { "party", "create", split[0], split[1] }); @@ -128,7 +127,7 @@ namespace Galactic_Colors_Control_Console else { Common.ConsoleWrite(multilang.GetResultText(createRes, config.lang)); - Console.ReadLine(); + System.Console.ReadLine(); } } else @@ -160,19 +159,19 @@ namespace Galactic_Colors_Control_Console Common.ConsoleWrite(multilang.Get("Play", config.lang)); while (run) { - Execute(Console.ReadLine()); //Process console input + Execute(System.Console.ReadLine()); //Process console input if (!client.isRunning) { run = false; } } - Console.Read(); + System.Console.Read(); } else { logger.Write("Connection error", Logger.logType.error); - Common.ConsoleWrite(multilang.Get("CantConnect", config.lang), ConsoleColor.Red); + Common.ConsoleWrite(multilang.Get("CantConnect", config.lang), System.ConsoleColor.Red); } run = false; logger.Join(); - Console.ReadLine(); + System.Console.ReadLine(); } private static void Execute(string input) @@ -193,10 +192,10 @@ namespace Galactic_Colors_Control_Console { req = Common.Strings("say", input); } - Common.ConsoleWrite(multilang.GetResultText(client.Request(req),config.lang)); + Common.ConsoleWrite(multilang.GetResultText(client.Request(req), config.lang)); } - private static void OnEvent(object sender, EventArgs e) + private static void OnEvent(object sender, System.EventArgs e) { //TODO add PartyKick EventData eve = ((EventDataArgs)e).Data; diff --git a/Galactic Colors Control GUI/Background.cs b/Galactic Colors Control GUI/Background.cs index b04284c..4f98066 100644 --- a/Galactic Colors Control GUI/Background.cs +++ b/Galactic Colors Control GUI/Background.cs @@ -1,6 +1,6 @@ -using System; -using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; +using System; namespace Galactic_Colors_Control_GUI { @@ -46,7 +46,7 @@ namespace Galactic_Colors_Control_GUI if (backgroundY[index] > backSprites[index].Height) { backgroundY[index] = 0; } if (backgroundX[index] < 0) { backgroundX[index] = backSprites[index].Width; } if (backgroundY[index] < 0) { backgroundY[index] = backSprites[index].Height; } - } + } } /// @@ -71,4 +71,4 @@ namespace Galactic_Colors_Control_GUI } } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control GUI/Game.cs b/Galactic Colors Control GUI/Game.cs index 9df80d0..0f35d29 100644 --- a/Galactic Colors Control GUI/Game.cs +++ b/Galactic Colors Control GUI/Game.cs @@ -41,7 +41,7 @@ namespace Galactic_Colors_Control_GUI private bool isFullScreen = false; - public States.State gameState = new States.TitleState(new States.MainMenuState(), new TimeSpan(0,0,5)); + public States.State gameState = new States.TitleState(new States.MainMenuState(), new TimeSpan(0, 0, 5)); private int _ScreenWidth = 1280; private int _ScreenHeight = 720; @@ -209,7 +209,7 @@ namespace Galactic_Colors_Control_GUI GUI.Draw(spriteBatch); gameState.Draw(spriteBatch); - + Color ActiveColor = IsActive ? Color.Green : Color.Red; GUI.Label(new MyMonoGame.Vector(10, ScreenHeight - 20), (1 / (float)gameTime.ElapsedGameTime.TotalSeconds).ToString(), fonts.small, new MyMonoGame.Colors(ActiveColor)); spriteBatch.Draw(pointerSprites[0], new Rectangle(Mouse.GetState().X - 10, Mouse.GetState().Y - 10, 20, 20), Color.Red); diff --git a/Galactic Colors Control GUI/Program.cs b/Galactic Colors Control GUI/Program.cs index 18b1aa6..623ffaa 100644 --- a/Galactic Colors Control GUI/Program.cs +++ b/Galactic Colors Control GUI/Program.cs @@ -10,6 +10,7 @@ namespace Galactic_Colors_Control_GUI { public static bool _dev = false; public static bool _debug = false; + /// /// The main entry point for the application. /// @@ -21,11 +22,11 @@ namespace Galactic_Colors_Control_GUI switch (args[0]) { case "--debug": - _debug = true; + _debug = true; break; case "--dev": - _dev = true; + _dev = true; break; default: diff --git a/Galactic Colors Control GUI/States/ConnectState.cs b/Galactic Colors Control GUI/States/ConnectState.cs index 5f6dc35..57b189a 100644 --- a/Galactic Colors Control GUI/States/ConnectState.cs +++ b/Galactic Colors Control GUI/States/ConnectState.cs @@ -1,9 +1,8 @@ -using Microsoft.Xna.Framework; +using Galactic_Colors_Control_Common; +using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MyMonoGame.GUI; using System.Threading; -using System; -using Galactic_Colors_Control_Common; namespace Galactic_Colors_Control_GUI.States { @@ -11,6 +10,7 @@ namespace Galactic_Colors_Control_GUI.States { public string title; public string text; + public Message(string Title, string Text = "") { title = Title; @@ -42,7 +42,7 @@ namespace Galactic_Colors_Control_GUI.States if (showOKMessage) { Game.singleton.GUI.Box(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 150), Game.singleton.buttonsSprites[0]); - Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4 + 60), message.title, Game.singleton.fonts.basic , null, Manager.textAlign.bottomCenter); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4 + 60), message.title, Game.singleton.fonts.basic, null, Manager.textAlign.bottomCenter); Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4 + 100), message.text, Game.singleton.fonts.small, null, Manager.textAlign.bottomCenter); if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 140, Game.singleton.ScreenHeight / 4 + 150, 280, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("OK", Game.singleton.config.lang), Game.singleton.fonts.basic)) { locked = false; Game.singleton.GUI.ResetFocus(); showOKMessage = false; } } @@ -71,7 +71,8 @@ namespace Galactic_Colors_Control_GUI.States } else { - if (Game.singleton.GUI.TextField(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 - 30, 150, 40), ref adress, Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White), Manager.textAlign.centerCenter, Game.singleton.multilang.Get("EnterHostname", Game.singleton.config.lang))) { + if (Game.singleton.GUI.TextField(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 - 30, 150, 40), ref adress, Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White), Manager.textAlign.centerCenter, Game.singleton.multilang.Get("EnterHostname", Game.singleton.config.lang))) + { if (!locked) { locked = true; diff --git a/Galactic Colors Control GUI/States/GameState.cs b/Galactic Colors Control GUI/States/GameState.cs index 0d834af..fd18af9 100644 --- a/Galactic Colors Control GUI/States/GameState.cs +++ b/Galactic Colors Control GUI/States/GameState.cs @@ -2,10 +2,10 @@ using Galactic_Colors_Control_Common.Protocol; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using MyMonoGame.GUI; -using System.Threading; -using System; using Microsoft.Xna.Framework.Input; +using MyMonoGame.GUI; +using System; +using System.Threading; namespace Galactic_Colors_Control_GUI.States { @@ -56,7 +56,8 @@ namespace Galactic_Colors_Control_GUI.States public override void Update() { - if (Keyboard.GetState().IsKeyDown(Keys.Escape) || (!Game.singleton.client.isRunning)) { + if (Keyboard.GetState().IsKeyDown(Keys.Escape) || (!Game.singleton.client.isRunning)) + { Game.singleton.client.ExitHost(); Game.singleton.gameState = new MainMenuState(); } @@ -99,7 +100,8 @@ namespace Galactic_Colors_Control_GUI.States message.title = Game.singleton.multilang.Get("ServerKick", Game.singleton.config.lang); message.text = Common.ArrayToString(eve.data); showOKMessage = true; - }else + } + else { ChatText(Game.singleton.multilang.GetEventText(eve, Game.singleton.config.lang)); } diff --git a/Galactic Colors Control GUI/States/IndentificationState.cs b/Galactic Colors Control GUI/States/IndentificationState.cs index 38a5066..52570d7 100644 --- a/Galactic Colors Control GUI/States/IndentificationState.cs +++ b/Galactic Colors Control GUI/States/IndentificationState.cs @@ -1,10 +1,9 @@ -using Microsoft.Xna.Framework; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MyMonoGame.GUI; using System.Threading; -using System; -using Galactic_Colors_Control_Common.Protocol; -using Galactic_Colors_Control_Common; namespace Galactic_Colors_Control_GUI.States { @@ -20,7 +19,7 @@ namespace Galactic_Colors_Control_GUI.States public override void Draw(SpriteBatch spritebatch) { Game.singleton.background.Draw(spritebatch); - Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4), Game.singleton.multilang.Get("GCC", Game.singleton.config.lang), Game.singleton.fonts.title , new MyMonoGame.Colors(Color.White), Manager.textAlign.centerCenter); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4), Game.singleton.multilang.Get("GCC", Game.singleton.config.lang), Game.singleton.fonts.title, new MyMonoGame.Colors(Color.White), Manager.textAlign.centerCenter); if (showLoading) { Game.singleton.GUI.Box(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 50), Game.singleton.buttonsSprites[0]); @@ -33,18 +32,20 @@ namespace Galactic_Colors_Control_GUI.States Game.singleton.GUI.Box(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 150), Game.singleton.buttonsSprites[0]); Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4 + 60), message.title, Game.singleton.fonts.basic, null, Manager.textAlign.bottomCenter); Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4 + 100), message.text, Game.singleton.fonts.small, null, Manager.textAlign.bottomCenter); - if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 140, Game.singleton.ScreenHeight / 4 + 150, 280, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("OK", Game.singleton.config.lang), Game.singleton.fonts.basic)){ Game.singleton.GUI.ResetFocus(); showOKMessage = false; } + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 140, Game.singleton.ScreenHeight / 4 + 150, 280, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("OK", Game.singleton.config.lang), Game.singleton.fonts.basic)) { Game.singleton.GUI.ResetFocus(); showOKMessage = false; } } else { - if (Game.singleton.GUI.TextField(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 - 30, 150, 40), ref username, Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White), Manager.textAlign.centerCenter, Game.singleton.multilang.Get("Username", Game.singleton.config.lang))) { + if (Game.singleton.GUI.TextField(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 - 30, 150, 40), ref username, Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White), Manager.textAlign.centerCenter, Game.singleton.multilang.Get("Username", Game.singleton.config.lang))) + { if (!locked) { locked = true; new Thread(IdentifiacateHost).Start(); } } - if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 + 20, 150, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("Validate", Game.singleton.config.lang), Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White))) { + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 + 20, 150, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("Validate", Game.singleton.config.lang), Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White))) + { if (!locked) { locked = true; @@ -93,7 +94,6 @@ namespace Galactic_Colors_Control_GUI.States locked = false; } - public override void Update() { Game.singleton.background.Update(); diff --git a/Galactic Colors Control GUI/States/MainMenuState.cs b/Galactic Colors Control GUI/States/MainMenuState.cs index cac61b7..54be37a 100644 --- a/Galactic Colors Control GUI/States/MainMenuState.cs +++ b/Galactic Colors Control GUI/States/MainMenuState.cs @@ -1,11 +1,10 @@ -using System; -using Microsoft.Xna.Framework.Graphics; +using Galactic_Colors_Control; +using Galactic_Colors_Control_Common; using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; using MyMonoGame.GUI; using System.Reflection; -using Galactic_Colors_Control; using System.Threading; -using Galactic_Colors_Control_Common; namespace Galactic_Colors_Control_GUI.States { @@ -34,7 +33,8 @@ namespace Galactic_Colors_Control_GUI.States }).Start(); } } - if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 + 20, 150, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("Options", Game.singleton.config.lang), Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.White, Color.Blue))) { + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 + 20, 150, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("Options", Game.singleton.config.lang), Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.White, Color.Blue))) + { Game.singleton.GUI.ResetFocus(); Game.singleton.gameState = new OptionsState(); } @@ -61,4 +61,4 @@ namespace Galactic_Colors_Control_GUI.States Game.singleton.background.Update(); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control GUI/States/OptionsState.cs b/Galactic Colors Control GUI/States/OptionsState.cs index 6fbdc0f..5da602e 100644 --- a/Galactic Colors Control GUI/States/OptionsState.cs +++ b/Galactic Colors Control GUI/States/OptionsState.cs @@ -13,8 +13,8 @@ namespace Galactic_Colors_Control_GUI.States { Game.singleton.background.Draw(spritebatch); Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4), Game.singleton.multilang.Get("GCC", Game.singleton.config.lang), Game.singleton.fonts.title, new MyMonoGame.Colors(Color.White), Manager.textAlign.centerCenter); - if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 + 20, 150, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Langs[Game.singleton.config.lang], Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White))) { - + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 + 20, 150, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Langs[Game.singleton.config.lang], Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White))) + { Game.singleton.GUI.ResetFocus(); ChangeLang(); } diff --git a/Galactic Colors Control GUI/States/PartyCreateState.cs b/Galactic Colors Control GUI/States/PartyCreateState.cs index 2be2702..4902d0a 100644 --- a/Galactic Colors Control GUI/States/PartyCreateState.cs +++ b/Galactic Colors Control GUI/States/PartyCreateState.cs @@ -1,11 +1,9 @@ -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using System.Collections.Generic; -using System.Threading; -using System; -using MyMonoGame.GUI; +using Galactic_Colors_Control_Common; using Galactic_Colors_Control_Common.Protocol; -using Galactic_Colors_Control_Common; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using MyMonoGame.GUI; +using System.Threading; namespace Galactic_Colors_Control_GUI.States { @@ -68,7 +66,7 @@ namespace Galactic_Colors_Control_GUI.States private void CreateParty() { showLoading = true; - if(name != null) + if (name != null) { int count; string party = name; @@ -100,4 +98,4 @@ namespace Galactic_Colors_Control_GUI.States Game.singleton.background.Update(); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control GUI/States/PartyState.cs b/Galactic Colors Control GUI/States/PartyState.cs index 6020a88..9b500c9 100644 --- a/Galactic Colors Control GUI/States/PartyState.cs +++ b/Galactic Colors Control GUI/States/PartyState.cs @@ -1,11 +1,10 @@ -using Microsoft.Xna.Framework; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MyMonoGame.GUI; -using System.Threading; -using System; -using Galactic_Colors_Control_Common.Protocol; -using Galactic_Colors_Control_Common; using System.Collections.Generic; +using System.Threading; namespace Galactic_Colors_Control_GUI.States { @@ -59,7 +58,7 @@ namespace Galactic_Colors_Control_GUI.States else { Game.singleton.GUI.Box(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 2 - 300, 300, 600), Game.singleton.buttonsSprites[0]); - if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 140, Game.singleton.ScreenHeight / 2 - 290, 100, 40), Game.singleton.buttonsSprites[0] ,Game.singleton.multilang.Get("Update", Game.singleton.config.lang), Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White))) + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 140, Game.singleton.ScreenHeight / 2 - 290, 100, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("Update", Game.singleton.config.lang), Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White))) { if (!locked) { @@ -77,13 +76,15 @@ namespace Galactic_Colors_Control_GUI.States } //TODO Game.singleton.GUI.TextField(new Rectangle(Game.singleton.ScreenWidth / 2 + 40, Game.singleton.ScreenHeight / 2 - 290, 100, 40), ref password, Game.singleton.fonts.basic, null, Manager.textAlign.centerCenter, Game.singleton.multilang.Get("Password", Game.singleton.config.lang)); - if (parties.Count > 0) { - if (parties.Count > 10) { + if (parties.Count > 0) + { + if (parties.Count > 10) + { //TODO page change } for (int i = (page - 1) * 10; i < page * 10 && i < parties.Count; i++) { - if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 100, Game.singleton.ScreenHeight / 2 - 240 + i*50, 200, 40), Game.singleton.buttonsSprites[0], parties[i].text, Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White))) + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 100, Game.singleton.ScreenHeight / 2 - 240 + i * 50, 200, 40), Game.singleton.buttonsSprites[0], parties[i].text, Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White))) { locked = true; id = parties[i].id; @@ -118,7 +119,8 @@ namespace Galactic_Colors_Control_GUI.States showLoading = true; page = 1; ResultData res = Game.singleton.client.Request(new string[2] { "party", "list" }); - if (res.type == ResultTypes.OK) { + if (res.type == ResultTypes.OK) + { parties.Clear(); foreach (string str in res.result) { @@ -143,7 +145,7 @@ namespace Galactic_Colors_Control_GUI.States showLoading = true; if (id != -1) { - string[] request = password != null ? new string[4] { "party", "join", id.ToString() , password } : new string[3] { "party", "join", id.ToString() }; + string[] request = password != null ? new string[4] { "party", "join", id.ToString(), password } : new string[3] { "party", "join", id.ToString() }; ResultData res = Game.singleton.client.Request(request); if (res.type == ResultTypes.OK) { diff --git a/Galactic Colors Control GUI/States/State.cs b/Galactic Colors Control GUI/States/State.cs index 294cd2f..e67113a 100644 --- a/Galactic Colors Control GUI/States/State.cs +++ b/Galactic Colors Control GUI/States/State.cs @@ -9,12 +9,10 @@ namespace Galactic_Colors_Control_GUI.States { public virtual void Draw(SpriteBatch spritebatch) { - } public virtual void Update() { - } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control GUI/States/TitleState.cs b/Galactic Colors Control GUI/States/TitleState.cs index a9c2ad9..6d30985 100644 --- a/Galactic Colors Control GUI/States/TitleState.cs +++ b/Galactic Colors Control GUI/States/TitleState.cs @@ -38,4 +38,4 @@ namespace Galactic_Colors_Control_GUI.States } } } -} +} \ 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 60d6e45..b7ad3d2 100644 --- a/Galactic Colors Control Server/Commands/ConnectCommand.cs +++ b/Galactic Colors Control Server/Commands/ConnectCommand.cs @@ -39,8 +39,11 @@ namespace Galactic_Colors_Control_Server.Commands if (allreadyconnected) return new RequestResult(ResultTypes.Error, Common.Strings("AllreadyTaken")); - Server.clients[soc].status = 0; - Server.clients[soc].pseudo = args[1]; + lock (Server.clients_lock) + { + Server.clients[soc].status = 0; + Server.clients[soc].pseudo = args[1]; + } Utilities.Broadcast(new EventData(EventTypes.ServerJoin, Common.Strings(args[1]))); Server.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])); diff --git a/Galactic Colors Control Server/Commands/ExitCommand.cs b/Galactic Colors Control Server/Commands/ExitCommand.cs index 808f18f..b5d8021 100644 --- a/Galactic Colors Control Server/Commands/ExitCommand.cs +++ b/Galactic Colors Control Server/Commands/ExitCommand.cs @@ -19,14 +19,7 @@ namespace Galactic_Colors_Control_Server.Commands public RequestResult Execute(string[] args, Socket soc, bool server = false) { - soc.Shutdown(SocketShutdown.Both); - Server.logger.Write("Client disconnected from " + Utilities.GetName(soc), Logger.logType.info); - string username = Utilities.GetName(soc); - bool connected = Server.clients[soc].status != -1; - soc.Close(); - Server.clients.Remove(soc); - if (connected) { Utilities.Broadcast(new EventData(EventTypes.ServerLeave, Common.Strings(username))); } - Server.logger.Write("Size: " + Server.clients.Count + "/" + Server.config.size, Logger.logType.debug); + Server.RemoveClient(soc); return new RequestResult(ResultTypes.OK); } } diff --git a/Galactic Colors Control Server/Commands/Party/PartyListCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyListCommand.cs index 32c7ffd..12cfe30 100644 --- a/Galactic Colors Control Server/Commands/Party/PartyListCommand.cs +++ b/Galactic Colors Control Server/Commands/Party/PartyListCommand.cs @@ -1,6 +1,5 @@ using Galactic_Colors_Control_Common; using Galactic_Colors_Control_Common.Protocol; -using System; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -21,7 +20,7 @@ namespace Galactic_Colors_Control_Server.Commands public RequestResult Execute(string[] args, Socket soc, bool server = false) { if (Server.parties.Keys.Count == 0) - return new RequestResult(ResultTypes.Error, Common.Strings("AnyParty")); + return new RequestResult(ResultTypes.Error, Common.Strings("AnyParty")); string[] text = new string[Server.parties.Keys.Count]; int i = 0; diff --git a/Galactic Colors Control Server/Party.cs b/Galactic Colors Control Server/Party.cs index 4908533..5a8307e 100644 --- a/Galactic Colors Control Server/Party.cs +++ b/Galactic Colors Control Server/Party.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using System.Net.Sockets; -using System.Threading; namespace Galactic_Colors_Control_Server { diff --git a/Galactic Colors Control Server/Program.cs b/Galactic Colors Control Server/Program.cs index cc47fbe..ee2f560 100644 --- a/Galactic Colors Control Server/Program.cs +++ b/Galactic Colors Control Server/Program.cs @@ -7,6 +7,7 @@ using System.Net; using System.Net.Sockets; using System.Reflection; using System.Threading; + //TODO gui parties pages namespace Galactic_Colors_Control_Server @@ -24,11 +25,13 @@ namespace Galactic_Colors_Control_Server private static readonly byte[] buffer = new byte[BUFFER_SIZE]; public static Dictionary clients { get; private set; } = new Dictionary(); + public static object clients_lock = new object(); private static int partyID = 0; + private static object partyID_lock = new object(); - public static Dictionary parties { get; private set; } = new Dictionary(); - public static int selectedParty = -1; + public static Dictionary parties { get; private set; } = new Dictionary(); //TODO add lock +       public static int selectedParty = -1; //TODO add lock public static Config config = new Config(); public static Logger logger = new Logger(); @@ -129,6 +132,7 @@ namespace Galactic_Colors_Control_Server private static void AcceptCallback(IAsyncResult AR) { Socket socket; + try { socket = serverSocket.EndAccept(AR); @@ -187,15 +191,9 @@ namespace Galactic_Colors_Control_Server { received = current.EndReceive(AR); } - catch (SocketException) + catch (Exception e) { - 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))); } + RemoveClient(current, e.GetType().Name); return; } @@ -203,11 +201,13 @@ namespace Galactic_Colors_Control_Server Array.Copy(buffer, data, received); 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; @@ -221,7 +221,6 @@ namespace Galactic_Colors_Control_Server { logger.Write("Wrong packet from " + Utilities.GetName(current), Logger.logType.error); } - if (clients.ContainsKey(current)) { current.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, current); } } @@ -251,20 +250,37 @@ namespace Galactic_Colors_Control_Server { 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))); } + RemoveClient(current, "NotConnected"); } - }catch { } + } + catch { } Thread.Sleep(200); } } } + public static void RemoveClient(Socket current, string reason = null) + { + //TODO add leave party for check empty parties + lock (clients_lock) + { + if (clients.ContainsKey(current)) + { + string username = Utilities.GetName(current); + logger.Write("Client forcefully disconnected from " + username + (reason != null ? " : " + reason : ""), 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))); } + } + else + { + logger.Write("Client forcefully disconnected : ObjectDisposedException", Logger.logType.warm); + } + } + } + /// /// Add new party with index /// @@ -276,8 +292,11 @@ namespace Galactic_Colors_Control_Server public static int GetPartyID(bool indent = true) { - if (indent) { partyID++; } - return partyID; + lock (partyID_lock) + { + if (indent) { partyID++; } + return partyID; + } } } } \ No newline at end of file diff --git a/Galactic Colors Control/Program.cs b/Galactic Colors Control/Program.cs index 47ff6f8..60ef4e8 100644 --- a/Galactic Colors Control/Program.cs +++ b/Galactic Colors Control/Program.cs @@ -18,6 +18,8 @@ namespace Galactic_Colors_Control private Socket ClientSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + private object ClientSocket_lock = new object(); + public string IP = null; //Server IP public int PORT = 0; //Server Port @@ -43,7 +45,11 @@ namespace Galactic_Colors_Control public bool isRunning { get { return _run; } } private int RequestId = 0; + private object RequestId_lock = new object(); + private List Results = new List(); + private object Results_lock = new object(); + private Thread RecieveThread; //Main Thread public EventHandler OnEvent; //Execute on EventData reception (must be short or async) @@ -64,7 +70,9 @@ namespace Galactic_Colors_Control public string ValidateHost(string text) { if (text == null) { text = ""; } //Prevent NullException + string[] parts = text.Split(new char[] { ':' }, 2, StringSplitOptions.RemoveEmptyEntries); //Split IP and Port + if (parts.Length == 0) //Default config (localhost) { parts = new string[] { "" }; @@ -140,9 +148,12 @@ namespace Galactic_Colors_Control /// private void ResetSocket() { - ClientSocket.Close(); - ClientSocket = new Socket - (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + lock (ClientSocket_lock) + { + ClientSocket.Close(); + ClientSocket = new Socket + (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + } } /// @@ -153,12 +164,15 @@ namespace Galactic_Colors_Control try { Send(new RequestData(GetRequestId(), new string[1] { "exit" })); } catch { }// Tell the server we are exiting _run = false; //Stopping Thread RecieveThread.Join(2000); - try + lock (ClientSocket_lock) { - ClientSocket.Shutdown(SocketShutdown.Both); - ClientSocket.Close(); + try + { + ClientSocket.Shutdown(SocketShutdown.Both); + ClientSocket.Close(); + } + catch { } } - catch { } ResetHost(); } @@ -169,7 +183,7 @@ namespace Galactic_Colors_Control /// ResultData or Timeout public ResultData Request(string[] args) { - switch(args[0]) + switch (args[0]) { case "exit": ExitHost(); @@ -181,7 +195,6 @@ namespace Galactic_Colors_Control default: return Execute(args); } - } /// @@ -190,18 +203,23 @@ namespace Galactic_Colors_Control private ResultData Execute(string[] args) { RequestData req = new RequestData(GetRequestId(), args); + if (!Send(req)) return new ResultData(req.id, ResultTypes.Error, Common.Strings("Send Exception")); DateTime timeoutDate = DateTime.Now.AddMilliseconds(config.timeout); //Create timeout DataTime + while (timeoutDate > DateTime.Now) { - foreach (ResultData res in Results.ToArray()) //Check all results + lock (Results_lock) { - if (res.id == req.id) + foreach (ResultData res in Results.ToArray()) //Check all results { - Results.Remove(res); - return res; + if (res.id == req.id) + { + Results.Remove(res); + return res; + } } } Thread.Sleep(config.refresh); @@ -252,6 +270,7 @@ namespace Galactic_Colors_Control { var buffer = new byte[2048]; int received = 0; + try { received = ClientSocket.Receive(buffer, SocketFlags.None); @@ -266,21 +285,26 @@ namespace Galactic_Colors_Control } if (received == 0) return; _errorCount = 0; + var data = new byte[received]; Array.Copy(buffer, data, received); Data packet = Data.FromBytes(ref data); //Create Data object from recieve bytes + if (packet != null) { switch (packet.GetType().Name) { case "EventData": + EventData eve = (EventData)packet; + if (OnEvent != null) OnEvent.Invoke(this, new EventDataArgs(eve)); break; case "ResultData": + ResultData res = (ResultData)packet; ResultAdd(res); break; @@ -296,7 +320,10 @@ namespace Galactic_Colors_Control public int GetRequestId(bool indent = true) { - if (indent) { RequestId++; } + lock (RequestId_lock) + { + if (indent) { RequestId++; } + } return RequestId; } @@ -305,8 +332,11 @@ namespace Galactic_Colors_Control /// public void ResultAdd(ResultData res) { - while (Results.Count + 1 > config.resultsBuffer) { Results.RemoveAt(0); } //Removes firsts - Results.Add(res); + lock (Results_lock) + { + while (Results.Count + 1 > config.resultsBuffer) { Results.RemoveAt(0); } //Removes firsts + Results.Add(res); + } } } } \ No newline at end of file