1
0
Fork 0

Common Logger, MultiLang(not used), Config

This commit is contained in:
sheychen 2016-11-15 18:54:13 +01:00
parent ed1f647fa2
commit 5add5b8f28
28 changed files with 769 additions and 127 deletions

View File

@ -49,7 +49,14 @@
</Compile>
<Compile Include="Binary.cs" />
<Compile Include="Common.cs" />
<Compile Include="Logger.cs" />
<Compile Include="MultiLang.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="Protocol\Data.cs" />
<Compile Include="Protocol\EventData.cs" />
<Compile Include="Protocol\EventDataArgs.cs" />
@ -57,6 +64,15 @@
<Compile Include="Protocol\RequestResult.cs" />
<Compile Include="Protocol\ResultData.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="Resources\Lang.csv" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.

View File

@ -1,25 +1,20 @@
using Galactic_Colors_Control_Common;
using System;
using System;
using System.Collections.Generic;
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_Server
namespace Galactic_Colors_Control_Common
{
public class Logger
{
public enum logType { dev, debug, info, warm, error, fatal }
public enum logConsole { normal, show, hide }
private static List<Log> toWriteLogs = new List<Log>();
private static string logPath;
public static Thread Updater;
public static bool _run = true;
public struct Log
{
public string text;
@ -34,20 +29,34 @@ namespace Galactic_Colors_Control_Server
}
}
private List<Log> toWriteLogs = new List<Log>();
private string logPath;
private ConsoleColor[] logBackColor;
private ConsoleColor[] logForeColor;
private Thread Updater;
private logType logLevel;
private bool _run = true;
public bool run { get { return _run; } }
/// <summary>
/// Create log file and start logger thread
/// </summary>
public static void Initialise()
/// <param name="LogPath">Absolute path to logs directory</param>
public void Initialise(string LogPath, ConsoleColor[] backColor, ConsoleColor[] foreColor, logType LogLevel)
{
if (!Directory.Exists(Program.config.logPath))
logPath = LogPath;
logBackColor = backColor;
logForeColor = foreColor;
logLevel = LogLevel;
if (!Directory.Exists(logPath))
{
Directory.CreateDirectory(Program.config.logPath);
Directory.CreateDirectory(logPath);
Write("Log Directory Created", logType.info);
}
else
{
//Sort old logs
string[] files = Directory.GetFiles(Program.config.logPath);
string[] files = Directory.GetFiles(logPath);
foreach (string file in files)
{
if (Path.GetExtension(file) == ".log")
@ -63,11 +72,11 @@ namespace Galactic_Colors_Control_Server
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(Program.config.logPath + "/" + y + "/" + m + "/" + d))
if (!Directory.Exists(logPath + "/" + y + "/" + m + "/" + d))
{
Directory.CreateDirectory(Program.config.logPath + "/" + y + "/" + m + "/" + d);
Directory.CreateDirectory(logPath + "/" + y + "/" + m + "/" + d);
}
File.Move(file, Program.config.logPath + "/" + y + "/" + m + "/" + d + "/" + Path.GetFileName(file));
File.Move(file, logPath + "/" + y + "/" + m + "/" + d + "/" + Path.GetFileName(file));
}
}
}
@ -75,20 +84,32 @@ namespace Galactic_Colors_Control_Server
}
}
int i = 0;
while (File.Exists(Program.config.logPath + "/" + DateTime.UtcNow.ToString("yyyy-MM-dd-", CultureInfo.InvariantCulture) + i + ".log")) { i++; }
logPath = Program.config.logPath + "/" + DateTime.UtcNow.ToString("yyyy-MM-dd-", CultureInfo.InvariantCulture) + i + ".log";
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";
Write("Log path:" + logPath, logType.debug);
Updater = new Thread(new ThreadStart(UpdaterLoop));
Updater.Start();
}
public void Join()
{
_run = false;
Updater.Join();
}
public void ChangeLevel(logType level)
{
logLevel = level;
Write("Change to " + logLevel.ToString(), logType.info, logConsole.show);
}
/// <summary>
/// Add log to log pile
/// </summary>
/// <param name="text">Log text</param>
/// <param name="type">Log status</param>
/// <param name="console">Server display modifier</param>
public static void Write(string text, logType type, logConsole console = logConsole.normal)
public void Write(string text, logType type, logConsole console = logConsole.normal)
{
Write(new Log(text, type, console));
}
@ -97,9 +118,9 @@ namespace Galactic_Colors_Control_Server
/// Add log to log pile
/// </summary>
/// <param name="log">Log struct</param>
public static void Write(Log log)
private void Write(Log log)
{
if (Program.config.logLevel == logType.debug || Program.config.logLevel == logType.dev)
if (logLevel == logType.debug || logLevel == logType.dev)
{
//Add Source Method
log.text = "[" + new StackTrace().GetFrame(2).GetMethod().Name + "]: " + log.text;
@ -110,44 +131,42 @@ namespace Galactic_Colors_Control_Server
/// <summary>
/// Write log pile to logfile and console
/// </summary>
public static void UpdaterLoop()
public void UpdaterLoop()
{
while (_run || toWriteLogs.Count > 0)
{
while (toWriteLogs.Count > 0)
{
Log log = toWriteLogs[0];
if (log.type >= Program.config.logLevel)
if (log.type >= logLevel)
{
File.AppendAllText(logPath, DateTime.UtcNow.ToString("[yyyy-MM-dd]", CultureInfo.InvariantCulture) + " [" + log.type.ToString().ToUpper() + "]: " + log.text + Environment.NewLine);
if (log.console != logConsole.hide)
{
Console.BackgroundColor = Program.config.logBackColor[(int)log.type];
Console.ForegroundColor = Program.config.logForeColor[(int)log.type];
Console.Write("\b");
Console.WriteLine(DateTime.UtcNow.ToString("[yyyy-MM-dd]", CultureInfo.InvariantCulture) + ": " + log.text);
Common.ConsoleResetColor();
Console.Write(">");
ConsoleWrite(log);
}
}
//TODO reactive show logger
/*
else
{
if(log.console == logConsole.show)
if (log.console == logConsole.show)
{
Console.BackgroundColor = Program.config.logBackColor[(int)log.type];
Console.ForegroundColor = Program.config.logForeColor[(int)log.type];
Console.Write("\b");
Console.WriteLine(DateTime.UtcNow.ToString("[yyyy-MM-dd]", CultureInfo.InvariantCulture) + ": " + log.text);
Utilities.ConsoleResetColor();
Console.Write(">");
ConsoleWrite(log);
}
}*/
}
toWriteLogs.Remove(log);
}
Thread.Sleep(200);
}
}
private void ConsoleWrite(Log log)
{
Console.BackgroundColor = logBackColor[(int)log.type];
Console.ForegroundColor = logForeColor[(int)log.type];
Console.Write("\b");
Console.WriteLine(DateTime.UtcNow.ToString("[yyyy-MM-dd]", CultureInfo.InvariantCulture) + ": " + log.text);
Common.ConsoleResetColor();
Console.Write(">");
}
}
}
}

