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>
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;
}
///<remarks>1 byte</remarks>
@ -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;
}
///<remarks>len(in bytes) + string</remarks>
@ -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;
}
///<remarks>4 bytes</remarks>
@ -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;
}
}
}
}

View File

@ -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(">");
}
}
}
}

View File

@ -79,4 +79,4 @@ namespace Galactic_Colors_Control_Common
return text;
}
}
}
}

View File

@ -1,6 +1,4 @@
using System;
namespace Galactic_Colors_Control_Common.Protocol
namespace Galactic_Colors_Control_Common.Protocol
{
/// <summary>
/// Packet Master Class
@ -8,14 +6,18 @@ namespace Galactic_Colors_Control_Common.Protocol
public class Data
{
public enum DataType { Request, Result, Event };
/// <summary>
/// Create Packet from bytes
/// </summary>
/// <param name="bytes">row bytes (remove used bytes)</param>
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);

View File

@ -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()

View File

@ -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
{
/// <summary>
/// Hide EventData in EventArgs
/// Hide EventData in EventArgs
/// for OnEvent Handler
/// </summary>
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; } }
}
}
}

View File

@ -6,4 +6,4 @@ namespace Galactic_Colors_Control_Common.Protocol
{
public static Version version = new Version(0, 1); //Protocol version
}
}
}

View File

@ -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()

View File

@ -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()

View File

@ -23,7 +23,7 @@ namespace Galactic_Colors_Control_Console
/// <returns>Loaded config</returns>
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; }
}
/// <summary>
@ -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);
}
}

View File

@ -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
/// <summary>
/// Console Client
/// </summary>
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 + " (<id> [password] or 'c' for create)");
string[] data = Common.SplitArgs(Console.ReadLine());
Common.ConsoleWrite(multilang.Get("Party", config.lang) + ":" + System.Environment.NewLine + " (<id> [password] or 'c' for create)");
string[] data = Common.SplitArgs(System.Console.ReadLine());
if (data.Length > 0)
{
if (data[0] == "c")
{
Common.ConsoleWrite("<party name> <player count>:");
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;

View File

@ -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; }
}
}
}
/// <summary>
@ -71,4 +71,4 @@ namespace Galactic_Colors_Control_GUI
}
}
}
}
}

View File

@ -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);

View File

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

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 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;

View File

@ -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));
}

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 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();

View File

@ -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();
}
}
}
}

View File

@ -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();
}

View File

@ -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();
}
}
}
}

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 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)
{

View File

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

View File

@ -38,4 +38,4 @@ namespace Galactic_Colors_Control_GUI.States
}
}
}
}
}

View File

@ -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]));

View File

@ -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);
}
}

View File

@ -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;

View File

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

View File

@ -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<Socket, Client> clients { get; private set; } = new Dictionary<Socket, Client>();
public static object clients_lock = new object();
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 int selectedParty = -1;
public static Dictionary<int, Party> parties { get; private set; } = new Dictionary<int, Party>(); //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);
}
}
}
/// <summary>
/// Add new party with index
/// </summary>
@ -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;
}
}
}
}

View File

@ -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<ResultData> Results = new List<ResultData>();
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
/// </summary>
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);
}
}
/// <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
_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
/// <returns>ResultData or Timeout</returns>
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);
}
}
/// <summary>
@ -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
/// </summary>
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);
}
}
}
}