1
0
Fork 0

Cleaning and Add thread lock

This commit is contained in:
sheychen 2016-11-21 12:46:35 +01:00
parent 3928ce4f9b
commit 31263f8e0c
29 changed files with 305 additions and 196 deletions

View File

@ -9,12 +9,34 @@ namespace Galactic_Colors_Control_Common
/// </summary> /// </summary>
public static class Binary 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]; byte[] data = new byte[1];
data = bytes.Take(1).ToArray(); data = bytes.Take(1).ToArray();
RemoveFirst(ref bytes, 1); 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;
} }
///<remarks>1 byte</remarks> ///<remarks>1 byte</remarks>
@ -23,12 +45,19 @@ namespace Galactic_Colors_Control_Common
return x ? new byte[1] { 1 } : new byte[1] { 0 }; 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); res = null;
string text = Encoding.ASCII.GetString(bytes.Take(len).ToArray()); 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); RemoveFirst(ref bytes, len);
return text; return res != null;
} }
///<remarks>len(in bytes) + string</remarks> ///<remarks>len(in bytes) + string</remarks>
@ -38,19 +67,19 @@ namespace Galactic_Colors_Control_Common
return AddBytes(FromInt(data.Length), data); 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) res = int.MinValue;
return -1;
if (bytes.Length < 4) if (bytes.Length < 4)
return -1; return false;
byte[] data = new byte[4]; byte[] data = new byte[4];
data = bytes.Take(4).ToArray(); data = bytes.Take(4).ToArray();
data.Reverse(); data.Reverse();
res = BitConverter.ToInt32(data, 0);
RemoveFirst(ref bytes, 4); RemoveFirst(ref bytes, 4);
return BitConverter.ToInt32(data, 0); return res != int.MinValue;
} }
///<remarks>4 bytes</remarks> ///<remarks>4 bytes</remarks>
@ -61,18 +90,24 @@ namespace Galactic_Colors_Control_Common
return data; return data;
} }
public static string[] ToStringArray(ref byte[] bytes) public static bool TryToStringArray(ref byte[] bytes, out string[] data)
{ {
int len = ToInt(ref bytes); data = null;
if (len < 1 || len > 10000)
return new string[0];
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++) 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) public static byte[] FromStringArray(string[] array)
@ -88,15 +123,20 @@ namespace Galactic_Colors_Control_Common
return data; return data;
} }
public static int[] ToIntArray(ref byte[] bytes) public static bool TryToIntArray(ref byte[] bytes, out int[] res)
{ {
int len = ToInt(ref bytes); res = null;
int[] data = new int[len]; int len;
if (!TryToInt(ref bytes, out len))
return false;
res = new int[len];
for (int i = 0; i < len; i++) 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) public static byte[] FromIntArray(int[] array)
@ -123,9 +163,16 @@ namespace Galactic_Colors_Control_Common
public static void RemoveFirst(ref byte[] bytes, int count) public static void RemoveFirst(ref byte[] bytes, int count)
{ {
byte[] newbytes = new byte[bytes.Length - count]; if (bytes.Length - count < 0)
newbytes = bytes.Skip(count).ToArray(); {
bytes = newbytes; bytes = new byte[0] { };
}
else
{
byte[] newbytes = new byte[bytes.Length - count];
newbytes = bytes.Skip(count).ToArray();
bytes = newbytes;
}
} }
} }
} }

View File