View File

@ -0,0 +1,74 @@
using Galactic_Colors_Control_Common.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Galactic_Colors_Control_Common
{
public class MultiLang
{
private Dictionary<string, List<string>> _multiDictionary = new Dictionary<string, List<string>>(); //List of phrases by key
private List<string> _Langs = new List<string>(); //Readable langs list
public Dictionary<string, List<string>> multiDictionary { get { return _multiDictionary; } }
public List<string> Langs { get { return _Langs; } }
public void Load()
{
_multiDictionary.Clear();
_Langs.Clear();
string[] lines = Properties.Resources.Lang.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries); //Load from .cvs ressources. //TODO add more langs
_Langs = lines[0].Split(';').OfType<string>().ToList();
_Langs.RemoveAt(0);
foreach (string line in lines)
{
List<string> items = line.Split(';').OfType<string>().ToList();
string key = items[0];
items.RemoveAt(0);
_multiDictionary.Add(key, items);
}
}
public string GetEventText(EventData eve, int lang)
{
string data = Common.ArrayToString(eve.data);
switch (eve.type)
{
case EventTypes.ChatMessage:
return data;
case EventTypes.PartyJoin:
case EventTypes.PartyLeave:
case EventTypes.ServerJoin:
case EventTypes.ServerLeave:
return data + " " + Get(eve.type.ToString(), lang);
default:
return eve.ToSmallString();
}
}
public string Get(string Key, int Lang)
{
string text = "";
if (_multiDictionary.ContainsKey(Key))
{
if (_multiDictionary[Key].Count >= Lang)
{
text = _multiDictionary[Key][Lang];
}
else
{
text = "!!!UNKNOW LANG KEY!!!";
}
}
else
{
text = "!!!UNKNOW WORD KEY!!!";
}
return text;
}
}
}

View File

@ -0,0 +1,87 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Ce code a été généré par un outil.
// Version du runtime :4.0.30319.42000
//
// Les modifications apportées à ce fichier peuvent provoquer un comportement incorrect et seront perdues si
// le code est régénéré.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Galactic_Colors_Control_Common.Properties {
using System;
/// <summary>
/// Une classe de ressource fortement typée destinée, entre autres, à la consultation des chaînes localisées.
/// </summary>
// Cette classe a été générée automatiquement par la classe StronglyTypedResourceBuilder
// à l'aide d'un outil, tel que ResGen ou Visual Studio.
// Pour ajouter ou supprimer un membre, modifiez votre fichier .ResX, puis réexécutez ResGen
// avec l'option /str ou régénérez votre projet VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Retourne l'instance ResourceManager mise en cache utilisée par cette classe.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Galactic_Colors_Control_Common.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Remplace la propriété CurrentUICulture du thread actuel pour toutes
/// les recherches de ressources à l'aide de cette classe de ressource fortement typée.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Recherche une chaîne localisée semblable à Key;Français;English
///Registered;Enregistré;Registered
///Not Registered;Non Enregistré;Not Registered
///File;Fichier;File
///Export;Exporter;Export
///Quit;Quitter;Quit
///Licence;Licence;License
///Language;Langue;Language
///Help;Aide;Help
///About;À Propos;About
///QuitConfirm;Êtes-vous certain de vouloir quitter CycleMollier ?;Are you sure than you would like to quit CycleMollier ?
///BP;Basse Pression;Low Pressure
///HP;Haute Pression;High Pressure
///InBar;(En Bar);(In Bar)
///Draw;Tracer;Draw
///DrawText;Tracer le diagramme e [le reste de la chaîne a été tronqué]&quot;;.
/// </summary>
internal static string Lang {
get {
return ResourceManager.GetString("Lang", resourceCulture);
}
}
}
}

View File

@ -0,0 +1,124 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="Lang" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\Lang.csv;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8</value>
</data>
</root>

View File

@ -0,0 +1,5 @@
Key;Français;English
ServerJoin;rejoint le server;join the server
PartyJoin;rejoint la partie;join the party
ServerLeave;quitte le server;leave the server
PartyLeave;quitte la partie;leave the party
1 Key Français English
2 ServerJoin rejoint le server join the server
3 PartyJoin rejoint la partie join the party
4 ServerLeave quitte le server leave the server
5 PartyLeave quitte la partie leave the party

View File

@ -0,0 +1,117 @@
using Galactic_Colors_Control_Common;
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace Galactic_Colors_Control_Console
{
[XmlRoot("config")]
public class Config
{
public string logPath = AppDomain.CurrentDomain.BaseDirectory + "Logs";
public Logger.logType logLevel = Logger.logType.info;
public char commandChar = '/';
public ConsoleColor[] logForeColor = new ConsoleColor[6] { ConsoleColor.DarkGray, ConsoleColor.Gray, ConsoleColor.White, ConsoleColor.Yellow, ConsoleColor.Red, ConsoleColor.White };
public ConsoleColor[] logBackColor = new ConsoleColor[6] { ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Red };
public int lang = 0;
/// <summary>
/// Load config from xml file
/// App.config is too easy
/// </summary>
/// <returns>Loaded config</returns>
public Config Load()
{
Program.logger.Write("Loading config", Logger.logType.info);
Config config = new Config();
if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "Config.xml"))
{
if (CorrectConfig())
{
XmlSerializer xs = new XmlSerializer(typeof(Config));
using (StreamReader re = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "Config.xml"))
{
config = xs.Deserialize(re) as Config;
};
}
else
{
Program.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();
}
}
else
{
Program.logger.Write("Any config file", Logger.logType.error);
config.Save();
}
if (Program._debug) { config.logLevel = Logger.logType.debug; }
if (Program._dev) { config.logLevel = Logger.logType.dev; }
return config;
}
/// <summary>
/// Write actual config in xml file
/// </summary>
public void Save()
{
XmlSerializer xs = new XmlSerializer(typeof(Config));
if (Program._debug || Program._dev) { logLevel = Logger.logType.info; }
using (StreamWriter st = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "Config.xml"))
{
xs.Serialize(st, this);
};
if (Program._debug) { logLevel = Logger.logType.debug; }
if (Program._dev) { logLevel = Logger.logType.dev; }
}
/// <summary>
/// Check config format using Schema
/// </summary>
public bool CorrectConfig()
{
bool isCorrect = false;
using (Stream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "Config.xml", FileMode.Open))
{
XmlReader re = new XmlTextReader(fs);
XmlSerializer xs = new XmlSerializer(typeof(Config));
try
{
isCorrect = xs.CanDeserialize(re);
}
catch (XmlException e)
{
isCorrect = false;
Program.logger.Write("Error: " + e.Message, Logger.logType.error);
}
}
if (isCorrect)
{
try
{
XmlDocument d = new XmlDocument();
d.Load(AppDomain.CurrentDomain.BaseDirectory + "Config.xml");
d.Schemas.Add("", XmlReader.Create("ConfigSchema.xsd"));
d.Validate((o, e) =>
{
Program.logger.Write("Error: " + e.Message, Logger.logType.error);
isCorrect = false;
});
}
catch (XmlException e)
{
isCorrect = false;
Program.logger.Write("Error: " + e.Message, Logger.logType.error);
}
}
return isCorrect;
}
}
}

View File

@ -47,6 +47,7 @@
<Compile Include="..\AssemblyInfoCommon.cs">
<Link>Properties\AssemblyInfoCommon.cs</Link>
</Compile>
<Compile Include="Config.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>

View File