@ -4,15 +4,14 @@ using System.Diagnostics;
using System.Globalization; using System.Globalization;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks;
namespace Galactic_Colors_Control_Common namespace Galactic_Colors_Control_Common
{ {
public class Logger public class Logger
{ {
public enum logType { dev, debug, info, warm, error, fatal } public enum logType { dev, debug, info, warm, error, fatal }
public enum logConsole { normal, show, hide } public enum logConsole { normal, show, hide }
public struct Log public struct Log
@ -61,6 +60,7 @@ namespace Galactic_Colors_Control_Common
{ {
//Sort old logs //Sort old logs
string[] files = Directory.GetFiles(logPath); string[] files = Directory.GetFiles(logPath);
foreach (string file in files) foreach (string file in files)
{ {
if (Path.GetExtension(file) == ".log") if (Path.GetExtension(file) == ".log")
@ -74,6 +74,7 @@ namespace Galactic_Colors_Control_Common
int y; int y;
int m; int m;
int d; 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(logPath + "/" + y + "/" + m + "/" + d)) if (!Directory.Exists(logPath + "/" + y + "/" + m + "/" + d))
@ -87,6 +88,7 @@ namespace Galactic_Colors_Control_Common
} }
} }
} }
int i = 0; int i = 0;
while (File.Exists(logPath + "/" + DateTime.UtcNow.ToString("yyyy-MM-dd-", CultureInfo.InvariantCulture) + i + ".log")) { i++; } 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"; 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) while (toWriteLogs.Count > 0)
{ {
Log log = toWriteLogs[0]; Log log = toWriteLogs[0]; //Saved log -> any lock need
if (log.type >= logLevel) if (log.type >= logLevel)
{ {
File.AppendAllText(logPath, DateTime.UtcNow.ToString("[yyyy-MM-dd]", CultureInfo.InvariantCulture) + " [" + log.type.ToString().ToUpper() + "]: " + log.text + Environment.NewLine); File.AppendAllText(logPath, DateTime.UtcNow.ToString("[yyyy-MM-dd]", CultureInfo.InvariantCulture) + " [" + log.type.ToString().ToUpper() + "]: " + log.text + Environment.NewLine);

View File

@ -1,6 +1,4 @@
using System; namespace Galactic_Colors_Control_Common.Protocol
namespace Galactic_Colors_Control_Common.Protocol
{ {
/// <summary> /// <summary>
/// Packet Master Class /// Packet Master Class
@ -15,7 +13,11 @@ namespace Galactic_Colors_Control_Common.Protocol
/// <param name="bytes">row bytes (remove used bytes)</param> /// <param name="bytes">row bytes (remove used bytes)</param>
public static Data FromBytes(ref byte[] 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: case DataType.Request:
return new RequestData(ref bytes); return new RequestData(ref bytes);

View File

@ -27,8 +27,14 @@
public EventData(ref byte[] bytes) public EventData(ref byte[] bytes)
{ {
type = (EventTypes)Binary.ToInt(ref bytes); int ntype;
data = Binary.ToStringArray(ref bytes); if (!Binary.TryToInt(ref bytes, out ntype))
return;
type = (EventTypes)ntype;
if (!Binary.TryToStringArray(ref bytes, out data))
return;
} }
public override byte[] ToBytes() public override byte[] ToBytes()

View File

@ -1,8 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Galactic_Colors_Control_Common.Protocol namespace Galactic_Colors_Control_Common.Protocol
{ {
@ -13,6 +9,7 @@ namespace Galactic_Colors_Control_Common.Protocol
public class EventDataArgs : EventArgs public class EventDataArgs : EventArgs
{ {
private EventData m_Data; private EventData m_Data;
public EventDataArgs(EventData _myData) public EventDataArgs(EventData _myData)
{ {
m_Data = _myData; m_Data = _myData;

View File

@ -16,8 +16,11 @@
public RequestData(ref byte[] bytes) public RequestData(ref byte[] bytes)
{ {
id = Binary.ToInt(ref bytes); if (!Binary.TryToInt(ref bytes, out id))
args = Binary.ToStringArray(ref bytes); return;
if (!Binary.TryToStringArray(ref bytes, out args))
return;
} }
public override byte[] ToBytes() public override byte[] ToBytes()

View File

@ -27,9 +27,16 @@
public ResultData(ref byte[] bytes) public ResultData(ref byte[] bytes)
{ {
id = Binary.ToInt(ref bytes); if (!Binary.TryToInt(ref bytes, out id))
type = (ResultTypes)Binary.ToInt(ref bytes); return;
result = Binary.ToStringArray(ref bytes);
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() public override byte[] ToBytes()

View File

@ -23,7 +23,7 @@ namespace Galactic_Colors_Control_Console
/// <returns>Loaded config</returns> /// <returns>Loaded config</returns>
public Config Load() public Config Load()
{ {
COnsole.logger.Write("Loading config", Logger.logType.info); Console.logger.Write("Loading config", Logger.logType.info);
Config config = new Config(); Config config = new Config();
if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "Config.xml")) if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "Config.xml"))
{ {
@ -37,7 +37,7 @@ namespace Galactic_Colors_Control_Console
} }
else 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.Delete(AppDomain.CurrentDomain.BaseDirectory + "Config.xml.old");
File.Move(AppDomain.CurrentDomain.BaseDirectory + "Config.xml", AppDomain.CurrentDomain.BaseDirectory + "Config.xml.old"); File.Move(AppDomain.CurrentDomain.BaseDirectory + "Config.xml", AppDomain.CurrentDomain.BaseDirectory + "Config.xml.old");
config.Save(); config.Save();
@ -45,11 +45,11 @@ namespace Galactic_Colors_Control_Console
} }
else else
{ {
COnsole.logger.Write("Any config file", Logger.logType.error); Console.logger.Write("Any config file", Logger.logType.error);
config.Save(); config.Save();
} }
if (COnsole._debug) { config.logLevel = Logger.logType.debug; } if (Console._debug) { config.logLevel = Logger.logType.debug; }
if (COnsole._dev) { config.logLevel = Logger.logType.dev; } if (Console._dev) { config.logLevel = Logger.logType.dev; }
return config; return config;
} }
@ -59,13 +59,13 @@ namespace Galactic_Colors_Control_Console
public void Save() public void Save()
{ {
XmlSerializer xs = new XmlSerializer(typeof(Config)); 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")) using (StreamWriter st = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "Config.xml"))
{ {
xs.Serialize(st, this); xs.Serialize(st, this);
}; };
if (COnsole._debug) { logLevel = Logger.logType.debug; } if (Console._debug) { logLevel = Logger.logType.debug; }
if (COnsole._dev) { logLevel = Logger.logType.dev; } if (Console._dev) { logLevel = Logger.logType.dev; }
} }
/// <summary> /// <summary>
@ -86,7 +86,7 @@ namespace Galactic_Colors_Control_Console
catch (XmlException e) catch (XmlException e)
{ {
isCorrect = false; 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) => d.Validate((o, e) =>
{ {
COnsole.logger.Write("Error: " + e.Message, Logger.logType.error); Console.logger.Write("Error: " + e.Message, Logger.logType.error);
isCorrect = false; isCorrect = false;
}); });
} }
catch (XmlException e) catch (XmlException e)
{ {
isCorrect = false; isCorrect = false;
COnsole.logger.Write("Error: " + e.Message, Logger.logType.error); Console.logger.Write("Error: " + e.Message, Logger.logType.error);
} }
} }

View File

@ -1,7 +1,6 @@
using Galactic_Colors_Control; using Galactic_Colors_Control;
using Galactic_Colors_Control_Common; using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol; using Galactic_Colors_Control_Common.Protocol;
using System;
using System.Reflection; using System.Reflection;
using System.Threading; using System.Threading;
@ -10,7 +9,7 @@ namespace Galactic_Colors_Control_Console
/// <summary> /// <summary>
/// Console Client /// Console Client
/// </summary> /// </summary>
internal class COnsole internal class Console
{ {
public static bool _debug = false; public static bool _debug = false;
public static bool _dev = false; public static bool _dev = false;
@ -23,14 +22,14 @@ namespace Galactic_Colors_Control_Console
private static void Main(string[] args) private static void Main(string[] args)
{ {
Console.Title = "Galactic Colors Control Client"; //Start display System.Console.Title = "Galactic Colors Control Client"; //Start display
Console.Write(">"); System.Console.Write(">");
logger.Write(Console.Title, Logger.logType.fatal); logger.Write(System.Console.Title, Logger.logType.fatal);
logger.Write("Console " + Assembly.GetEntryAssembly().GetName().Version.ToString(), Logger.logType.error); logger.Write("Console " + Assembly.GetEntryAssembly().GetName().Version.ToString(), Logger.logType.error);
config = config.Load(); config = config.Load();
logger.Initialise(config.logPath, config.logBackColor, config.logForeColor, config.logLevel, _debug, _dev); logger.Initialise(config.logPath, config.logBackColor, config.logForeColor, config.logLevel, _debug, _dev);
multilang.Load(); multilang.Load();
client.OnEvent += new EventHandler(OnEvent); //Set OnEvent function client.OnEvent += new System.EventHandler(OnEvent); //Set OnEvent function
if (args.Length > 0) if (args.Length > 0)
{ {
switch (args[0]) switch (args[0])
@ -54,25 +53,25 @@ namespace Galactic_Colors_Control_Console
while (!hostSet) //Request hostname while (!hostSet) //Request hostname
{ {
Thread.Sleep(100); Thread.Sleep(100);
Common.ConsoleWrite(multilang.Get("EnterHostname", config.lang) +":"); Common.ConsoleWrite(multilang.Get("EnterHostname", config.lang) + ":");
string host = client.ValidateHost(Console.ReadLine()); string host = client.ValidateHost(System.Console.ReadLine());
if (host[0] == '*') if (host[0] == '*')
{ {
host = host.Substring(1); host = host.Substring(1);
logger.Write("Validate error " + host, Logger.logType.error); logger.Write("Validate error " + host, Logger.logType.error);
Common.ConsoleWrite(host, ConsoleColor.Red); Common.ConsoleWrite(host, System.ConsoleColor.Red);
client.ResetHost(); client.ResetHost();
} }
else else
{ {
logger.Write("Validate " + host, Logger.logType.info); logger.Write("Validate " + host, Logger.logType.info);
Common.ConsoleWrite(multilang.Get("Use", config.lang) + " " + host + "? y/n"); Common.ConsoleWrite(multilang.Get("Use", config.lang) + " " + host + "? y/n");
ConsoleKeyInfo c = new ConsoleKeyInfo(); System.ConsoleKeyInfo c = new System.ConsoleKeyInfo();
while (c.Key != ConsoleKey.Y && c.Key != ConsoleKey.N) 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; hostSet = true;
} }
@ -92,11 +91,11 @@ namespace Galactic_Colors_Control_Console
while (!connected) while (!connected)
{ {
Common.ConsoleWrite(multilang.Get("Username", config.lang) + ":"); Common.ConsoleWrite(multilang.Get("Username", config.lang) + ":");
string username = Console.ReadLine(); string username = System.Console.ReadLine();
if (username.Length > 3) if (username.Length > 3)
{ {
ResultData res = client.Request(new string[3] { "connect", username, Protocol.version.ToString() }); 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 else
{ {
logger.Write("Identification error " + res.result, Logger.logType.info); logger.Write("Identification error " + res.result, Logger.logType.info);
@ -111,16 +110,16 @@ namespace Galactic_Colors_Control_Console
bool inparty = false; bool inparty = false;
while (!inparty) while (!inparty)
{ {
Console.Clear(); System.Console.Clear();
Common.ConsoleWrite(multilang.GetResultText(client.Request(new string[2] { "party", "list" }), config.lang)); Common.ConsoleWrite(multilang.GetResultText(client.Request(new string[2] { "party", "list" }), config.lang));
Common.ConsoleWrite(multilang.Get("Party", config.lang) + ":" + Environment.NewLine + " (<id> [password] or 'c' for create)"); Common.ConsoleWrite(multilang.Get("Party", config.lang) + ":" + System.Environment.NewLine + " (<id> [password] or 'c' for create)");
string[] data = Common.SplitArgs(Console.ReadLine()); string[] data = Common.SplitArgs(System.Console.ReadLine());
if (data.Length > 0) if (data.Length > 0)
{ {
if (data[0] == "c") if (data[0] == "c")
{ {
Common.ConsoleWrite("<party name> <player count>:"); Common.ConsoleWrite("<party name> <player count>:");
string[] split = Common.SplitArgs(Console.ReadLine()); string[] split = Common.SplitArgs(System.Console.ReadLine());
if (split.Length == 2) if (split.Length == 2)
{ {
ResultData createRes = client.Request(new string[4] { "party", "create", split[0], split[1] }); ResultData createRes = client.Request(new string[4] { "party", "create", split[0], split[1] });
@ -128,7 +127,7 @@ namespace Galactic_Colors_Control_Console
else else
{ {
Common.ConsoleWrite(multilang.GetResultText(createRes, config.lang)); Common.ConsoleWrite(multilang.GetResultText(createRes, config.lang));
Console.ReadLine(); System.Console.ReadLine();
} }
} }
else else
@ -160,19 +159,19 @@ namespace Galactic_Colors_Control_Console
Common.ConsoleWrite(multilang.Get("Play", config.lang)); Common.ConsoleWrite(multilang.Get("Play", config.lang));
while (run) while (run)
{ {
Execute(Console.ReadLine()); //Process console input Execute(System.Console.ReadLine()); //Process console input
if (!client.isRunning) { run = false; } if (!client.isRunning) { run = false; }
} }
Console.Read(); System.Console.Read();
} }
else else
{ {
logger.Write("Connection error", Logger.logType.error); 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; run = false;
logger.Join(); logger.Join();
Console.ReadLine(); System.Console.ReadLine();
} }
private static void Execute(string input) private static void Execute(string input)
@ -193,10 +192,10 @@ namespace Galactic_Colors_Control_Console
{ {
req = Common.Strings("say", input); 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 //TODO add PartyKick
EventData eve = ((EventDataArgs)e).Data; EventData eve = ((EventDataArgs)e).Data;

View File

@ -1,6 +1,6 @@
using System; using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Graphics;
using System;
namespace Galactic_Colors_Control_GUI namespace Galactic_Colors_Control_GUI
{ {

View File

@ -41,7 +41,7 @@ namespace Galactic_Colors_Control_GUI
private bool isFullScreen = false; 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 _ScreenWidth = 1280;
private int _ScreenHeight = 720; private int _ScreenHeight = 720;

View File

@ -10,6 +10,7 @@ namespace Galactic_Colors_Control_GUI
{ {
public static bool _dev = false; public static bool _dev = false;
public static bool _debug = false; public static bool _debug = false;
/// <summary> /// <summary>
/// The main entry point for the application. /// The main entry point for the application.
/// </summary> /// </summary>

View File

@ -1,9 +1,8 @@
using Microsoft.Xna.Framework; using Galactic_Colors_Control_Common;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Graphics;
using MyMonoGame.GUI; using MyMonoGame.GUI;
using System.Threading; using System.Threading;
using System;
using Galactic_Colors_Control_Common;
namespace Galactic_Colors_Control_GUI.States namespace Galactic_Colors_Control_GUI.States
{ {
@ -11,6 +10,7 @@ namespace Galactic_Colors_Control_GUI.States
{ {
public string title; public string title;
public string text; public string text;
public Message(string Title, string Text = "") public Message(string Title, string Text = "")
{ {
title = Title; title = Title;
@ -42,7 +42,7 @@ namespace Galactic_Colors_Control_GUI.States
if (showOKMessage) 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.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); 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; } 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 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) if (!locked)
{ {
locked = true; locked = true;

View File

@ -2,10 +2,10 @@
using Galactic_Colors_Control_Common.Protocol; using Galactic_Colors_Control_Common.Protocol;
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Graphics;
using MyMonoGame.GUI;
using System.Threading;
using System;
using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Input;
using MyMonoGame.GUI;
using System;
using System.Threading;
namespace Galactic_Colors_Control_GUI.States namespace Galactic_Colors_Control_GUI.States
{ {
@ -56,7 +56,8 @@ namespace Galactic_Colors_Control_GUI.States
public override void Update() 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.client.ExitHost();
Game.singleton.gameState = new MainMenuState(); 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.title = Game.singleton.multilang.Get("ServerKick", Game.singleton.config.lang);
message.text = Common.ArrayToString(eve.data); message.text = Common.ArrayToString(eve.data);
showOKMessage = true; showOKMessage = true;
}else }
else
{ {
ChatText(Game.singleton.multilang.GetEventText(eve, Game.singleton.config.lang)); ChatText(Game.singleton.multilang.GetEventText(eve, Game.singleton.config.lang));
} }

View File

@ -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 Microsoft.Xna.Framework.Graphics;
using MyMonoGame.GUI; using MyMonoGame.GUI;
using System.Threading; using System.Threading;
using System;
using Galactic_Colors_Control_Common.Protocol;
using Galactic_Colors_Control_Common;
namespace Galactic_Colors_Control_GUI.States namespace Galactic_Colors_Control_GUI.States
{ {
@ -20,7 +19,7 @@ namespace Galactic_Colors_Control_GUI.States
public override void Draw(SpriteBatch spritebatch) public override void Draw(SpriteBatch spritebatch)
{ {
Game.singleton.background.Draw(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) if (showLoading)
{ {
Game.singleton.GUI.Box(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 50), Game.singleton.buttonsSprites[0]); 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.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); 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 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) if (!locked)
{ {
locked = true; locked = true;
new Thread(IdentifiacateHost).Start(); 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) if (!locked)
{ {
locked = true; locked = true;
@ -93,7 +94,6 @@ namespace Galactic_Colors_Control_GUI.States
locked = false; locked = false;
} }
public override void Update() public override void Update()
{ {
Game.singleton.background.Update(); Game.singleton.background.Update();

View File

@ -1,11 +1,10 @@
using System; using Galactic_Colors_Control;
using Microsoft.Xna.Framework.Graphics; using Galactic_Colors_Control_Common;
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using MyMonoGame.GUI; using MyMonoGame.GUI;
using System.Reflection; using System.Reflection;
using Galactic_Colors_Control;
using System.Threading; using System.Threading;
using Galactic_Colors_Control_Common;
namespace Galactic_Colors_Control_GUI.States namespace Galactic_Colors_Control_GUI.States
{ {
@ -34,7 +33,8 @@ namespace Galactic_Colors_Control_GUI.States
}).Start(); }).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.GUI.ResetFocus();
Game.singleton.gameState = new OptionsState(); Game.singleton.gameState = new OptionsState();
} }

View File

@ -13,8 +13,8 @@ namespace Galactic_Colors_Control_GUI.States
{ {
Game.singleton.background.Draw(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 (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(); Game.singleton.GUI.ResetFocus();
ChangeLang(); ChangeLang();
} }

View File

@ -1,11 +1,9 @@
using Microsoft.Xna.Framework; using Galactic_Colors_Control_Common;
using Microsoft.Xna.Framework.Graphics;
using System.Collections.Generic;
using System.Threading;
using System;
using MyMonoGame.GUI;
using Galactic_Colors_Control_Common.Protocol; 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 namespace Galactic_Colors_Control_GUI.States
{ {
@ -68,7 +66,7 @@ namespace Galactic_Colors_Control_GUI.States
private void CreateParty() private void CreateParty()
{ {
showLoading = true; showLoading = true;
if(name != null) if (name != null)
{ {
int count; int count;
string party = name; string party = name;

View File

@ -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 Microsoft.Xna.Framework.Graphics;
using MyMonoGame.GUI; 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.Collections.Generic;
using System.Threading;
namespace Galactic_Colors_Control_GUI.States namespace Galactic_Colors_Control_GUI.States
{ {
@ -59,7 +58,7 @@ namespace Galactic_Colors_Control_GUI.States
else else
{ {
Game.singleton.GUI.Box(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 2 - 300, 300, 600), Game.singleton.buttonsSprites[0]); 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) 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)); //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 > 0)
if (parties.Count > 10) { {
if (parties.Count > 10)
{
//TODO page change //TODO page change
} }
for (int i = (page - 1) * 10; i < page * 10 && i < parties.Count; i++) 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; locked = true;
id = parties[i].id; id = parties[i].id;
@ -118,7 +119,8 @@ namespace Galactic_Colors_Control_GUI.States
showLoading = true; showLoading = true;
page = 1; page = 1;
ResultData res = Game.singleton.client.Request(new string[2] { "party", "list" }); ResultData res = Game.singleton.client.Request(new string[2] { "party", "list" });
if (res.type == ResultTypes.OK) { if (res.type == ResultTypes.OK)
{
parties.Clear(); parties.Clear();
foreach (string str in res.result) foreach (string str in res.result)
{ {
@ -143,7 +145,7 @@ namespace Galactic_Colors_Control_GUI.States
showLoading = true; showLoading = true;
if (id != -1) 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); ResultData res = Game.singleton.client.Request(request);
if (res.type == ResultTypes.OK) if (res.type == ResultTypes.OK)
{ {

View File

@ -9,12 +9,10 @@ namespace Galactic_Colors_Control_GUI.States
{ {
public virtual void Draw(SpriteBatch spritebatch) public virtual void Draw(SpriteBatch spritebatch)
{ {
} }
public virtual void Update() public virtual void Update()
{ {
} }
} }
} }

View File

@ -39,8 +39,11 @@ namespace Galactic_Colors_Control_Server.Commands
if (allreadyconnected) if (allreadyconnected)
return new RequestResult(ResultTypes.Error, Common.Strings("AllreadyTaken")); return new RequestResult(ResultTypes.Error, Common.Strings("AllreadyTaken"));
Server.clients[soc].status = 0; lock (Server.clients_lock)
Server.clients[soc].pseudo = args[1]; {
Server.clients[soc].status = 0;
Server.clients[soc].pseudo = args[1];
}
Utilities.Broadcast(new EventData(EventTypes.ServerJoin, Common.Strings(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); 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])); return new RequestResult(ResultTypes.OK, Common.Strings(args[1]));

View File

@ -19,14 +19,7 @@ namespace Galactic_Colors_Control_Server.Commands
public RequestResult Execute(string[] args, Socket soc, bool server = false) public RequestResult Execute(string[] args, Socket soc, bool server = false)
{ {
soc.Shutdown(SocketShutdown.Both); Server.RemoveClient(soc);
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);
return new RequestResult(ResultTypes.OK); return new RequestResult(ResultTypes.OK);
} }
} }

View File

@ -1,6 +1,5 @@
using Galactic_Colors_Control_Common; using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol; using Galactic_Colors_Control_Common.Protocol;
using System;
using System.Net.Sockets; using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands namespace Galactic_Colors_Control_Server.Commands

View File

@ -1,6 +1,5 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Sockets; using System.Net.Sockets;
using System.Threading;
namespace Galactic_Colors_Control_Server namespace Galactic_Colors_Control_Server
{ {

View File

@ -7,6 +7,7 @@ using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using System.Reflection; using System.Reflection;
using System.Threading; using System.Threading;
//TODO gui parties pages //TODO gui parties pages
namespace Galactic_Colors_Control_Server namespace Galactic_Colors_Control_Server
@ -24,11 +25,13 @@ namespace Galactic_Colors_Control_Server
private static readonly byte[] buffer = new byte[BUFFER_SIZE]; private static readonly byte[] buffer = new byte[BUFFER_SIZE];
public static Dictionary<Socket, Client> clients { get; private set; } = new Dictionary<Socket, Client>(); public static Dictionary<Socket, Client> clients { get; private set; } = new Dictionary<Socket, Client>();
public static object clients_lock = new object();
private static int partyID = 0; private static int partyID = 0;
private static object partyID_lock = new object();
public static Dictionary<int, Party> parties { get; private set; } = new Dictionary<int, Party>(); public static Dictionary<int, Party> parties { get; private set; } = new Dictionary<int, Party>(); //TODO add lock
public static int selectedParty = -1;       public static int selectedParty = -1; //TODO add lock
public static Config config = new Config(); public static Config config = new Config();
public static Logger logger = new Logger(); public static Logger logger = new Logger();
@ -129,6 +132,7 @@ namespace Galactic_Colors_Control_Server
private static void AcceptCallback(IAsyncResult AR) private static void AcceptCallback(IAsyncResult AR)
{ {
Socket socket; Socket socket;
try try
{ {
socket = serverSocket.EndAccept(AR); socket = serverSocket.EndAccept(AR);
@ -187,15 +191,9 @@ namespace Galactic_Colors_Control_Server
{ {
received = current.EndReceive(AR); received = current.EndReceive(AR);
} }
catch (SocketException) catch (Exception e)
{ {
logger.Write("Client forcefully disconnected from " + Utilities.GetName(current) + " : SocketException", Logger.logType.info); RemoveClient(current, e.GetType().Name);
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; return;
} }
@ -203,11 +201,13 @@ namespace Galactic_Colors_Control_Server
Array.Copy(buffer, data, received); Array.Copy(buffer, data, received);
Data packet = Data.FromBytes(ref data); Data packet = Data.FromBytes(ref data);
if (packet != null) if (packet != null)
{ {
switch (packet.GetType().Name) switch (packet.GetType().Name)
{ {
case "RequestData": case "RequestData":
RequestData req = (RequestData)packet; RequestData req = (RequestData)packet;
Utilities.Send(current, new ResultData(req.id, Commands.Manager.Execute(req.args, current))); Utilities.Send(current, new ResultData(req.id, Commands.Manager.Execute(req.args, current)));
break; break;
@ -221,7 +221,6 @@ namespace Galactic_Colors_Control_Server
{ {
logger.Write("Wrong packet from " + Utilities.GetName(current), Logger.logType.error); 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); } 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) if ((current.Poll(10, SelectMode.SelectRead) && current.Available == 0) || !current.Connected)
{ {
string username = Utilities.GetName(current); RemoveClient(current, "NotConnected");
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))); }
} }
}catch { } }
catch { }
Thread.Sleep(200); 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);
}
}
}
/// <summary> /// <summary>
/// Add new party with index /// Add new party with index
/// </summary> /// </summary>
@ -276,8 +292,11 @@ namespace Galactic_Colors_Control_Server
public static int GetPartyID(bool indent = true) public static int GetPartyID(bool indent = true)
{ {
if (indent) { partyID++; } lock (partyID_lock)
return partyID; {
if (indent) { partyID++; }
return partyID;
}
} }
} }
} }

View File

@ -18,6 +18,8 @@ namespace Galactic_Colors_Control
private Socket ClientSocket = new Socket private Socket ClientSocket = new Socket
(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private object ClientSocket_lock = new object();
public string IP = null; //Server IP public string IP = null; //Server IP
public int PORT = 0; //Server Port public int PORT = 0; //Server Port
@ -43,7 +45,11 @@ namespace Galactic_Colors_Control
public bool isRunning { get { return _run; } } public bool isRunning { get { return _run; } }
private int RequestId = 0; private int RequestId = 0;
private object RequestId_lock = new object();
private List<ResultData> Results = new List<ResultData>(); private List<ResultData> Results = new List<ResultData>();
private object Results_lock = new object();
private Thread RecieveThread; //Main Thread private Thread RecieveThread; //Main Thread
public EventHandler OnEvent; //Execute on EventData reception (must be short or async) 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) public string ValidateHost(string text)
{ {
if (text == null) { text = ""; } //Prevent NullException if (text == null) { text = ""; } //Prevent NullException
string[] parts = text.Split(new char[] { ':' }, 2, StringSplitOptions.RemoveEmptyEntries); //Split IP and Port string[] parts = text.Split(new char[] { ':' }, 2, StringSplitOptions.RemoveEmptyEntries); //Split IP and Port
if (parts.Length == 0) //Default config (localhost) if (parts.Length == 0) //Default config (localhost)
{ {
parts = new string[] { "" }; parts = new string[] { "" };
@ -140,9 +148,12 @@ namespace Galactic_Colors_Control
/// </summary> /// </summary>
private void ResetSocket() private void ResetSocket()
{ {
ClientSocket.Close(); lock (ClientSocket_lock)
ClientSocket = new Socket {
(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ClientSocket.Close();
ClientSocket = new Socket
(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
} }
/// <summary> /// <summary>
@ -153,12 +164,15 @@ namespace Galactic_Colors_Control
try { Send(new RequestData(GetRequestId(), new string[1] { "exit" })); } catch { }// Tell the server we are exiting try { Send(new RequestData(GetRequestId(), new string[1] { "exit" })); } catch { }// Tell the server we are exiting
_run = false; //Stopping Thread _run = false; //Stopping Thread
RecieveThread.Join(2000); RecieveThread.Join(2000);
try lock (ClientSocket_lock)
{ {
ClientSocket.Shutdown(SocketShutdown.Both); try
ClientSocket.Close(); {
ClientSocket.Shutdown(SocketShutdown.Both);
ClientSocket.Close();
}
catch { }
} }
catch { }
ResetHost(); ResetHost();
} }
@ -169,7 +183,7 @@ namespace Galactic_Colors_Control
/// <returns>ResultData or Timeout</returns> /// <returns>ResultData or Timeout</returns>
public ResultData Request(string[] args) public ResultData Request(string[] args)
{ {
switch(args[0]) switch (args[0])
{ {
case "exit": case "exit":
ExitHost(); ExitHost();
@ -181,7 +195,6 @@ namespace Galactic_Colors_Control
default: default:
return Execute(args); return Execute(args);
} }
} }
/// <summary> /// <summary>
@ -190,18 +203,23 @@ namespace Galactic_Colors_Control
private ResultData Execute(string[] args) private ResultData Execute(string[] args)
{ {
RequestData req = new RequestData(GetRequestId(), args); RequestData req = new RequestData(GetRequestId(), args);
if (!Send(req)) if (!Send(req))
return new ResultData(req.id, ResultTypes.Error, Common.Strings("Send Exception")); return new ResultData(req.id, ResultTypes.Error, Common.Strings("Send Exception"));
DateTime timeoutDate = DateTime.Now.AddMilliseconds(config.timeout); //Create timeout DataTime DateTime timeoutDate = DateTime.Now.AddMilliseconds(config.timeout); //Create timeout DataTime
while (timeoutDate > DateTime.Now) 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); if (res.id == req.id)
return res; {
Results.Remove(res);
return res;
}
} }
} }
Thread.Sleep(config.refresh); Thread.Sleep(config.refresh);
@ -252,6 +270,7 @@ namespace Galactic_Colors_Control
{ {
var buffer = new byte[2048]; var buffer = new byte[2048];
int received = 0; int received = 0;
try try
{ {
received = ClientSocket.Receive(buffer, SocketFlags.None); received = ClientSocket.Receive(buffer, SocketFlags.None);
@ -266,21 +285,26 @@ namespace Galactic_Colors_Control
} }
if (received == 0) return; if (received == 0) return;
_errorCount = 0; _errorCount = 0;
var data = new byte[received]; var data = new byte[received];
Array.Copy(buffer, data, received); Array.Copy(buffer, data, received);
Data packet = Data.FromBytes(ref data); //Create Data object from recieve bytes Data packet = Data.FromBytes(ref data); //Create Data object from recieve bytes
if (packet != null) if (packet != null)
{ {
switch (packet.GetType().Name) switch (packet.GetType().Name)
{ {
case "EventData": case "EventData":
EventData eve = (EventData)packet; EventData eve = (EventData)packet;
if (OnEvent != null) if (OnEvent != null)
OnEvent.Invoke(this, new EventDataArgs(eve)); OnEvent.Invoke(this, new EventDataArgs(eve));
break; break;
case "ResultData": case "ResultData":
ResultData res = (ResultData)packet; ResultData res = (ResultData)packet;
ResultAdd(res); ResultAdd(res);
break; break;
@ -296,7 +320,10 @@ namespace Galactic_Colors_Control
public int GetRequestId(bool indent = true) public int GetRequestId(bool indent = true)
{ {
if (indent) { RequestId++; } lock (RequestId_lock)
{
if (indent) { RequestId++; }
}
return RequestId; return RequestId;
} }
@ -305,8 +332,11 @@ namespace Galactic_Colors_Control
/// </summary> /// </summary>
public void ResultAdd(ResultData res) public void ResultAdd(ResultData res)
{ {
while (Results.Count + 1 > config.resultsBuffer) { Results.RemoveAt(0); } //Removes firsts lock (Results_lock)
Results.Add(res); {
while (Results.Count + 1 > config.resultsBuffer) { Results.RemoveAt(0); } //Removes firsts
Results.Add(res);
}
} }
} }
} }