@ -11,18 +11,44 @@ namespace Galactic_Colors_Control_Console
/// </summary>
internal class Program
{
private static Client client;
private static bool run = true;
private static char commandChar = '/';
public static bool _debug = false;
public static bool _dev = false;
private static void Main()
private static Client client = new Client();
private static MultiLang multilang = new MultiLang(); //TODO use multilang
public static Config config = new Config();
public static Logger logger = new Logger();
private static bool run = true;
private static void Main(string[] args)
{
client = new Client();
config = config.Load();
logger.Initialise(config.logPath, config.logBackColor, config.logForeColor, config.logLevel);
multilang.Load();
client.OnEvent += new EventHandler(OnEvent); //Set OnEvent function
Console.Title = "Galactic Colors Control Client"; //Start display
Console.Write(">");
Common.ConsoleWrite("Galactic Colors Control Client", ConsoleColor.Red);
Common.ConsoleWrite("Console " + Assembly.GetEntryAssembly().GetName().Version.ToString(), ConsoleColor.Yellow);
if (args.Length > 0)
{
switch (args[0])
{
case "--debug":
_debug = true;
logger.Write("CLIENT IS IN DEBUG MODE !", Logger.logType.error, Logger.logConsole.show);
break;
case "--dev":
_dev = true;
logger.Write("CLIENT IS IN DEV MODE !", Logger.logType.error, Logger.logConsole.show);
break;
default:
Common.ConsoleWrite("Use --debug or --dev");
break;
}
}
bool hostSet = false;
while (!hostSet) //Request hostname
{
@ -78,7 +104,7 @@ namespace Galactic_Colors_Control_Console
return;
string[] req;
if (input[0] == commandChar)
if (input[0] == config.commandChar)
{
input = input.Substring(1);
req = Common.SplitArgs(input);
@ -93,7 +119,7 @@ namespace Galactic_Colors_Control_Console
private static void OnEvent(object sender, EventArgs e)
{
EventData eve = ((EventDataArgs)e).Data;
Common.ConsoleWrite(eve.ToSmallString()); //TODO add processing (common)
Common.ConsoleWrite(multilang.GetEventText(eve, config.lang));
}
}
}

View File

@ -0,0 +1,117 @@
using Galactic_Colors_Control_Common;
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace Galactic_Colors_Control_GUI
{
[XmlRoot("config")]
public class Config
{
public string logPath = AppDomain.CurrentDomain.BaseDirectory + "Logs";
public Logger.logType logLevel = Logger.logType.info;
public char commandChar = '/';
public ConsoleColor[] logForeColor = new ConsoleColor[6] { ConsoleColor.DarkGray, ConsoleColor.Gray, ConsoleColor.White, ConsoleColor.Yellow, ConsoleColor.Red, ConsoleColor.White };
public ConsoleColor[] logBackColor = new ConsoleColor[6] { ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Red };
public int lang = 0;
/// <summary>
/// Load config from xml file
/// App.config is too easy
/// </summary>
/// <returns>Loaded config</returns>
public Config Load()
{
Game.singleton.logger.Write("Loading config", Logger.logType.info);
Config config = new Config();
if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "Config.xml"))
{
if (CorrectConfig())
{
XmlSerializer xs = new XmlSerializer(typeof(Config));
using (StreamReader re = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "Config.xml"))
{
config = xs.Deserialize(re) as Config;
};
}
else
{
Game.singleton.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();
}
}
else
{
Game.singleton.logger.Write("Any config file", Logger.logType.error);
config.Save();
}
if (Program._debug) { config.logLevel = Logger.logType.debug; }
if (Program._dev) { config.logLevel = Logger.logType.dev; }
return config;
}
/// <summary>
/// Write actual config in xml file
/// </summary>
public void Save()
{
XmlSerializer xs = new XmlSerializer(typeof(Config));
if (Program._debug || Program._dev) { logLevel = Logger.logType.info; }
using (StreamWriter st = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "Config.xml"))
{
xs.Serialize(st, this);
};
if (Program._debug) { logLevel = Logger.logType.debug; }
if (Program._dev) { logLevel = Logger.logType.dev; }
}
/// <summary>
/// Check config format using Schema
/// </summary>
public bool CorrectConfig()
{
bool isCorrect = false;
using (Stream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "Config.xml", FileMode.Open))
{
XmlReader re = new XmlTextReader(fs);
XmlSerializer xs = new XmlSerializer(typeof(Config));
try
{
isCorrect = xs.CanDeserialize(re);
}
catch (XmlException e)
{
isCorrect = false;
Game.singleton.logger.Write("Error: " + e.Message, Logger.logType.error);
}
}
if (isCorrect)
{
try
{
XmlDocument d = new XmlDocument();
d.Load(AppDomain.CurrentDomain.BaseDirectory + "Config.xml");
d.Schemas.Add("", XmlReader.Create("ConfigSchema.xsd"));
d.Validate((o, e) =>
{
Game.singleton.logger.Write("Error: " + e.Message, Logger.logType.error);
isCorrect = false;
});
}
catch (XmlException e)
{
isCorrect = false;
Game.singleton.logger.Write("Error: " + e.Message, Logger.logType.error);
}
}
return isCorrect;
}
}
}

View File

@ -45,6 +45,7 @@
<Link>Properties\AssemblyInfoCommon.cs</Link>
</Compile>
<Compile Include="Background.cs" />
<Compile Include="Config.cs" />
<Compile Include="Game.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />

View File

@ -1,4 +1,5 @@
using Galactic_Colors_Control;
using Galactic_Colors_Control_Common;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
@ -7,8 +8,6 @@ using Microsoft.Xna.Framework.Input;
using MyMonoGame.GUI;
using System;
using System.IO;
using System.Reflection;
using System.Threading;
namespace Galactic_Colors_Control_GUI
{
@ -33,6 +32,9 @@ namespace Galactic_Colors_Control_GUI
public boxSprites[] buttonsSprites = new boxSprites[1];
public Background background;
public MultiLang multilang = new MultiLang();
public Config config = new Config();
public Logger logger = new Logger();
public Client client; //Client Core
public Manager GUI = new Manager(); //MyMonogameGUI
@ -72,6 +74,11 @@ namespace Galactic_Colors_Control_GUI
/// </summary>
protected override void Initialize()
{
config = config.Load();
logger.Initialise(config.logPath, config.logBackColor, config.logForeColor, config.logLevel);
multilang.Load();
if (Program._debug) { logger.Write("CLIENT IS IN DEBUG MODE !", Logger.logType.error, Logger.logConsole.show); }
if (Program._dev) { logger.Write("CLIENT IS IN DEV MODE !", Logger.logType.error, Logger.logConsole.show); }
nullSprite = new Texture2D(GraphicsDevice, 1, 1);
nullSprite.SetData(new Color[1 * 1] { Color.White });

View File

@ -1,4 +1,5 @@
using System;
using Galactic_Colors_Control_Common;
using System;
namespace Galactic_Colors_Control_GUI
{
@ -7,13 +8,31 @@ namespace Galactic_Colors_Control_GUI
/// </summary>
public static class Program
{
public static bool _dev = false;
public static bool _debug = false;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
private static void Main()
private static void Main(string[] args)
{
//TODO add debug and more
if (args.Length > 0)
{
switch (args[0])
{
case "--debug":
_debug = true;
break;
case "--dev":
_dev = true;
break;
default:
Common.ConsoleWrite("Use --debug or --dev");
break;
}
}
using (var game = new Game())
game.Run();
}

View File

@ -53,50 +53,57 @@ 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], "Ok", Game.singleton.fonts.basic)) { Game.singleton.GUI.ResetFocus(); showOKMessage = false; Game.singleton.client.ExitHost(); Game.singleton.gameState = new MainMenuState(); }
if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 140, Game.singleton.ScreenHeight / 4 + 150, 280, 40), Game.singleton.buttonsSprites[0], "Ok", Game.singleton.fonts.basic)) { Game.singleton.GUI.ResetFocus(); showOKMessage = false; Game.singleton.client.ExitHost(); }
}
}
}
public override void Update()
{
if (Keyboard.GetState().IsKeyDown(Keys.Escape)) { Game.singleton.GUI.ResetFocus(); Game.singleton.client.ExitHost(); Game.singleton.gameState = new MainMenuState(); }
if (Keyboard.GetState().IsKeyDown(Keys.Escape) || (!Game.singleton.client.isRunning)) { Game.singleton.GUI.ResetFocus(); Game.singleton.client.ExitHost(); }
}
private void ChatEnter()
{
string request = chatInput;
chatInput = null;
ResultData res = Game.singleton.client.Request(new string[2] { "say", request });
if(res.type != ResultTypes.OK)
if (request == null)
return;
if (request.Length == 0)
return;
ResultData res;
if (request[0] == Game.singleton.config.commandChar)
{
//TODO Mutlilang
ChatText("Error :" + Common.ArrayToString(res.result));
request = request.Substring(1);
res = Game.singleton.client.Request(Common.SplitArgs(request));
ChatText(res.ToSmallString()); //TODO multilang
}
else
{
res = Game.singleton.client.Request(Common.Strings("say", request));
if (res.type != ResultTypes.OK)
{
//TODO Mutlilang
ChatText("Error :" + Common.ArrayToString(res.result));
}
}
}
private void OnEvent(object sender, EventArgs e)
{
//TODO add PartyKick
EventData eve = ((EventDataArgs)e).Data;
switch (eve.type)
if (eve.type == EventTypes.ServerKick)
{
case EventTypes.ChatMessage:
ChatText(Common.ArrayToString(eve.data));
break;
case EventTypes.ServerJoin:
ChatText(Common.ArrayToString(eve.data) + "join the server");
break;
case EventTypes.ServerLeave:
ChatText(Common.ArrayToString(eve.data) + "leave the server");
break;
case EventTypes.ServerKick:
message.title = "Kick from server";
message.text = Common.ArrayToString(eve.data);
showOKMessage = true;
break;
message.title = "Kick from server";
message.text = Common.ArrayToString(eve.data);
showOKMessage = true;
}else
{
ChatText(Game.singleton.multilang.GetEventText(eve, Game.singleton.config.lang));
}
}

View File

@ -27,11 +27,11 @@ namespace Galactic_Colors_Control_Server.Commands
if (target == null)
return new RequestResult(ResultTypes.Error, Common.Strings("Can't find"));
Logger.Write(args[2] + " was kick by server.", Logger.logType.info, Logger.logConsole.show);
Program.logger.Write(args[2] + " was kick by server.", Logger.logType.info, Logger.logConsole.show);
if (args.Length > 2)
{
Utilities.Send(target, new EventData(EventTypes.ServerKick, Common.Strings(args[3])));
Logger.Write("because" + args[3], Logger.logType.debug);
Program.logger.Write("because" + args[3], Logger.logType.debug);
}
else
{

View File

@ -26,7 +26,7 @@ namespace Galactic_Colors_Control_Server.Commands
if (args[1].Length < 3)
return new RequestResult(ResultTypes.Error, Common.Strings("Too Short"));
Logger.Write("Identifiaction request from " + Utilities.GetName(soc), Logger.logType.debug);
Program.logger.Write("Identifiaction request from " + Utilities.GetName(soc), Logger.logType.debug);
bool allreadyconnected = false;
args[1] = args[1][0].ToString().ToUpper()[0] + args[1].Substring(1);
foreach (Client client in Program.clients.Values)
@ -39,7 +39,7 @@ namespace Galactic_Colors_Control_Server.Commands
Program.clients[soc].status = 0;
Program.clients[soc].pseudo = args[1];
Utilities.Broadcast(new EventData(EventTypes.ServerJoin, Common.Strings(args[1])));
Logger.Write("Identified as " + Utilities.GetName(soc) + " form " + ((IPEndPoint)soc.LocalEndPoint).Address.ToString(), Logger.logType.info);
Program.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

@ -20,13 +20,13 @@ namespace Galactic_Colors_Control_Server.Commands
public RequestResult Execute(string[] args, Socket soc, bool server = false)
{
soc.Shutdown(SocketShutdown.Both);
Logger.Write("Client disconnected from " + Utilities.GetName(soc), Logger.logType.info);
Program.logger.Write("Client disconnected from " + Utilities.GetName(soc), Logger.logType.info);
string username = Utilities.GetName(soc);
bool connected = Program.clients[soc].status != -1;
soc.Close();
Program.clients.Remove(soc);
if (connected) { Utilities.Broadcast(new EventData(EventTypes.ServerLeave, Common.Strings(username))); }
Logger.Write("Size: " + Program.clients.Count + "/" + Program.config.size, Logger.logType.debug);
Program.logger.Write("Size: " + Program.clients.Count + "/" + Program.config.size, Logger.logType.debug);
return new RequestResult(ResultTypes.OK);
}
}

View File

@ -22,6 +22,7 @@ namespace Galactic_Colors_Control_Server.Commands
{
if (Enum.TryParse(args[1], true, out Program.config.logLevel))
{
Program.logger.ChangeLevel(Program.config.logLevel);
return new RequestResult(ResultTypes.OK, Common.Strings(Program.config.logLevel.ToString()));
}
else

View File

@ -26,7 +26,7 @@ namespace Galactic_Colors_Control_Server.Commands
foreach (ICommand com in coms)
{
commands.Add(com);
Logger.Write("Added command " + com.Group.ToString() + " " + com.Name, Logger.logType.debug);
Program.logger.Write("Added command " + com.Group.ToString() + " " + com.Name, Logger.logType.debug);
}
}
@ -60,7 +60,7 @@ namespace Galactic_Colors_Control_Server.Commands
}
catch (Exception e)
{
Logger.Write("Command " + args[0] + " Exception : " + e.Message, Logger.logType.error);
Program.logger.Write("Command " + args[0] + " Exception : " + e.Message, Logger.logType.error);
return new RequestResult(ResultTypes.Error, Common.Strings("Execute Exception"));
}
}

View File

@ -33,7 +33,7 @@ namespace Galactic_Colors_Control_Server.Commands
return new RequestResult(ResultTypes.Error, Common.Strings("Too Big"));
Program.AddParty(new Party(args[2], size, Utilities.GetName(soc)));
Logger.Write("Party " + args[2] + " create with " + size + " slots as " + Program.GetPartyID(false), Logger.logType.info);
Program.logger.Write("Party " + args[2] + " create with " + size + " slots as " + Program.GetPartyID(false), Logger.logType.info);
if (server)
{
Program.selectedParty = Program.GetPartyID(false);

View File

@ -27,7 +27,7 @@ namespace Galactic_Colors_Control_Server.Commands
{
Manager.Execute(new string[4] { "party", "kick", Utilities.GetName(client), "stop_party" }, soc, server);
}
Logger.Write("Party " + Program.parties[partyId].name + " closed", Logger.logType.info, server ? Logger.logConsole.show : Logger.logConsole.normal);
Program.logger.Write("Party " + Program.parties[partyId].name + " closed", Logger.logType.info, server ? Logger.logConsole.show : Logger.logConsole.normal);
if (Program.selectedParty == partyId) { Program.selectedParty = -1; }
Program.parties.Remove(partyId);
return new RequestResult(ResultTypes.OK);

View File

@ -23,7 +23,7 @@ namespace Galactic_Colors_Control_Server.Commands
return new RequestResult(ResultTypes.Error, Common.Strings("Allready"));
Program._open = false;
Logger.Write("Server closed", Logger.logType.warm, Logger.logConsole.show);
Program.logger.Write("Server closed", Logger.logType.warm, Logger.logConsole.show);
return new RequestResult(ResultTypes.OK);
}
}

View File

@ -23,7 +23,7 @@ namespace Galactic_Colors_Control_Server.Commands
return new RequestResult(ResultTypes.Error, Common.Strings("Allready"));
Program._open = true;
Logger.Write("Server opened", Logger.logType.warm, Logger.logConsole.show);
Program.logger.Write("Server opened", Logger.logType.warm, Logger.logConsole.show);
return new RequestResult(ResultTypes.OK);
}
}

View File

@ -1,4 +1,5 @@
using System;
using Galactic_Colors_Control_Common;
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
@ -14,6 +15,7 @@ namespace Galactic_Colors_Control_Server
public int size = 20;
public ConsoleColor[] logForeColor = new ConsoleColor[6] { ConsoleColor.DarkGray, ConsoleColor.Gray, ConsoleColor.White, ConsoleColor.Yellow, ConsoleColor.Red, ConsoleColor.White };
public ConsoleColor[] logBackColor = new ConsoleColor[6] { ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Red };
public int lang = 0;
/// <summary>
/// Load config from xml file
@ -22,7 +24,7 @@ namespace Galactic_Colors_Control_Server
/// <returns>Loaded config</returns>
public Config Load()
{
Logger.Write("Loading config", Logger.logType.info);
Program.logger.Write("Loading config", Logger.logType.info);
Config config = new Config();
if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "Config.xml"))
{
@ -36,7 +38,7 @@ namespace Galactic_Colors_Control_Server
}
else
{
Logger.Write("Old config in Config.xml.old", Logger.logType.warm);
Program.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();
@ -44,7 +46,7 @@ namespace Galactic_Colors_Control_Server
}
else
{
Logger.Write("Any config file", Logger.logType.error);
Program.logger.Write("Any config file", Logger.logType.error);
config.Save();
}
if (Program._debug) { config.logLevel = Logger.logType.debug; }
@ -85,7 +87,7 @@ namespace Galactic_Colors_Control_Server
catch (XmlException e)
{
isCorrect = false;
Logger.Write("Error: " + e.Message, Logger.logType.error);
Program.logger.Write("Error: " + e.Message, Logger.logType.error);
}
}
@ -99,14 +101,14 @@ namespace Galactic_Colors_Control_Server
d.Validate((o, e) =>
{
Logger.Write("Error: " + e.Message, Logger.logType.error);
Program.logger.Write("Error: " + e.Message, Logger.logType.error);
isCorrect = false;
});
}
catch (XmlException e)
{
isCorrect = false;
Logger.Write("Error: " + e.Message, Logger.logType.error);
Program.logger.Write("Error: " + e.Message, Logger.logType.error);
}
}

View File

@ -88,7 +88,6 @@
<Compile Include="Commands\Server\ServerStatusCommand.cs" />
<Compile Include="Commands\TimeCommand.cs" />
<Compile Include="Config.cs" />
<Compile Include="Logger.cs" />
<Compile Include="Party.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />

View File

@ -29,7 +29,9 @@ namespace Galactic_Colors_Control_Server
public static Dictionary<int, Party> parties { get; private set; } = new Dictionary<int, Party>();
public static int selectedParty = -1;
//TODO add multilang
public static Config config = new Config();
public static Logger logger = new Logger();
public static Thread CheckConnected = new Thread(CheckConnectedLoop);
/// <summary>
@ -38,19 +40,19 @@ namespace Galactic_Colors_Control_Server
private static void Main(string[] args)
{
Console.Title = "Galactic Colors Control Server";
Logger.Write("Galactic Colors Control Server " + Assembly.GetEntryAssembly().GetName().Version.ToString(), Logger.logType.fatal);
logger.Write("Galactic Colors Control Server " + Assembly.GetEntryAssembly().GetName().Version.ToString(), Logger.logType.fatal);
if (args.Length > 0)
{
switch (args[0])
{
case "--debug":
_debug = true;
Logger.Write("SERVER IS IN DEBUG MODE !", Logger.logType.error, Logger.logConsole.show);
logger.Write("SERVER IS IN DEBUG MODE !", Logger.logType.error, Logger.logConsole.show);
break;
case "--dev":
_dev = true;
Logger.Write("SERVER IS IN DEV MODE !", Logger.logType.error, Logger.logConsole.show);
logger.Write("SERVER IS IN DEV MODE !", Logger.logType.error, Logger.logConsole.show);
break;
default:
@ -58,7 +60,7 @@ namespace Galactic_Colors_Control_Server
break;
}
}
if (Type.GetType("Mono.Runtime") != null) { Logger.Write("Using Mono", Logger.logType.warm); }
if (Type.GetType("Mono.Runtime") != null) { logger.Write("Using Mono", Logger.logType.warm, Logger.logConsole.show); }
Console.Write(">");
SetupServer();
ConsoleLoop();
@ -71,15 +73,15 @@ namespace Galactic_Colors_Control_Server
private static void SetupServer()
{
config = config.Load();
Logger.Initialise();
logger.Initialise(config.logPath, config.logBackColor, config.logForeColor, config.logLevel);
Commands.Manager.Load();
Logger.Write("Setting up server on *:" + config.port, Logger.logType.warm);
Logger.Write("Size:" + config.size, Logger.logType.debug);
logger.Write("Setting up server on *:" + config.port, Logger.logType.warm);
logger.Write("Size:" + config.size, Logger.logType.debug);
serverSocket.Bind(new IPEndPoint(IPAddress.Any, config.port));
serverSocket.Listen(0);
serverSocket.BeginAccept(AcceptCallback, null);
CheckConnected.Start();
Logger.Write("Server setup complete", Logger.logType.info);
logger.Write("Server setup complete", Logger.logType.info);
}
/// <summary>
@ -102,19 +104,18 @@ namespace Galactic_Colors_Control_Server
/// </summary>
private static void CloseAllSockets()
{
Logger.Write("Stoping server", Logger.logType.warm, Logger.logConsole.show);
logger.Write("Stoping server", Logger.logType.warm, Logger.logConsole.show);
Utilities.Broadcast(new EventData(EventTypes.ServerKick, Common.Strings("Close")));
config.Save();
foreach (Socket socket in clients.Keys)
{
socket.Shutdown(SocketShutdown.Both);
Logger.Write("Shutdown " + Utilities.GetName(socket), Logger.logType.debug);
logger.Write("Shutdown " + Utilities.GetName(socket), Logger.logType.debug);
}
serverSocket.Close();
CheckConnected.Join(2000);
Logger.Write("Server stoped", Logger.logType.info);
Logger._run = false;
Logger.Updater.Join();
logger.Write("Server stoped", Logger.logType.info);
logger.Join();
}
/// <summary>
@ -139,14 +140,14 @@ namespace Galactic_Colors_Control_Server
}
else
{
Logger.Write("Client can't join from " + ((IPEndPoint)socket.LocalEndPoint).Address.ToString() + " no more space", Logger.logType.warm);
logger.Write("Client can't join from " + ((IPEndPoint)socket.LocalEndPoint).Address.ToString() + " no more space", Logger.logType.warm);
Utilities.Send(socket, new EventData(EventTypes.ServerKick, Common.Strings("Space")));
socket.Close();
}
}
else
{
Logger.Write("Client can't join from " + ((IPEndPoint)socket.LocalEndPoint).Address.ToString() + " server closed", Logger.logType.info);
logger.Write("Client can't join from " + ((IPEndPoint)socket.LocalEndPoint).Address.ToString() + " server closed", Logger.logType.info);
Utilities.Send(socket, new EventData(EventTypes.ServerKick, Common.Strings("Close")));
socket.Close();
}
@ -161,11 +162,11 @@ namespace Galactic_Colors_Control_Server
Client client = new Client();
clients.Add(socket, client);
socket.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, socket);
Logger.Write("Client connection from " + Utilities.GetName(socket), Logger.logType.info);
Logger.Write("Size: " + clients.Count + "/" + config.size, Logger.logType.dev);
logger.Write("Client connection from " + Utilities.GetName(socket), Logger.logType.info);
logger.Write("Size: " + clients.Count + "/" + config.size, Logger.logType.dev);
if (clients.Count >= config.size)
{
Logger.Write("Server full", Logger.logType.warm, Logger.logConsole.show);
logger.Write("Server full", Logger.logType.warm, Logger.logConsole.show);
}
}
@ -183,10 +184,10 @@ namespace Galactic_Colors_Control_Server
}
catch (SocketException)
{
Logger.Write("Client forcefully disconnected from " + Utilities.GetName(current) + " : SocketException", Logger.logType.info);
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);
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))); }
@ -207,13 +208,13 @@ namespace Galactic_Colors_Control_Server
break;
default:
Logger.Write("Wrong packet from " + Utilities.GetName(current), Logger.logType.error);
logger.Write("Wrong packet from " + Utilities.GetName(current), Logger.logType.error);
break;
}
}
else
{
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); }
@ -228,9 +229,9 @@ 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);
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);
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))); }

View File

@ -20,7 +20,7 @@ namespace Galactic_Colors_Control_Server
if (Program.clients.ContainsKey(soc))
return Program.clients[soc].status != -1;
Logger.Write("IsConnect : Unknown client", Logger.logType.error);
Program.logger.Write("IsConnect : Unknown client", Logger.logType.error);
return false;
}
@ -64,12 +64,12 @@ namespace Galactic_Colors_Control_Server
soc.Send(packet.ToBytes());
if (Program.config.logLevel == Logger.logType.dev)
{
Logger.Write("Send to " + GetName(soc) + " : " + packet.ToLongString(), Logger.logType.dev);
Program.logger.Write("Send to " + GetName(soc) + " : " + packet.ToLongString(), Logger.logType.dev);
}
}
catch (Exception e)
{
Logger.Write("Send exception to " + GetName(soc) + " : " + e.Message, Logger.logType.error);
Program.logger.Write("Send exception to " + GetName(soc) + " : " + e.Message, Logger.logType.error);
}
}
}

View File

@ -165,7 +165,26 @@ namespace Galactic_Colors_Control
/// <returns>ResultData or Timeout</returns>
public ResultData Request(string[] args)
{
// TODO filter Client Side Requests
switch(args[0])
{
case "exit":
ExitHost();
return new ResultData(GetRequestId(), ResultTypes.OK);
case "ping":
return PingHost();
default:
return Execute(args);
}
}
/// <summary>
/// Send row command to server
/// </summary>
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"));
@ -190,16 +209,16 @@ namespace Galactic_Colors_Control
/// Ping Current Server IP
/// </summary>
/// <returns>Time in ms or 'Timeout'</returns>
private string PingHost()
private ResultData PingHost()
{
Ping ping = new Ping();
PingReply reply;
reply = ping.Send(IP);
if (reply.Status == IPStatus.Success)
return reply.RoundtripTime.ToString();
return new ResultData(GetRequestId(), ResultTypes.OK, Common.SplitArgs(reply.RoundtripTime.ToString() + "ms"));
return "Timeout";
return new ResultData(GetRequestId(), ResultTypes.Error, Common.SplitArgs("Timeout"));
}
/// <summary>