1
0
Fork 0

Merged Dev into master

This commit is contained in:
sheychen 2016-11-17 14:18:03 +01:00
commit 6dfb34d4e0
92 changed files with 4468 additions and 1643 deletions

21
AssemblyInfoCommon.cs Normal file
View File

@ -0,0 +1,21 @@
using System.Reflection;
//Common AssemblyInfo
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
[assembly: AssemblyCompany("sheychen")]
[assembly: AssemblyCopyright("Copyright © 2016")]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
// en utilisant '*', comme indiqué ci-dessous :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.1")]
[assembly: AssemblyFileVersion("1.1.0.1")]

View File

@ -0,0 +1,131 @@
using System;
using System.Linq;
using System.Text;
namespace Galactic_Colors_Control_Common
{
/// <summary>
/// All used types - byte[] convertions
/// </summary>
public static class Binary
{
public static bool ToBool(ref byte[] bytes)
{
byte[] data = new byte[1];
data = bytes.Take(1).ToArray();
RemoveFirst(ref bytes, 1);
return data[1] == 1 ? true : false;
}
///<remarks>1 byte</remarks>
public static byte[] FromBool(bool x)
{
return x ? new byte[1] { 1 } : new byte[1] { 0 };
}
public static string ToString(ref byte[] bytes)
{
int len = ToInt(ref bytes);
string text = Encoding.ASCII.GetString(bytes.Take(len).ToArray());
RemoveFirst(ref bytes, len);
return text;
}
///<remarks>len(in bytes) + string</remarks>
public static byte[] FromString(string text)
{
byte[] data = Encoding.ASCII.GetBytes(text);
return AddBytes(FromInt(data.Length), data);
}
public static int ToInt(ref byte[] bytes)
{
if (bytes == null)
return -1;
if (bytes.Length < 4)
return -1;
byte[] data = new byte[4];
data = bytes.Take(4).ToArray();
data.Reverse();
RemoveFirst(ref bytes, 4);
return BitConverter.ToInt32(data, 0);
}
///<remarks>4 bytes</remarks>
public static byte[] FromInt(int x)
{
byte[] data = new byte[4];
data = BitConverter.GetBytes(x);
return data;
}
public static string[] ToStringArray(ref byte[] bytes)
{
int len = ToInt(ref bytes);
if (len < 1 || len > 10000)
return new string[0];
string[] data = new string[len];
for (int i = 0; i < len; i++)
{
data[i] = ToString(ref bytes);
}
return data;
}
public static byte[] FromStringArray(string[] array)
{
if (array == null)
return new byte[0];
byte[] data = FromInt(array.Length);
for (int i = 0; i < array.Length; i++)
{
data = AddBytes(data, FromString(array[i]));
}
return data;
}
public static int[] ToIntArray(ref byte[] bytes)
{
int len = ToInt(ref bytes);
int[] data = new int[len];
for (int i = 0; i < len; i++)
{
data[i] = ToInt(ref bytes);
}
return data;
}
public static byte[] FromIntArray(int[] array)
{
byte[] data = FromInt(array.Length);
for (int i = 0; i < array.Length; i++)
{
data = AddBytes(data, FromInt(array[i]));
}
return data;
}
public static byte[] AddBytes(params byte[][] arguments)
{
byte[] res = new byte[arguments.Sum(a => a.Length)];
int offset = 0;
for (int i = 0; i < arguments.Length; i++)
{
Buffer.BlockCopy(arguments[i], 0, res, offset, arguments[i].Length);
offset += arguments[i].Length;
}
return res;
}
public static void RemoveFirst(ref byte[] bytes, int count)
{
byte[] newbytes = new byte[bytes.Length - count];
newbytes = bytes.Skip(count).ToArray();
bytes = newbytes;
}
}
}

View File

@ -0,0 +1,74 @@
using System;
using System.Linq;
namespace Galactic_Colors_Control_Common
{
public static class Common
{
/// <summary>
/// Write line in console with correct colors
/// </summary>
/// <param name="v">Text to write</param>
/// <param name="Fore">Foreground color</param>
/// <param name="Back">Background color</param>
public static void ConsoleWrite(string v, ConsoleColor Fore = ConsoleColor.White, ConsoleColor Back = ConsoleColor.Black)
{
Console.Write("\b");
Console.ForegroundColor = Fore;
Console.BackgroundColor = Back;
Console.WriteLine(v);
ConsoleResetColor();
Console.Write(">");
}
/// <summary>
/// Reset Console Colors
/// For non black background console as Ubuntu
/// </summary>
public static void ConsoleResetColor()
{
Console.ResetColor();
Console.BackgroundColor = ConsoleColor.Black;
}
/// <summary>
/// Simpler string array creation
/// </summary>
public static string[] Strings(params string[] args)
{
return args;
}
public static string ArrayToString(string[] array)
{
string text = "";
if (array != null)
{
foreach (string str in array)
{
text += ((text == "" ? "" : Environment.NewLine) + str);
}
}
return text;
}
public static string ArrayToString(int[] array)
{
string text = "";
foreach (int i in array)
{
text += ((text == "" ? "" : Environment.NewLine) + i.ToString());
}
return text;
}
public static string[] SplitArgs(string text)
{
return text.Split('"')
.Select((element, index) => index % 2 == 0
? element.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
: new string[] { element })
.SelectMany(element => element).ToArray();
}
}
}

View File

@ -0,0 +1,84 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{022A69CE-22B5-4934-BE9F-A9C6DF9557ED}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Galactic_Colors_Control_Common</RootNamespace>
<AssemblyName>Galactic Colors Control Common</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<StartupObject />
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\AssemblyInfoCommon.cs">
<Link>Properties\AssemblyInfoCommon.cs</Link>
</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" />
<Compile Include="Protocol\RequestData.cs" />
<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.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,176 @@
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_Common
{
public class Logger
{
public enum logType { dev, debug, info, warm, error, fatal }
public enum logConsole { normal, show, hide }
public struct Log
{
public string text;
public logType type;
public logConsole console;
public Log(string p1, logType p2, logConsole p3 = logConsole.normal)
{
text = p1;
type = p2;
console = p3;
}
}
private List<Log> toWriteLogs = new List<Log>();
private string logPath;
private ConsoleColor[] logBackColor;
private ConsoleColor[] logForeColor;
private Thread Updater;
private logType logLevel = logType.info;
private bool _run = true;
public bool run { get { return _run; } }
private static bool _debug = false;
private static bool _dev = false;
/// <summary>
/// Create log file and start logger thread
/// </summary>
/// <param name="LogPath">Absolute path to logs directory</param>
public void Initialise(string LogPath, ConsoleColor[] backColor, ConsoleColor[] foreColor, logType LogLevel, bool debug, bool dev)
{
logPath = LogPath;
logBackColor = backColor;
logForeColor = foreColor;
logLevel = LogLevel;
_debug = debug;
_dev = dev;
if (!Directory.Exists(logPath))
{
Directory.CreateDirectory(logPath);
Write("Log Directory Created", logType.info);
}
else
{
//Sort old logs
string[] files = Directory.GetFiles(logPath);
foreach (string file in files)
{
if (Path.GetExtension(file) == ".log")
{
string name = Path.GetFileName(file);
name = name.Substring(0, Math.Min(name.Length, 10));
if (name.Length == 10)
{
if (name != DateTime.UtcNow.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))
{
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))
{
Directory.CreateDirectory(logPath + "/" + y + "/" + m + "/" + d);
}
File.Move(file, logPath + "/" + y + "/" + m + "/" + d + "/" + Path.GetFileName(file));
}
}
}
}
}
}
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";
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 void Write(string text, logType type, logConsole console = logConsole.normal)
{
Write(new Log(text, type, console));
}
/// <summary>
/// Add log to log pile
/// </summary>
/// <param name="log">Log struct</param>
private void Write(Log log)
{
if (_debug || _dev)
{
//Add Source Method
log.text = "[" + new StackTrace().GetFrame(2).GetMethod().Name + "]: " + log.text;
}
toWriteLogs.Add(log);
}
/// <summary>
/// Write log pile to logfile and console
/// </summary>
public void UpdaterLoop()
{
while (_run || toWriteLogs.Count > 0)
{
while (toWriteLogs.Count > 0)
{
Log log = toWriteLogs[0];
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)
{
ConsoleWrite(log);
}
}
else
{
if (log.console == logConsole.show)
{
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,82 @@
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 GetResultText(ResultData res, int lang)
{
string data = Common.ArrayToString(res.result);
if (res.type == ResultTypes.Error)
data = Get("Error", lang) + ": " + data;
return data;
}
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,20 @@
using System.Reflection;
using System.Runtime.InteropServices;
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
[assembly: AssemblyTitle("Galactic Colors Control Common")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Galactic Colors Control Common")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)]
// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM
[assembly: Guid("022a69ce-22b5-4934-be9f-a9c6df9557ed")]

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,56 @@
namespace Galactic_Colors_Control_Common.Protocol
{
/// <summary>
/// Packet Master Class
/// </summary>
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))
{
case DataType.Request:
return new RequestData(ref bytes);
case DataType.Result:
return new ResultData(ref bytes);
case DataType.Event:
return new EventData(ref bytes);
default:
return null;
}
}
/// <summary>
/// Small readable text
/// </summary>
public virtual string ToSmallString()
{
return null;
}
/// <summary>
/// Long readble text
/// </summary>
public virtual string ToLongString()
{
return null;
}
/// <summary>
/// Generate bytes to send
/// </summary>
public virtual byte[] ToBytes()
{
return new byte[0];
}
}
}

View File

@ -0,0 +1,49 @@
namespace Galactic_Colors_Control_Common.Protocol
{
public enum EventTypes
{
ChatMessage, //To displat in chatbox
ServerJoin, //A player join server
ServerLeave, //A player leave server
ServerKick, //You are kick from server
PartyJoin, //A player join your party
PartyLeave, //A player leave your party
PartyKick //Tou are jick from your party
}
/// <summary>
/// Server to Client Packet
/// </summary>
public class EventData : Data
{
public EventTypes type;
public string[] data; //EventArgs like
public EventData(EventTypes Type, string[] Data = null)
{
type = Type;
data = Data;
}
public EventData(ref byte[] bytes)
{
type = (EventTypes)Binary.ToInt(ref bytes);
data = Binary.ToStringArray(ref bytes);
}
public override byte[] ToBytes()
{
return Binary.AddBytes(Binary.FromInt((int)DataType.Event), Binary.FromInt((int)type), Binary.FromStringArray(data));
}
public override string ToSmallString()
{
return type.ToString() + "|" + Common.ArrayToString(data);
}
public override string ToLongString()
{
return "Event : " + ToSmallString();
}
}
}

View File

@ -0,0 +1,23 @@
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
/// for OnEvent Handler
/// </summary>
public class EventDataArgs : EventArgs
{
private EventData m_Data;
public EventDataArgs(EventData _myData)
{
m_Data = _myData;
}
public EventData Data { get { return m_Data; } }
}
}

View File

@ -0,0 +1,38 @@
namespace Galactic_Colors_Control_Common.Protocol
{
/// <summary>
/// Client to Server Data request packet 'allways' return ResultData
/// </summary>
public class RequestData : Data
{
public int id; //Client Size autoindent id
public string[] args;
public RequestData(int Id, string[] Args)
{
id = Id;
args = Args;
}
public RequestData(ref byte[] bytes)
{
id = Binary.ToInt(ref bytes);
args = Binary.ToStringArray(ref bytes);
}
public override byte[] ToBytes()
{
return Binary.AddBytes(Binary.FromInt((int)DataType.Request), Binary.FromInt(id), Binary.FromStringArray(args));
}
public override string ToSmallString()
{
return Common.ArrayToString(args);
}
public override string ToLongString()
{
return "Request : " + Common.ArrayToString(args) + "|" + id;
}
}
}

View File

@ -0,0 +1,18 @@
namespace Galactic_Colors_Control_Common.Protocol
{
/// <summary>
/// Part of RequestData
/// Commands return
/// </summary>
public class RequestResult
{
public ResultTypes type;
public string[] result;
public RequestResult(ResultTypes p1, string[] p2 = null)
{
type = p1;
result = p2;
}
}
}

View File

@ -0,0 +1,50 @@
namespace Galactic_Colors_Control_Common.Protocol
{
public enum ResultTypes { Error, OK }
/// <summary>
/// Server to Client Result from RequestData
/// </summary>
public class ResultData : Data
{
public int id; //Client Side Autoindent
public ResultTypes type;
public string[] result;
public ResultData(int Id, ResultTypes Type, string[] Result = null)
{
id = Id;
type = Type;
result = Result;
}
public ResultData(int Id, RequestResult Result)
{
id = Id;
type = Result.type;
result = Result.result;
}
public ResultData(ref byte[] bytes)
{
id = Binary.ToInt(ref bytes);
type = (ResultTypes)Binary.ToInt(ref bytes);
result = Binary.ToStringArray(ref bytes);
}
public override byte[] ToBytes()
{
return Binary.AddBytes(Binary.FromInt((int)DataType.Result), Binary.FromInt(id), Binary.FromInt((int)type), Binary.FromStringArray(result));
}
public override string ToSmallString()
{
return type.ToString() + "|" + Common.ArrayToString(result);
}
public override string ToLongString()
{
return "Result : " + type.ToString() + "|" + Common.ArrayToString(result) + "|" + id;
}
}
}

View File

@ -0,0 +1,52 @@
Key;Francais;English
GCC;Galactic Colors Control;Galactic Colors Control
Client;Client;Client
Server;Serveur;Server
Console;Console;Console
Loading;Chargement;Loading
OK;OK;OK
Yes;Oui;Yes
No;Non;No
EnterHostname;Saisir l'addresse;Enter hostname
EnterMessage;Saisir un message;Enter message
Connect;Connexion;Connect
Back;Retour;Back
Username;Pseudo;Username
Validate;Valider;Validate
GUI;GUI;GUI
Play;Jouer;Play
Options;Options;Options
Exit;Quitter;Exit
Error;Erreur;Error
Hide;Cacher;Hide
Show;Afficher;Show
Chat;Chat;Chat
Party;Partie;Party
Join;Rejoindre;Join
Use;Utiliser;Use
CantConnect;Connexion impossible. Au revoir;Can't connect sorry. Bye
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
ServerKick;Exclus du serveur;Kick from server
TooShort;Trop court;Too short
TooLong;Trop long;Too long
Update;Actualiser;Update
AnyParty;Aucune partie;Any party
Password;Mot de passe;Password
ClientSide;Cote client;Client side
CantFind:Introuvable;Can't find
Connected:Connecte;Connected
AllreadyTaken;Deja pris;Allready taken
AnyCommand;Aucune commande;Any command
IncorrectArgs;Arguements incorrects;Incorrect Arguements
ExecuteException;Exception d'execution;Execute exception
Access;Acces refuse;Access denied
Allready;Deja fait;Allready do
Format;Format incorrect;Incorrect format
Full;Plein;Full
Close;Fermee;Close
Owner;Proprietaire;Owner
AnyMessage;Aucun message;Any message
MustBeConnected;Doit etre connecte;Must be connected
Can't render this file because it has a wrong number of fields in line 39.

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 = 1;
/// <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

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xs="http://www.w3.org/2001/XMLSchema" attributeFormDefault="unqualified" elementFormDefault="qualified">
<xsd:element name="config">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="logPath" type="xsd:string" />
<xsd:element name="logLevel" type="xsd:string" />
<xsd:element name="commandChar" type="xsd:unsignedByte" />
<xsd:element name="logForeColor">
<xsd:complexType>
<xsd:sequence>
<xsd:element maxOccurs="unbounded" name="ConsoleColor" type="xsd:string" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="logBackColor">
<xsd:complexType>
<xsd:sequence>
<xsd:element maxOccurs="unbounded" name="ConsoleColor" type="xsd:string" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="lang" type="xsd:unsignedByte" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xs:schema>

View File

@ -44,15 +44,29 @@
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="..\AssemblyInfoCommon.cs">
<Link>Properties\AssemblyInfoCommon.cs</Link>
</Compile>
<Compile Include="Config.cs" />
<Compile Include="Program.cs" /> <Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Galactic Colors Control Common\Galactic Colors Control Common.csproj">
<Project>{022A69CE-22B5-4934-BE9F-A9C6DF9557ED}</Project>
<Name>Galactic Colors Control Common</Name>
</ProjectReference>
<ProjectReference Include="..\Galactic Colors Control\Galactic Colors Control.csproj"> <ProjectReference Include="..\Galactic Colors Control\Galactic Colors Control.csproj">
<Project>{93582ce8-c8c8-4e19-908b-d671ecbade25}</Project> <Project>{93582ce8-c8c8-4e19-908b-d671ecbade25}</Project>
<Name>Galactic Colors Control</Name> <Name>Galactic Colors Control</Name>
</ProjectReference> </ProjectReference>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Include="ConfigSchema.xsd">
<SubType>Designer</SubType>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it. <!-- 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. Other similar extension points exist, see Microsoft.Common.targets.

View File

@ -1,46 +1,78 @@
using System; using Galactic_Colors_Control;
using Galactic_Colors_Control; using Galactic_Colors_Control_Common;
using System.Threading; using Galactic_Colors_Control_Common.Protocol;
using System;
using System.Reflection; using System.Reflection;
using System.Threading;
namespace Galactic_Colors_Control_Console namespace Galactic_Colors_Control_Console
{ {
/// <summary>
/// Console Client
/// </summary>
internal class Program internal class Program
{ {
private static Client client; public static bool _debug = false;
private static bool run = true; public static bool _dev = false;
private static Thread Writer;
private static void Main() private static Client client = new Client();
private static MultiLang multilang = new 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(); Console.Title = "Galactic Colors Control Client"; //Start display
Console.Title = "Galactic Colors Control Client";
Console.Write(">"); Console.Write(">");
Write("Galactic Colors Control Client"); logger.Write(Console.Title, Logger.logType.fatal);
Write("Console " + Assembly.GetEntryAssembly().GetName().Version.ToString()); logger.Write("Console " + Assembly.GetEntryAssembly().GetName().Version.ToString(), Logger.logType.error);
bool hostSet = false; config = config.Load();
while(!hostSet) logger.Initialise(config.logPath, config.logBackColor, config.logForeColor, config.logLevel, _debug, _dev);
multilang.Load();
client.OnEvent += new EventHandler(OnEvent); //Set OnEvent function
if (args.Length > 0)
{ {
Write("Enter server host:"); switch (args[0])
string host = client.ValidateHost(Console.ReadLine());
if(host == null)
{ {
foreach (string output in client.Output.ToArray()) case "--debug":
{ _debug = true;
Write(output); logger.Write("CLIENT IS IN DEBUG MODE !", Logger.logType.error, Logger.logConsole.show);
} break;
client.Output.Clear();
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
{
Thread.Sleep(100);
Common.ConsoleWrite(multilang.Get("EnterHostname", config.lang) +":");
string host = client.ValidateHost(Console.ReadLine());
if (host[0] == '*')
{
host = host.Substring(1);
logger.Write("Validate error " + host, Logger.logType.error);
Common.ConsoleWrite(host, ConsoleColor.Red);
client.ResetHost(); client.ResetHost();
} }
else else
{ {
Write("Use " + host + "? y/n"); logger.Write("Validate " + host, Logger.logType.info);
Common.ConsoleWrite(multilang.Get("Use", config.lang) + " " + host + "? y/n");
ConsoleKeyInfo c = new ConsoleKeyInfo(); ConsoleKeyInfo c = new ConsoleKeyInfo();
while(c.Key != ConsoleKey.Y && c.Key != ConsoleKey.N) while (c.Key != ConsoleKey.Y && c.Key != ConsoleKey.N)
{ {
c = Console.ReadKey(); c = Console.ReadKey();
} }
if(c.Key == ConsoleKey.Y) if (c.Key == ConsoleKey.Y)
{ {
hostSet = true; hostSet = true;
} }
@ -50,58 +82,125 @@ namespace Galactic_Colors_Control_Console
} }
} }
} }
if (client.ConnectHost()) Common.ConsoleWrite(multilang.Get("Loading", config.lang));
if (client.ConnectHost()) //Try connection
{ {
logger.Write("Connected", Logger.logType.warm);
run = true; run = true;
Writer = new Thread(OutputWriter); bool connected = false;
Writer.Start(); //Identifaction
while (!connected)
{
Common.ConsoleWrite(multilang.Get("Username", config.lang) + ":");
string username = Console.ReadLine();
if (username.Length > 3)
{
ResultData res = client.Request(new string[2] { "connect", username });
if(res.type == ResultTypes.OK) { connected = true; logger.Write("Identification", Logger.logType.info); }
else
{
logger.Write("Identification error " + res.result, Logger.logType.info);
Common.ConsoleWrite(multilang.GetResultText(res, config.lang));
}
}
else
{
Common.ConsoleWrite(multilang.Get("TooShort", config.lang));
}
}
bool inparty = false;
while (!inparty)
{
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());
if (data.Length > 0)
{
if (data[0] == "c")
{
Common.ConsoleWrite("<party name> <player count>:");
string[] split = Common.SplitArgs(Console.ReadLine());
if (split.Length == 2)
{
ResultData createRes = client.Request(new string[4] { "party", "create", split[0], split[1] });
if (createRes.type == ResultTypes.OK) { inparty = true; }
else
{
Common.ConsoleWrite(multilang.GetResultText(createRes, config.lang));
Console.ReadLine();
}
}
else
{
Common.ConsoleWrite("Format");
}
}
else
{
int id;
if (int.TryParse(data[0], out id))
{
string[] request = data.Length == 1 ? new string[3] { "party", "join", id.ToString() } : new string[4] { "party", "join", id.ToString(), data[1] };
ResultData res = client.Request(request);
if (res.type == ResultTypes.OK) { inparty = true; }
else
{
Common.ConsoleWrite(multilang.GetResultText(res, config.lang));
}
}
else
{
Common.ConsoleWrite("Format");
}
}
}
}
logger.Write("Play", Logger.logType.info, Logger.logConsole.hide);
Common.ConsoleWrite(multilang.Get("Play", config.lang));
while (run) while (run)
{ {
client.SendRequest(Console.ReadLine()); Execute(Console.ReadLine()); //Process console input
if (!client.isRunning) { run = false; } if (!client.isRunning) { run = false; }
} }
Writer.Join();
Console.Read(); Console.Read();
} }
else else
{ {
foreach (string output in client.Output.ToArray()) logger.Write("Connection error", Logger.logType.error);
{ Common.ConsoleWrite(multilang.Get("CantConnect", config.lang), ConsoleColor.Red);
Write(output);
}
client.Output.Clear();
Console.Read();
} }
run = false;
logger.Join();
Console.ReadLine();
} }
private static void OutputWriter() private static void Execute(string input)
{ {
while (run || client.Output.Count > 0) if (input == null)
return;
if (input.Length == 0)
return;
string[] req;
if (input[0] == config.commandChar)
{ {
if (client.Output.Count > 0) input = input.Substring(1);
{ req = Common.SplitArgs(input);
string text = client.Output[0];
switch (text)
{
case "/clear":
Console.Clear();
break;
default:
Write(text);
break;
}
client.Output.Remove(text);
}
Thread.Sleep(200);
} }
else
{
req = Common.Strings("say", input);
}
Common.ConsoleWrite(multilang.GetResultText(client.Request(req),config.lang));
} }
private static void Write( string text) private static void OnEvent(object sender, EventArgs e)
{ {
Console.Write("\b"); //TODO add PartyKick
Console.WriteLine(text); EventData eve = ((EventDataArgs)e).Data;
Console.Write(">"); Common.ConsoleWrite(multilang.GetEventText(eve, config.lang));
} }
} }
} }

View File

@ -1,36 +1,20 @@
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
// Les informations générales relatives à un assembly dépendent de // Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations // l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly. // associées à un assembly.
[assembly: AssemblyTitle("Galactic Colors Control Console")] [assembly: AssemblyTitle("Galactic Colors Control Console")]
[assembly: AssemblyDescription("")] [assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")] [assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("sheychen")]
[assembly: AssemblyProduct("Galactic Colors Control Console")] [assembly: AssemblyProduct("Galactic Colors Control Console")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")] [assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")] [assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly // L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de // aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type. // COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)] [assembly: ComVisible(false)]
// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM // Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM
[assembly: Guid("5d6a09d1-dcab-4fd8-b4e6-62d9f41ae8f0")] [assembly: Guid("5d6a09d1-dcab-4fd8-b4e6-62d9f41ae8f0")]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
// en utilisant '*', comme indiqué ci-dessous :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.1.1")]
[assembly: AssemblyFileVersion("1.0.1.1")]

View File

@ -0,0 +1,74 @@
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Galactic_Colors_Control_GUI
{
/// <summary>
/// Multilayer Background
/// </summary>
public class Background
{
private double[] backgroundX;
private double[] backgroundY;
private Texture2D[] backSprites;
private double[] ratio;
public double speedX = 0;
public double speedY = 0;
internal void Draw(object spriteBatch)
{
throw new NotImplementedException();
}
/// <summary>
/// Background.lenght == Ratio.Lenght
/// </summary>
public Background(Texture2D[] BackSprites, double[] Ratio)
{
backSprites = BackSprites;
ratio = Ratio;
backgroundX = new double[backSprites.Length];
backgroundY = new double[backSprites.Length];
}
/// <summary>
/// Manual Move
/// </summary>
public void Move(double x, double y)
{
for (int index = 0; index < backSprites.Length; index++)
{
backgroundX[index] += (x * ratio[index]);
backgroundY[index] += (y * ratio[index]);
if (backgroundX[index] > backSprites[index].Width) { backgroundX[index] = 0; }
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>
/// AutoMove for speedX and speedY
/// </summary>
public void Update()
{
Move(speedX, speedY);
}
public void Draw(SpriteBatch spriteBatch)
{
for (int index = 0; index < backSprites.Length; index++)
{
for (int X = -1; X < Game.singleton.ScreenWidth / backSprites[index].Width + 1; X++)
{
for (int Y = -1; Y < Game.singleton.ScreenHeight / backSprites[index].Height + 1; Y++)
{
spriteBatch.Draw(backSprites[index], new Rectangle(X * backSprites[index].Width + (int)backgroundX[index], Y * backSprites[index].Height + (int)backgroundY[index], backSprites[index].Width, backSprites[index].Height), Color.White);
}
}
}
}
}
}

View File

@ -0,0 +1,118 @@
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 = 1;
public string skin = "default";
/// <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

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xs="http://www.w3.org/2001/XMLSchema" attributeFormDefault="unqualified" elementFormDefault="qualified">
<xsd:element name="config">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="logPath" type="xsd:string" />
<xsd:element name="logLevel" type="xsd:string" />
<xsd:element name="commandChar" type="xsd:unsignedByte" />
<xsd:element name="logForeColor">
<xsd:complexType>
<xsd:sequence>
<xsd:element maxOccurs="unbounded" name="ConsoleColor" type="xsd:string" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="logBackColor">
<xsd:complexType>
<xsd:sequence>
<xsd:element maxOccurs="unbounded" name="ConsoleColor" type="xsd:string" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="lang" type="xsd:unsignedByte" />
<xsd:element name="skin" type="xsd:string" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xs:schema>

View File

@ -41,9 +41,22 @@
<StartupObject /> <StartupObject />
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Compile Include="Game1.cs" /> <Compile Include="..\AssemblyInfoCommon.cs">
<Link>Properties\AssemblyInfoCommon.cs</Link>
</Compile>
<Compile Include="Background.cs" />
<Compile Include="Config.cs" />
<Compile Include="Game.cs" />
<Compile Include="Program.cs" /> <Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="States\ConnectState.cs" />
<Compile Include="States\GameState.cs" />
<Compile Include="States\IndentificationState.cs" />
<Compile Include="States\PartyState.cs" />
<Compile Include="States\MainMenuState.cs" />
<Compile Include="States\OptionsState.cs" />
<Compile Include="States\State.cs" />
<Compile Include="States\TitleState.cs" />
<Compile Include="Utilities.cs" /> <Compile Include="Utilities.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
@ -111,11 +124,21 @@
<MonoGameContentReference Include="Content\Content.mgcb" /> <MonoGameContentReference Include="Content\Content.mgcb" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Galactic Colors Control Common\Galactic Colors Control Common.csproj">
<Project>{022a69ce-22b5-4934-be9f-a9c6df9557ed}</Project>
<Name>Galactic Colors Control Common</Name>
</ProjectReference>
<ProjectReference Include="..\Galactic Colors Control\Galactic Colors Control.csproj"> <ProjectReference Include="..\Galactic Colors Control\Galactic Colors Control.csproj">
<Project>{93582ce8-c8c8-4e19-908b-d671ecbade25}</Project> <Project>{93582ce8-c8c8-4e19-908b-d671ecbade25}</Project>
<Name>Galactic Colors Control</Name> <Name>Galactic Colors Control</Name>
</ProjectReference> </ProjectReference>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Include="ConfigSchema.xsd">
<SubType>Designer</SubType>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(MSBuildExtensionsPath)\MonoGame\v3.0\MonoGame.Content.Builder.targets" /> <Import Project="$(MSBuildExtensionsPath)\MonoGame\v3.0\MonoGame.Content.Builder.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it. <!-- To modify your build process, add your task inside one of the targets below and uncomment it.

View File

@ -0,0 +1,222 @@
using Galactic_Colors_Control;
using Galactic_Colors_Control_Common;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using MyMonoGame.GUI;
using System;
using System.IO;
using System.Reflection;
namespace Galactic_Colors_Control_GUI
{
/// <summary>
/// This is the main type for your game.
/// </summary>
public class Game : Microsoft.Xna.Framework.Game
{
public static Game singleton;
private GraphicsDeviceManager graphics;
private SpriteBatch spriteBatch;
private ContentManager content;
private SoundEffect[] effects = new SoundEffect[4]; //click, hover, explosion,...
public Fonts fonts;
internal static Texture2D nullSprite;
private Texture2D[] pointerSprites = new Texture2D[1];
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
private bool isFullScreen = false;
public States.State gameState = new States.TitleState(new States.MainMenuState(), new TimeSpan(0,0,5));
private int _ScreenWidth = 1280;
private int _ScreenHeight = 720;
public int ScreenWidth { get { return _ScreenWidth; } private set { _ScreenWidth = value; } }
public int ScreenHeight { get { return _ScreenHeight; } private set { _ScreenHeight = value; } }
public Game()
{
singleton = this;
if (isFullScreen) //Fullscreen resolution
{
ScreenWidth = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width;
ScreenHeight = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height;
}
graphics = new GraphicsDeviceManager(this);
graphics.PreferredBackBufferWidth = ScreenWidth;
graphics.PreferredBackBufferHeight = ScreenHeight;
graphics.IsFullScreen = isFullScreen;
graphics.ApplyChanges();
Content.RootDirectory = "Content";
content = Content;
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
config = config.Load();
logger.Write("Galactic Colors Control GUI " + Assembly.GetEntryAssembly().GetName().Version.ToString(), Logger.logType.fatal);
logger.Initialise(config.logPath, config.logBackColor, config.logForeColor, config.logLevel, Program._debug, Program._dev);
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 });
GUI.Initialise();
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
//Need OpenAL Update for Windows 10 at least
effects[0] = content.Load<SoundEffect>("Sounds/alert");
effects[1] = content.Load<SoundEffect>("Sounds/bip");
effects[2] = content.Load<SoundEffect>("Sounds/change");
effects[3] = content.Load<SoundEffect>("Sounds/valid");
fonts.small = content.Load<SpriteFont>("Fonts/small");
fonts.basic = content.Load<SpriteFont>("Fonts/basic");
fonts.title = content.Load<SpriteFont>("Fonts/title");
for (int i = 0; i < pointerSprites.Length; i++)
{
pointerSprites[i] = content.Load<Texture2D>("Textures/Hub/pointer" + i);
}
Texture2D[] backSprites = new Texture2D[2];
backSprites[0] = content.Load<Texture2D>("Textures/background0");
backSprites[1] = content.Load<Texture2D>("Textures/background1");
States.MainMenuState.logoSprite = content.Load<Texture2D>("Textures/LogoSmall");
for (int i = 0; i < buttonsSprites.Length; i++)
{
buttonsSprites[i].topLeft = content.Load<Texture2D>("Textures/Hub/Buttons/" + i + "/topLeft");
buttonsSprites[i].topCenter = content.Load<Texture2D>("Textures/Hub/Buttons/" + i + "/topCenter");
buttonsSprites[i].topRight = content.Load<Texture2D>("Textures/Hub/Buttons/" + i + "/topRight");
buttonsSprites[i].centerLeft = content.Load<Texture2D>("Textures/Hub/Buttons/" + i + "/centerLeft");
buttonsSprites[i].centerCenter = content.Load<Texture2D>("Textures/Hub/Buttons/" + i + "/centerCenter");
buttonsSprites[i].centerRight = content.Load<Texture2D>("Textures/Hub/Buttons/" + i + "/centerRight");
buttonsSprites[i].bottomLeft = content.Load<Texture2D>("Textures/Hub/Buttons/" + i + "/bottomLeft");
buttonsSprites[i].bottomCenter = content.Load<Texture2D>("Textures/Hub/Buttons/" + i + "/bottomCenter");
buttonsSprites[i].bottomRight = content.Load<Texture2D>("Textures/Hub/Buttons/" + i + "/bottomRight");
}
//Load from files
if (Directory.Exists("Skin/" + config.skin))
{
if (Directory.Exists("Skin/" + config.skin + "/Sounds"))
{
Utilities.SoundFromMp3("Skin/" + config.skin + "/Sounds/alert.mp3", ref effects[0]);
Utilities.SoundFromMp3("Skin/" + config.skin + "/Sounds/bip.mp3", ref effects[1]);
Utilities.SoundFromMp3("Skin/" + config.skin + "/Sounds/change.mp3", ref effects[2]);
Utilities.SoundFromMp3("Skin/" + config.skin + "/Sounds/valid.mp3", ref effects[3]);
}
if (Directory.Exists("Skin/" + config.skin + "/Textures"))
{
Utilities.SpriteFromPng("Skin/" + config.skin + "Textures/background0.png", ref backSprites[0], GraphicsDevice);
Utilities.SpriteFromPng("Skin/" + config.skin + "Textures/background1.png", ref backSprites[1], GraphicsDevice);
if (Directory.Exists("Skin/" + config.skin + "/Textures/Hub/"))
{
if (Directory.Exists("Skin/" + config.skin + "/Textures/Hub/Buttons"))
{
for (int i = 0; i < buttonsSprites.Length; i++)
{
Utilities.SpriteFromPng("Skin/" + config.skin + "Textures/Hub/Buttons/" + i + "/topLeft.png", ref buttonsSprites[i].topLeft, GraphicsDevice);
Utilities.SpriteFromPng("Skin/" + config.skin + "Textures/Hub/Buttons/" + i + "/topCenter.png", ref buttonsSprites[i].topCenter, GraphicsDevice);
Utilities.SpriteFromPng("Skin/" + config.skin + "Textures/Hub/Buttons/" + i + "/topRight.png", ref buttonsSprites[i].topRight, GraphicsDevice);
Utilities.SpriteFromPng("Skin/" + config.skin + "Textures/Hub/Buttons/" + i + "/centerLeft.png", ref buttonsSprites[i].centerLeft, GraphicsDevice);
Utilities.SpriteFromPng("Skin/" + config.skin + "Textures/Hub/Buttons/" + i + "/centerCenter.png", ref buttonsSprites[i].centerCenter, GraphicsDevice);
Utilities.SpriteFromPng("Skin/" + config.skin + "Textures/Hub/Buttons/" + i + "/centerRight.png", ref buttonsSprites[i].centerRight, GraphicsDevice);
Utilities.SpriteFromPng("Skin/" + config.skin + "Textures/Hub/Buttons/" + i + "/bottomLeft.png", ref buttonsSprites[i].bottomLeft, GraphicsDevice);
Utilities.SpriteFromPng("Skin/" + config.skin + "Textures/Hub/Buttons/" + i + "/bottomCenter.png", ref buttonsSprites[i].bottomCenter, GraphicsDevice);
Utilities.SpriteFromPng("Skin/" + config.skin + "Textures/Hub/Buttons/" + i + "/bottomRight.png", ref buttonsSprites[i].bottomRight, GraphicsDevice);
}
}
for (int i = 0; i < pointerSprites.Length; i++)
{
Utilities.SpriteFromPng("Skin/" + config.skin + "/Textures/Hub/pointer" + i + ".png", ref pointerSprites[i], GraphicsDevice);
}
}
}
}
background = new Background(backSprites, new double[2] { 1, 2 }); //Background initialisation
background.speedX = 1;
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// game-specific content.
/// </summary>
protected override void UnloadContent()
{
// Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
gameState.Update();
GUI.Update();
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.DarkGray);
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied);
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);
spriteBatch.End();
base.Draw(gameTime);
}
}
}

View File

@ -1,508 +0,0 @@
using System;
using MyMonoGame.GUI;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Audio;
using Galactic_Colors_Control;
using System.Threading;
using System.IO;
using Microsoft.Xna.Framework.Input;
using System.Reflection;
using System.Collections.Generic;
namespace Galactic_Colors_Control_GUI
{
/// <summary>
/// This is the main type for your game.
/// </summary>
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
ContentManager content;
private SoundEffect[] effects = new SoundEffect[4];
private SpriteFont smallFont;
private SpriteFont basicFont;
private SpriteFont titleFont;
internal static Texture2D nullSprite;
private Texture2D logoSprite;
private Texture2D[] backSprites = new Texture2D[2];
private double[] backgroundX = new double[2];
private double[] backgroundY = new double[2];
private double acceleratorX = 1;
private Texture2D[] pointerSprites = new Texture2D[1];
private boxSprites[] buttonsSprites = new boxSprites[1];
private Client client;
private Manager GUI = new Manager();
private string skinName;
private bool isFullScren = false;
private enum GameStatus { Home, Connect, Options, Game, Pause, End, Thanks,
Title,
Indentification,
Kick
}
private GameStatus gameStatus = GameStatus.Home;
private int ScreenWidth = 1280;
private int ScreenHeight = 720;
private string username = null;
private static Thread Writer;
private bool showOKMessage = false;
private string messageTitle;
private string messageText = string.Empty;
private bool showYNMessage = false;
private bool showLoading = false;
private bool showChat = false;
private string chatText = string.Empty;
private string chatInput = string.Empty;
public Game1()
{
if (isFullScren)
{
ScreenWidth = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width;
ScreenHeight = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height;
}
graphics = new GraphicsDeviceManager(this);
graphics.PreferredBackBufferWidth = ScreenWidth;
graphics.PreferredBackBufferHeight = ScreenHeight;
graphics.IsFullScreen = isFullScren;
graphics.ApplyChanges();
Content.RootDirectory = "Content";
content = Content;
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
nullSprite = new Texture2D(GraphicsDevice, 1, 1);
nullSprite.SetData(new Color[1 * 1] { Color.White });
GUI.Initialise();
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
//Need OpenAL Update for Windows 10 at least
effects[0] = content.Load<SoundEffect>("Sounds/alert");
effects[1] = content.Load<SoundEffect>("Sounds/bip");
effects[2] = content.Load<SoundEffect>("Sounds/change");
effects[3] = content.Load<SoundEffect>("Sounds/valid");
smallFont = content.Load<SpriteFont>("Fonts/small");
basicFont = content.Load<SpriteFont>("Fonts/basic");
titleFont = content.Load<SpriteFont>("Fonts/title");
for (int i = 0; i < pointerSprites.Length; i++) {
pointerSprites[i] = content.Load<Texture2D>("Textures/Hub/pointer" + i);
}
backSprites[0] = content.Load<Texture2D>("Textures/background0");
backSprites[1] = content.Load<Texture2D>("Textures/background1");
logoSprite = content.Load<Texture2D>("Textures/LogoSmall");
for (int i = 0; i < buttonsSprites.Length; i++)
{
buttonsSprites[i].topLeft = content.Load<Texture2D>("Textures/Hub/Buttons/" + i + "/topLeft");
buttonsSprites[i].topCenter = content.Load<Texture2D>("Textures/Hub/Buttons/" + i + "/topCenter");
buttonsSprites[i].topRight = content.Load<Texture2D>("Textures/Hub/Buttons/" + i + "/topRight");
buttonsSprites[i].centerLeft = content.Load<Texture2D>("Textures/Hub/Buttons/" + i + "/centerLeft");
buttonsSprites[i].centerCenter = content.Load<Texture2D>("Textures/Hub/Buttons/" + i + "/centerCenter");
buttonsSprites[i].centerRight = content.Load<Texture2D>("Textures/Hub/Buttons/" + i + "/centerRight");
buttonsSprites[i].bottomLeft = content.Load<Texture2D>("Textures/Hub/Buttons/" + i + "/bottomLeft");
buttonsSprites[i].bottomCenter = content.Load<Texture2D>("Textures/Hub/Buttons/" + i + "/bottomCenter");
buttonsSprites[i].bottomRight = content.Load<Texture2D>("Textures/Hub/Buttons/" + i + "/bottomRight");
}
if (Directory.Exists("Skin/" + skinName))
{
if (Directory.Exists("Skin/" + skinName + "/Sounds"))
{
Utilities.SoundFromMp3("Skin/" + skinName + "/Sounds/alert.mp3", ref effects[0]);
Utilities.SoundFromMp3("Skin/" + skinName + "/Sounds/bip.mp3", ref effects[1]);
Utilities.SoundFromMp3("Skin/" + skinName + "/Sounds/change.mp3", ref effects[2]);
Utilities.SoundFromMp3("Skin/" + skinName + "/Sounds/valid.mp3", ref effects[3]);
}
if (Directory.Exists("Skin/" + skinName + "/Textures"))
{
Utilities.SpriteFromPng("Skin/" + skinName + "Textures/background0.png", ref backSprites[0], GraphicsDevice);
Utilities.SpriteFromPng("Skin/" + skinName + "Textures/background1.png", ref backSprites[1], GraphicsDevice);
if (Directory.Exists("Skin/" + skinName + "/Textures/Hub/"))
{
if(Directory.Exists("Skin/" + skinName + "/Textures/Hub/Buttons"))
{
for (int i = 0; i < buttonsSprites.Length; i++)
{
Utilities.SpriteFromPng("Skin/" + skinName + "Textures/Hub/Buttons/" + i + "/topLeft.png", ref buttonsSprites[i].topLeft, GraphicsDevice);
Utilities.SpriteFromPng("Skin/" + skinName + "Textures/Hub/Buttons/" + i + "/topCenter.png", ref buttonsSprites[i].topCenter, GraphicsDevice);
Utilities.SpriteFromPng("Skin/" + skinName + "Textures/Hub/Buttons/" + i + "/topRight.png", ref buttonsSprites[i].topRight, GraphicsDevice);
Utilities.SpriteFromPng("Skin/" + skinName + "Textures/Hub/Buttons/" + i + "/centerLeft.png", ref buttonsSprites[i].centerLeft, GraphicsDevice);
Utilities.SpriteFromPng("Skin/" + skinName + "Textures/Hub/Buttons/" + i + "/centerCenter.png", ref buttonsSprites[i].centerCenter, GraphicsDevice);
Utilities.SpriteFromPng("Skin/" + skinName + "Textures/Hub/Buttons/" + i + "/centerRight.png", ref buttonsSprites[i].centerRight, GraphicsDevice);
Utilities.SpriteFromPng("Skin/" + skinName + "Textures/Hub/Buttons/" + i + "/bottomLeft.png", ref buttonsSprites[i].bottomLeft, GraphicsDevice);
Utilities.SpriteFromPng("Skin/" + skinName + "Textures/Hub/Buttons/" + i + "/bottomCenter.png", ref buttonsSprites[i].bottomCenter, GraphicsDevice);
Utilities.SpriteFromPng("Skin/" + skinName + "Textures/Hub/Buttons/" + i + "/bottomRight.png", ref buttonsSprites[i].bottomRight, GraphicsDevice);
}
}
for (int i = 0; i < pointerSprites.Length; i++)
{
Utilities.SpriteFromPng("Skin/" + skinName + "/Textures/Hub/pointer" + i + ".png", ref pointerSprites[i], GraphicsDevice);
}
}
}
}
// TODO: use this.Content to load your game content here
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// game-specific content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
switch (gameStatus)
{
case GameStatus.Home:
case GameStatus.Title:
case GameStatus.Connect:
case GameStatus.Indentification:
backgroundX[0] -= 1 * acceleratorX;
backgroundX[1] -= 2 * acceleratorX;
break;
case GameStatus.Game:
if (client.Output.Count > 0)
{
string text = client.Output[0];
switch (text)
{
case "/clear":
chatText = string.Empty;
break;
default:
ChatAdd(text);
break;
}
client.Output.Remove(text);
}
if (!client.isRunning) { gameStatus = GameStatus.Kick; }
break;
}
GUI.Update();
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.DarkGray);
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied);
GUI.Draw(spriteBatch);
switch (gameStatus)
{
case GameStatus.Title:
DrawBackground(0);
DrawBackground(1);
GUI.Label(new MyMonoGame.Vector(ScreenWidth / 2, ScreenHeight / 2), "Galactic Colors Control", titleFont, new MyMonoGame.Colors(Color.White), Manager.textAlign.centerCenter);
break;
case GameStatus.Home:
DrawBackground(0);
DrawBackground(1);
GUI.Label(new MyMonoGame.Vector(ScreenWidth / 2, ScreenHeight / 4), "Galactic Colors Control", titleFont, new MyMonoGame.Colors(Color.White), Manager.textAlign.centerCenter);
GUI.Label(new MyMonoGame.Vector(ScreenWidth / 2, ScreenHeight / 4 + 40), "GUI " + Assembly.GetEntryAssembly().GetName().Version.ToString(), basicFont, new MyMonoGame.Colors(Color.White), Manager.textAlign.centerCenter);
if (GUI.Button(new Rectangle(ScreenWidth - 64, ScreenHeight - 74,64,64), logoSprite)) { System.Diagnostics.Process.Start("https://sheychen.shost.ca/"); }
if (GUI.Button(new Rectangle(ScreenWidth / 2 - 75, ScreenHeight / 2 - 30, 150, 40), buttonsSprites[0], "Play", basicFont, new MyMonoGame.Colors(Color.White, Color.Green))) {
GUI.ResetFocus();
client = new Client();
new Thread(() => {
while (acceleratorX < 5)
{
Thread.Sleep(20);
acceleratorX += 0.1d;
}
gameStatus = GameStatus.Connect;
}).Start();
}
//if (GUI.Button(new Rectangle(ScreenWidth / 2 - 75, ScreenHeight / 2 + 20, 150, 40), buttonsSprites[0], "Options", basicFont, new MyMonoGame.Colors(Color.White, Color.Blue))) {
// GUI.ResetFocus();
// gameStatus = GameStatus.Options;
//}
if (GUI.Button(new Rectangle(ScreenWidth / 2 - 75, ScreenHeight / 2 + 70, 150, 40), buttonsSprites[0], "Exit", basicFont, new MyMonoGame.Colors(Color.White, Color.Red))) {
GUI.ResetFocus();
gameStatus = GameStatus.Title;
new Thread(() => {
while (acceleratorX > 0)
{
Thread.Sleep(10);
acceleratorX -= 0.01d;
}
Exit();
}).Start();
}
break;
case GameStatus.Connect:
DrawBackground(0);
DrawBackground(1);
GUI.Label(new MyMonoGame.Vector(ScreenWidth / 2, ScreenHeight / 4), "Galactic Colors Control", titleFont, new MyMonoGame.Colors(Color.White), Manager.textAlign.centerCenter);
if (showLoading)
{
GUI.Box(new Rectangle(ScreenWidth / 2 - 150, ScreenHeight / 4 + 50, 300, 50), buttonsSprites[0]);
GUI.Label(new Rectangle(ScreenWidth / 2 - 150, ScreenHeight / 4 + 50, 300, 50), "Loading", basicFont);
}
else
{
if (showOKMessage)
{
GUI.Box(new Rectangle(ScreenWidth / 2 - 150, ScreenHeight / 4 + 50, 300, 150), buttonsSprites[0]);
GUI.Label(new MyMonoGame.Vector(ScreenWidth / 2, ScreenHeight / 4 + 60), messageTitle, basicFont, null, Manager.textAlign.bottomCenter);
GUI.Label(new MyMonoGame.Vector(ScreenWidth / 2, ScreenHeight / 4 + 100), messageText, smallFont, null, Manager.textAlign.bottomCenter);
if (GUI.Button(new Rectangle(ScreenWidth / 2 - 140, ScreenHeight / 4 + 150, 280, 40), buttonsSprites[0], "Ok", basicFont)) { GUI.ResetFocus(); showOKMessage = false; }
}
else {
if (showYNMessage)
{
GUI.Box(new Rectangle(ScreenWidth / 2 - 150, ScreenHeight / 4 + 50, 300, 100), buttonsSprites[0]);
GUI.Label(new MyMonoGame.Vector(ScreenWidth / 2, ScreenHeight / 4 + 60), messageTitle, basicFont, null, Manager.textAlign.bottomCenter);
if (GUI.Button(new Rectangle(ScreenWidth / 2 - 140, ScreenHeight / 4 + 100, 135, 40), buttonsSprites[0], "Yes", basicFont))
{
GUI.ResetFocus();
new Thread(ConnectHost).Start();
showYNMessage = false;
}
if (GUI.Button(new Rectangle(ScreenWidth / 2 + 5, ScreenHeight / 4 + 100, 135, 40), buttonsSprites[0], "No", basicFont))
{
client.Output.Clear();
client.ResetHost();
GUI.ResetFocus();
showYNMessage = false;
}
}
else {
if (GUI.TextField(new Rectangle(ScreenWidth / 2 - 75, ScreenHeight / 2 - 30, 150, 40), ref username, basicFont, new MyMonoGame.Colors(Color.LightGray, Color.White), Manager.textAlign.centerCenter, "Server address")) { new Thread(ValidateHost).Start(); }
if (GUI.Button(new Rectangle(ScreenWidth / 2 - 75, ScreenHeight / 2 + 20, 150, 40), buttonsSprites[0], "Connect", basicFont, new MyMonoGame.Colors(Color.LightGray, Color.White))) { new Thread(ValidateHost).Start(); }
if (GUI.Button(new Rectangle(ScreenWidth / 2 - 75, ScreenHeight / 2 + 70, 150, 40), buttonsSprites[0], "Back", basicFont, new MyMonoGame.Colors(Color.LightGray, Color.White)))
{
GUI.ResetFocus();
new Thread(() =>
{
while (acceleratorX > 1)
{
Thread.Sleep(20);
acceleratorX -= 0.1d;
}
gameStatus = GameStatus.Home;
username = null;
}).Start();
}
}
}
}
break;
case GameStatus.Indentification:
DrawBackground(0);
DrawBackground(1);
GUI.Label(new MyMonoGame.Vector(ScreenWidth / 2, ScreenHeight / 4), "Galactic Colors Control", titleFont, new MyMonoGame.Colors(Color.White), Manager.textAlign.centerCenter);
if (showLoading)
{
GUI.Box(new Rectangle(ScreenWidth / 2 - 150, ScreenHeight / 4 + 50, 300, 50), buttonsSprites[0]);
GUI.Label(new Rectangle(ScreenWidth / 2 - 150, ScreenHeight / 4 + 50, 300, 50), "Loading", basicFont);
}
else
{
if (showOKMessage)
{
GUI.Box(new Rectangle(ScreenWidth / 2 - 150, ScreenHeight / 4 + 50, 300, 150), buttonsSprites[0]);
GUI.Label(new MyMonoGame.Vector(ScreenWidth / 2, ScreenHeight / 4 + 60), messageTitle, basicFont, null, Manager.textAlign.bottomCenter);
GUI.Label(new MyMonoGame.Vector(ScreenWidth / 2, ScreenHeight / 4 + 100), messageText, smallFont, null, Manager.textAlign.bottomCenter);
if (GUI.Button(new Rectangle(ScreenWidth / 2 - 140, ScreenHeight / 4 + 150, 280, 40), buttonsSprites[0], "Ok", basicFont)) { GUI.ResetFocus(); showOKMessage = false; }
}
else {
if (GUI.TextField(new Rectangle(ScreenWidth / 2 - 75, ScreenHeight / 2 - 30, 150, 40), ref username, basicFont, new MyMonoGame.Colors(Color.LightGray, Color.White), Manager.textAlign.centerCenter, "Username")) { new Thread(IdentifiacateHost).Start(); }
if (GUI.Button(new Rectangle(ScreenWidth / 2 - 75, ScreenHeight / 2 + 20, 150, 40), buttonsSprites[0], "Validate", basicFont, new MyMonoGame.Colors(Color.LightGray, Color.White))) { new Thread(IdentifiacateHost).Start(); }
if (GUI.Button(new Rectangle(ScreenWidth / 2 - 75, ScreenHeight / 2 + 70, 150, 40), buttonsSprites[0], "Back", basicFont, new MyMonoGame.Colors(Color.LightGray, Color.White)))
{
GUI.ResetFocus();
new Thread(() =>
{
while (acceleratorX > 1)
{
Thread.Sleep(20);
acceleratorX -= 0.1d;
}
gameStatus = GameStatus.Home;
username = null;
}).Start();
}
}
}
break;
case GameStatus.Game:
DrawBackground(0);
DrawBackground(1);
GUI.Texture(new Rectangle(0,0,ScreenWidth, 30), nullSprite, new MyMonoGame.Colors(new Color(0.1f,0.1f,0.1f)));
if(GUI.Button(new Rectangle(5, 5, 50, 20), (showChat ? "Hide" : "Show") + " chat", smallFont, new MyMonoGame.Colors(Color.White, Color.LightGray, Color.Gray))) { GUI.ResetFocus(); showChat = !showChat; }
if (showChat)
{
GUI.Box(new Rectangle(0, 30, 310, 310), buttonsSprites[0]);
if(GUI.TextField(new Rectangle(5,35,305,20), ref chatInput, basicFont, null, Manager.textAlign.centerLeft, "Enter message")) { if(chatInput != null) { ChatAdd(chatInput); client.SendRequest(chatInput); chatInput = null; } }
GUI.Label(new Rectangle(5, 60, 305, 245), chatText, smallFont, null, Manager.textAlign.topLeft, true);
}
break;
}
Color ActiveColor = IsActive ? Color.Green : Color.Red;
GUI.Label(new MyMonoGame.Vector(10, ScreenHeight - 20), (1 / (float)gameTime.ElapsedGameTime.TotalSeconds).ToString(), smallFont, new MyMonoGame.Colors(ActiveColor));
spriteBatch.Draw(pointerSprites[0], new Rectangle(Mouse.GetState().X - 10, Mouse.GetState().Y - 10, 20, 20), Color.Red);
spriteBatch.End();
base.Draw(gameTime);
}
private void ValidateHost()
{
showLoading = true;
if ( username == null) { username = ""; }
string Host = client.ValidateHost(username);
if (Host == null)
{
messageTitle = "Error";
messageText = string.Empty;
foreach(string line in client.Output.ToArray()) { messageText += (line + Environment.NewLine); }
showOKMessage = true;
client.Output.Clear();
client.ResetHost();;
}
else
{
messageTitle = "Use " + Host + "?";
showYNMessage = true;
}
showLoading = false;
}
private void ConnectHost()
{
showLoading = true;
if (client.ConnectHost())
{
gameStatus = GameStatus.Indentification;
}
else
{
messageTitle = "Error";
messageText = string.Empty;
foreach (string line in client.Output.ToArray()) { messageText += (line + Environment.NewLine); }
showOKMessage = true;
client.Output.Clear();
client.ResetHost();
}
showLoading = false;
}
private void IdentifiacateHost()
{
showLoading = true;
if (username != null)
{
if(username.Length > 3)
{
client.Output.Clear();
client.SendRequest("/connect " + username);
bool wait = true;
while (wait)
{
if (client.Output.Count > 0)
{
wait = false;
}
}
if(client.Output.Contains("Identifiaction succes"))
{
gameStatus = GameStatus.Game;
}
else
{
messageTitle = "Error";
messageText = string.Empty;
foreach (string line in client.Output.ToArray()) { messageText += (line + Environment.NewLine); }
showOKMessage = true;
showLoading = false;
client.Output.Clear();
}
}
}
showLoading = false;
}
private void ChatAdd(string text)
{
chatText += ((chatText != string.Empty ? Environment.NewLine : "") + text);
}
private void DrawBackground(int index)
{
if (backgroundX[index] > backSprites[index].Width) { backgroundX[index] = 0; }
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; }
for (int X = -1; X < ScreenWidth / backSprites[index].Width + 1; X++)
{
for (int Y = -1; Y < ScreenHeight / backSprites[index].Height + 1; Y++)
{
GUI.Texture(new Rectangle(X * backSprites[index].Width + (int)backgroundX[index], Y * backSprites[index].Height + (int)backgroundY[index], backSprites[index].Width, backSprites[index].Height), backSprites[index], new MyMonoGame.Colors(Color.White));
}
}
}
}
}

View File

@ -1,25 +1,25 @@
<configuration> <configuration>
<dllmap os="linux" dll="opengl32.dll" target="libGL.so.1"/> <dllmap os="linux" dll="opengl32.dll" target="libGL.so.1" />
<dllmap os="linux" dll="glu32.dll" target="libGLU.so.1"/> <dllmap os="linux" dll="glu32.dll" target="libGLU.so.1" />
<dllmap os="linux" dll="openal32.dll" target="libopenal.so.1"/> <dllmap os="linux" dll="openal32.dll" target="libopenal.so.1" />
<dllmap os="linux" dll="alut.dll" target="libalut.so.0"/> <dllmap os="linux" dll="alut.dll" target="libalut.so.0" />
<dllmap os="linux" dll="opencl.dll" target="libOpenCL.so"/> <dllmap os="linux" dll="opencl.dll" target="libOpenCL.so" />
<dllmap os="linux" dll="libX11" target="libX11.so.6"/> <dllmap os="linux" dll="libX11" target="libX11.so.6" />
<dllmap os="linux" dll="libXi" target="libXi.so.6"/> <dllmap os="linux" dll="libXi" target="libXi.so.6" />
<dllmap os="linux" dll="SDL2.dll" target="libSDL2-2.0.so.0.disabled"/> <dllmap os="linux" dll="SDL2.dll" target="libSDL2-2.0.so.0.disabled" />
<dllmap os="osx" dll="opengl32.dll" target="/System/Library/Frameworks/OpenGL.framework/OpenGL"/> <dllmap os="osx" dll="opengl32.dll" target="/System/Library/Frameworks/OpenGL.framework/OpenGL" />
<dllmap os="osx" dll="openal32.dll" target="/System/Library/Frameworks/OpenAL.framework/OpenAL" /> <dllmap os="osx" dll="openal32.dll" target="/System/Library/Frameworks/OpenAL.framework/OpenAL" />
<dllmap os="osx" dll="alut.dll" target="/System/Library/Frameworks/OpenAL.framework/OpenAL" /> <dllmap os="osx" dll="alut.dll" target="/System/Library/Frameworks/OpenAL.framework/OpenAL" />
<dllmap os="osx" dll="libGLES.dll" target="/System/Library/Frameworks/OpenGLES.framework/OpenGLES" /> <dllmap os="osx" dll="libGLES.dll" target="/System/Library/Frameworks/OpenGLES.framework/OpenGLES" />
<dllmap os="osx" dll="libGLESv1_CM.dll" target="/System/Library/Frameworks/OpenGLES.framework/OpenGLES" /> <dllmap os="osx" dll="libGLESv1_CM.dll" target="/System/Library/Frameworks/OpenGLES.framework/OpenGLES" />
<dllmap os="osx" dll="libGLESv2.dll" target="/System/Library/Frameworks/OpenGLES.framework/OpenGLES" /> <dllmap os="osx" dll="libGLESv2.dll" target="/System/Library/Frameworks/OpenGLES.framework/OpenGLES" />
<dllmap os="osx" dll="opencl.dll" target="/System/Library/Frameworks/OpenCL.framework/OpenCL"/> <dllmap os="osx" dll="opencl.dll" target="/System/Library/Frameworks/OpenCL.framework/OpenCL" />
<dllmap os="osx" dll="SDL2.dll" target="libSDL2.dylib"/> <dllmap os="osx" dll="SDL2.dll" target="libSDL2.dylib" />
<!-- XQuartz compatibility (X11 on Mac) --> <!-- XQuartz compatibility (X11 on Mac) -->
<dllmap os="osx" dll="libGL.so.1" target="/usr/X11/lib/libGL.dylib"/> <dllmap os="osx" dll="libGL.so.1" target="/usr/X11/lib/libGL.dylib" />
<dllmap os="osx" dll="libX11" target="/usr/X11/lib/libX11.dylib"/> <dllmap os="osx" dll="libX11" target="/usr/X11/lib/libX11.dylib" />
<dllmap os="osx" dll="libXcursor.so.1" target="/usr/X11/lib/libXcursor.dylib"/> <dllmap os="osx" dll="libXcursor.so.1" target="/usr/X11/lib/libXcursor.dylib" />
<dllmap os="osx" dll="libXi" target="/usr/X11/lib/libXi.dylib"/> <dllmap os="osx" dll="libXi" target="/usr/X11/lib/libXi.dylib" />
<dllmap os="osx" dll="libXinerama" target="/usr/X11/lib/libXinerama.dylib"/> <dllmap os="osx" dll="libXinerama" target="/usr/X11/lib/libXinerama.dylib" />
<dllmap os="osx" dll="libXrandr.so.2" target="/usr/X11/lib/libXrandr.dylib"/> <dllmap os="osx" dll="libXrandr.so.2" target="/usr/X11/lib/libXrandr.dylib" />
</configuration> </configuration>

View File

@ -1,4 +1,5 @@
using System; using Galactic_Colors_Control_Common;
using System;
namespace Galactic_Colors_Control_GUI namespace Galactic_Colors_Control_GUI
{ {
@ -7,14 +8,33 @@ namespace Galactic_Colors_Control_GUI
/// </summary> /// </summary>
public static class Program public static class Program
{ {
public static bool _dev = false;
public static bool _debug = false;
/// <summary> /// <summary>
/// The main entry point for the application. /// The main entry point for the application.
/// </summary> /// </summary>
[STAThread] [STAThread]
static void Main() private static void Main(string[] args)
{ {
using (var game = new Game1()) 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(); game.Run();
} }
} }
} }

View File

@ -1,36 +1,20 @@
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following // General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information // set of attributes. Change these attribute values to modify the information
// associated with an assembly. // associated with an assembly.
[assembly: AssemblyTitle("Galactic Colors Control GUI")] [assembly: AssemblyTitle("Galactic Colors Control GUI")]
[assembly: AssemblyProduct("Galactic Colors Control GUI")] [assembly: AssemblyProduct("Galactic Colors Control GUI")]
[assembly: AssemblyConfiguration("")] [assembly: AssemblyConfiguration("")]
[assembly: AssemblyDescription("")] [assembly: AssemblyDescription("")]
[assembly: AssemblyCompany("sheychen")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")] [assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")] [assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible // Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from // to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type. // COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)] [assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM // The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("606d35be-02e8-4a7e-978e-04c2aca6ccd7")] [assembly: Guid("606d35be-02e8-4a7e-978e-04c2aca6ccd7")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.1.1")]
[assembly: AssemblyFileVersion("1.0.1.1")]

View File

@ -0,0 +1,154 @@
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
{
public struct Message
{
public string title;
public string text;
public Message(string Title, string Text = "")
{
title = Title;
text = Text;
}
}
public class ConnectState : State
{
private bool locked = false;
private bool showLoading = false;
private bool showOKMessage = false;
private bool showYNMessage = false;
private Message message;
private string adress;
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);
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.Label(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 50), Game.singleton.multilang.Get("Loading", Game.singleton.config.lang), Game.singleton.fonts.basic);
}
else
{
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 + 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; }
}
else
{
if (showYNMessage)
{
Game.singleton.GUI.Box(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 100), 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);
if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 140, Game.singleton.ScreenHeight / 4 + 100, 135, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("Yes", Game.singleton.config.lang), Game.singleton.fonts.basic))
{
if (!locked)
{
locked = true;
showYNMessage = false;
Game.singleton.GUI.ResetFocus();
new Thread(ConnectHost).Start();
}
}
if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 + 5, Game.singleton.ScreenHeight / 4 + 100, 135, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("No", Game.singleton.config.lang), Game.singleton.fonts.basic))
{
showYNMessage = false;
Game.singleton.client.ResetHost();
Game.singleton.GUI.ResetFocus();
}
}
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 (!locked)
{
locked = true;
new Thread(ValidateHost).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("Connect", Game.singleton.config.lang), Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White)))
{
if (!locked)
{
locked = true;
new Thread(ValidateHost).Start();
}
}
if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 + 70, 150, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("Back", Game.singleton.config.lang), Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White)))
{
if (!locked)
{
locked = true;
Game.singleton.GUI.ResetFocus();
new Thread(() =>
{
while (!Utilities.DoubleTo(ref Game.singleton.background.speedX, 1, 0.1)) { Thread.Sleep(20); }
Game.singleton.gameState = new MainMenuState();
}).Start();
}
}
}
}
}
}
public override void Update()
{
Game.singleton.background.Update();
}
private void ValidateHost()
{
showLoading = true;
if (adress == null) { adress = ""; }
string Host = Game.singleton.client.ValidateHost(adress);
if (Host[0] == '*')
{
Host = Host.Substring(1);
message.title = Game.singleton.multilang.Get("Error", Game.singleton.config.lang);
message.text = Host;
showOKMessage = true;
Game.singleton.client.ResetHost();
Game.singleton.logger.Write("Validate : " + Host, Logger.logType.info);
}
else
{
message.title = Game.singleton.multilang.Get("Use", Game.singleton.config.lang) + " " + Host + "?";
showYNMessage = true;
}
showLoading = false;
locked = false;
}
private void ConnectHost()
{
showLoading = true;
if (Game.singleton.client.ConnectHost())
{
Game.singleton.logger.Write("Connected", Logger.logType.info);
Game.singleton.gameState = new IndentificationState();
}
else
{
Game.singleton.logger.Write("Connect error", Logger.logType.error);
message.title = Game.singleton.multilang.Get("Error", Game.singleton.config.lang);
message.text = string.Empty;
showOKMessage = true;
Game.singleton.client.ResetHost();
}
showLoading = false;
}
}
}

View File

@ -0,0 +1,175 @@
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 Microsoft.Xna.Framework.Input;
namespace Galactic_Colors_Control_GUI.States
{
public class GameState : State
{
private bool showChat = false;
private string chatText;
private string chatInput;
private bool showLoading = false;
private bool showOKMessage = false;
private Message message;
public GameState()
{
Game.singleton.client.OnEvent += new EventHandler(OnEvent); //Set OnEvent function
}
public override void Draw(SpriteBatch spritebatch)
{
Game.singleton.background.Draw(spritebatch);
Game.singleton.GUI.Texture(new Rectangle(0, 0, Game.singleton.ScreenWidth, 30), Game.nullSprite, new MyMonoGame.Colors(new Color(0.1f, 0.1f, 0.1f)));
if (Game.singleton.GUI.Button(new Rectangle(5, 5, 50, 20), (showChat ? Game.singleton.multilang.Get("Hide", Game.singleton.config.lang) : Game.singleton.multilang.Get("Show", Game.singleton.config.lang)) + " " + Game.singleton.multilang.Get("Chat", Game.singleton.config.lang), Game.singleton.fonts.small, new MyMonoGame.Colors(Color.White, Color.LightGray, Color.Gray))) { Game.singleton.GUI.ResetFocus(); showChat = !showChat; }
if (showChat)
{
Game.singleton.GUI.Box(new Rectangle(0, 30, 310, 310), Game.singleton.buttonsSprites[0]);
if (Game.singleton.GUI.TextField(new Rectangle(5, 35, 305, 20), ref chatInput, Game.singleton.fonts.basic, null, Manager.textAlign.centerLeft, Game.singleton.multilang.Get("EnterMessage", Game.singleton.config.lang))) { if (chatInput != null) { new Thread(ChatEnter).Start(); } }
Game.singleton.GUI.Label(new Rectangle(5, 60, 305, 245), chatText, Game.singleton.fonts.small, null, Manager.textAlign.topLeft, true);
}
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.Label(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 50), Game.singleton.multilang.Get("Loading", Game.singleton.config.lang), Game.singleton.fonts.basic);
}
else
{
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 + 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; Game.singleton.client.ExitHost(); }
}
}
}
public override void Update()
{
if (Keyboard.GetState().IsKeyDown(Keys.Escape) || (!Game.singleton.client.isRunning)) {
Game.singleton.client.ExitHost();
Game.singleton.gameState = new MainMenuState();
}
}
private void ChatEnter()
{
string request = chatInput;
chatInput = null;
if (request == null)
return;
if (request.Length == 0)
return;
ResultData res;
if (request[0] == Game.singleton.config.commandChar)
{
request = request.Substring(1);
res = Game.singleton.client.Request(Common.SplitArgs(request));
ChatText(Game.singleton.multilang.GetResultText(res, Game.singleton.config.lang));
}
else
{
res = Game.singleton.client.Request(Common.Strings("say", request));
if (res.type != ResultTypes.OK)
{
ChatText(Game.singleton.multilang.GetResultText(res, Game.singleton.config.lang));
}
}
}
private void OnEvent(object sender, EventArgs e)
{
//TODO add PartyKick
EventData eve = ((EventDataArgs)e).Data;
if (eve.type == EventTypes.ServerKick)
{
Game.singleton.logger.Write("Server kick" + eve.data, Logger.logType.warm);
message.title = Game.singleton.multilang.Get("ServerKick", Game.singleton.config.lang);
message.text = Common.ArrayToString(eve.data);
showOKMessage = true;
}else
{
ChatText(Game.singleton.multilang.GetEventText(eve, Game.singleton.config.lang));
}
}
public void ChatText(string text)
{
chatText += (text + Environment.NewLine);
}
/*
private void PartyClick()
{
showLoading = true;
GUI.ResetFocus();
//TODO
/*
if (showParty)
{
client.SendRequest("/party leave");
showParty = false;
showLoading = false;
}
else
{
client.Output.Clear();
client.SendRequest("/party list");
int wait = 0;
while (wait < 20)
{
if (client.Output.Count > 0)
{
wait = 20;
}
else
{
wait++;
Thread.Sleep(200);
}
}
if (client.Output.Count > 0)
{
Thread.Sleep(500);
if (client.Output.Count > 1)
{
messageTitle = "Party";
messageText = string.Empty;
foreach (string line in client.Output.ToArray()) { messageText += (line + Environment.NewLine); }
showOKMessage = true;
client.Output.Clear();
}
else
{
messageTitle = "Any party";
messageText = string.Empty;
foreach (string line in client.Output.ToArray()) { messageText += (line + Environment.NewLine); }
showOKMessage = true;
client.Output.Clear();
}
}
else
{
messageTitle = "Timeout";
messageText = "";
showOKMessage = true;
showLoading = false;
client.Output.Clear();
}
}
}*/
}
}

View File

@ -0,0 +1,102 @@
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
{
public class IndentificationState : State
{
private string username;
private Message message;
private bool locked = false;
private bool showLoading = false;
private bool showOKMessage = false;
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);
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.Label(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 50), Game.singleton.multilang.Get("Loading", Game.singleton.config.lang), Game.singleton.fonts.basic);
}
else
{
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 + 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; }
}
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 (!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 (!locked)
{
locked = true;
new Thread(IdentifiacateHost).Start();
}
}
if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 + 70, 150, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("Back", Game.singleton.config.lang), Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White)))
{
if (!locked)
{
locked = true;
Game.singleton.GUI.ResetFocus();
Game.singleton.client.ExitHost();
new Thread(() =>
{
while (!Utilities.DoubleTo(ref Game.singleton.background.speedX, 1, 0.1)) { Thread.Sleep(20); }
Game.singleton.gameState = new MainMenuState();
}).Start();
}
}
}
}
}
private void IdentifiacateHost()
{
showLoading = true;
if (username != null)
{
if (username.Length > 3)
{
ResultData res = Game.singleton.client.Request(new string[2] { "connect", username });
if (res.type == ResultTypes.OK)
{
Game.singleton.gameState = new PartyState();
}
else
{
message.title = Game.singleton.multilang.Get("Error", Game.singleton.config.lang);
message.text = Common.ArrayToString(res.result);
showOKMessage = true;
}
}
}
showLoading = false;
locked = false;
}
public override void Update()
{
Game.singleton.background.Update();
}
}
}

View File

@ -0,0 +1,64 @@
using System;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using MyMonoGame.GUI;
using System.Reflection;
using Galactic_Colors_Control;
using System.Threading;
using Galactic_Colors_Control_Common;
namespace Galactic_Colors_Control_GUI.States
{
public class MainMenuState : State
{
public static Texture2D logoSprite;
private bool locked = false;
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 + 40), Game.singleton.multilang.Get("GUI", Game.singleton.config.lang) + " " + Assembly.GetEntryAssembly().GetName().Version.ToString(), Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.White), Manager.textAlign.centerCenter);
if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth - 64, Game.singleton.ScreenHeight - 74, 64, 64), logoSprite)) { System.Diagnostics.Process.Start("https://sheychen.shost.ca/"); }
if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 - 30, 150, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("Play", Game.singleton.config.lang), Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.White, Color.Green)))
{
if (!locked)
{
locked = true;
Game.singleton.GUI.ResetFocus();
Game.singleton.client = new Client();
new Thread(() =>
{
while (!Utilities.DoubleTo(ref Game.singleton.background.speedX, 5, 0.1)) { Thread.Sleep(20); }
Game.singleton.gameState = new ConnectState();
}).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))) {
Game.singleton.GUI.ResetFocus();
Game.singleton.gameState = new OptionsState();
}
if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 + 70, 150, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("Exit", Game.singleton.config.lang), Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.White, Color.Red)))
{
if (!locked)
{
locked = true;
Game.singleton.GUI.ResetFocus();
Game.singleton.logger.Write("Game exit", Logger.logType.warm);
Game.singleton.gameState = new TitleState();
new Thread(() =>
{
while (!Utilities.DoubleTo(ref Game.singleton.background.speedX, 0, 0.1)) { Thread.Sleep(50); }
Game.singleton.logger.Join();
Game.singleton.Exit();
}).Start();
}
}
}
public override void Update()
{
Game.singleton.background.Update();
}
}
}

View File

@ -0,0 +1,54 @@
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using MyMonoGame.GUI;
using System.Threading;
namespace Galactic_Colors_Control_GUI.States
{
public class OptionsState : State
{
private bool locked = false;
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);
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();
}
if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 + 70, 150, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("Back", Game.singleton.config.lang), Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White)))
{
if (!locked)
{
locked = true;
Game.singleton.GUI.ResetFocus();
Game.singleton.config.Save();
new Thread(() =>
{
while (!Utilities.DoubleTo(ref Game.singleton.background.speedX, 1, 0.1)) { Thread.Sleep(20); }
Game.singleton.gameState = new MainMenuState();
}).Start();
}
}
}
public override void Update()
{
Game.singleton.background.Update();
}
private void ChangeLang()
{
if (Game.singleton.config.lang < Game.singleton.multilang.Langs.Count - 1)
{
Game.singleton.config.lang++;
}
else
{
Game.singleton.config.lang = 0;
}
}
}
}

View File

@ -0,0 +1,166 @@
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;
namespace Galactic_Colors_Control_GUI.States
{
public class PartyState : State
{
public struct Party
{
public int id;
public string text;
public Party(int ID, string TEXT)
{
id = ID;
text = TEXT;
}
}
private string password;
private int page = 1;
private List<Party> parties = new List<Party>();
private Message message;
private int id = -1;
private bool locked = false;
private bool showLoading = false;
private bool showOKMessage = false;
public PartyState()
{
UpdateParty();
}
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);
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.Label(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 50), Game.singleton.multilang.Get("Loading", Game.singleton.config.lang), Game.singleton.fonts.basic);
}
else
{
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 + 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; }
}
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 (!locked)
{
locked = true;
new Thread(UpdateParty).Start();
}
}
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) {
//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 - 250 + 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;
new Thread(PartyJoin).Start();
}
}
}
else
{
Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 2 - 240), Game.singleton.multilang.Get("AnyParty", Game.singleton.config.lang), Game.singleton.fonts.basic, null, Manager.textAlign.centerCenter);
}
if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 + 250, 150, 40), Game.singleton.buttonsSprites[0], Game.singleton.multilang.Get("Back", Game.singleton.config.lang), Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White)))
{
if (!locked)
{
locked = true;
Game.singleton.GUI.ResetFocus();
Game.singleton.client.ExitHost();
new Thread(() =>
{
while (!Utilities.DoubleTo(ref Game.singleton.background.speedX, 1, 0.1)) { Thread.Sleep(20); }
Game.singleton.gameState = new MainMenuState();
}).Start();
}
}
}
}
}
private void UpdateParty()
{
showLoading = true;
page = 1;
ResultData res = Game.singleton.client.Request(new string[2] { "party", "list" });
if (res.type == ResultTypes.OK) {
parties.Clear();
foreach (string str in res.result)
{
string[] data = str.Split(new char[1] { ':' }, 2);
int id = -1;
if (int.TryParse(data[0], out id))
{
parties.Add(new Party(id, data[1]));
}
}
}
else
{
parties = new List<Party>();
}
showLoading = false;
locked = false;
}
private void PartyJoin()
{
showLoading = true;
if (id != -1)
{
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)
{
Game.singleton.logger.Write("Join party " + id.ToString(), Logger.logType.info);
Game.singleton.gameState = new GameState();
}
else
{
Game.singleton.logger.Write("Join error " + res.result, Logger.logType.error);
message.title = Game.singleton.multilang.Get("Error", Game.singleton.config.lang);
message.text = Common.ArrayToString(res.result);
showOKMessage = true;
}
}
showLoading = false;
locked = false;
}
private void PartyCreate()
{
//TODO
}
public override void Update()
{
Game.singleton.background.Update();
}
}
}

View File

@ -0,0 +1,20 @@
using Microsoft.Xna.Framework.Graphics;
namespace Galactic_Colors_Control_GUI.States
{
/// <summary>
/// Game Menu Main Class
/// </summary>
public class State
{
public virtual void Draw(SpriteBatch spritebatch)
{
}
public virtual void Update()
{
}
}
}

View File

@ -0,0 +1,41 @@
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using MyMonoGame.GUI;
using System;
namespace Galactic_Colors_Control_GUI.States
{
/// <summary>
/// Only title in screen (and state change)
/// </summary>
public class TitleState : State
{
private DateTime _changeDate;
private State _target;
public TitleState()
{
_target = null;
}
public TitleState(State target, TimeSpan time)
{
_target = target;
_changeDate = DateTime.Now.Add(time);
}
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 / 2), Game.singleton.multilang.Get("GCC", Game.singleton.config.lang), Game.singleton.fonts.title, new MyMonoGame.Colors(Color.White), Manager.textAlign.centerCenter);
}
public override void Update()
{
if (_target != null)
{
if (DateTime.Now > _changeDate) { Game.singleton.gameState = _target; }
}
}
}
}

View File

@ -1,11 +1,24 @@
using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Graphics;
using System;
using System.IO; using System.IO;
namespace Galactic_Colors_Control_GUI namespace Galactic_Colors_Control_GUI
{ {
static class Utilities public struct Fonts
{ {
public SpriteFont small; //Text fonts
public SpriteFont basic;
public SpriteFont title;
}
internal static class Utilities
{
/// <summary>
/// Load Texture2D from files
/// </summary>
/// <param name="path">File .png path</param>
/// <param name="sprite">Result sprite</param>
static public void SpriteFromPng(string path, ref Texture2D sprite, GraphicsDevice graphics) static public void SpriteFromPng(string path, ref Texture2D sprite, GraphicsDevice graphics)
{ {
if (File.Exists(path)) if (File.Exists(path))
@ -17,6 +30,11 @@ namespace Galactic_Colors_Control_GUI
} }
} }
/// <summary>
/// Load SoundEffect from files
/// </summary>
/// <param name="path">File .mp3 path</param>
/// <param name="sound">Result sound</param>
static public void SoundFromMp3(string path, ref SoundEffect sound) static public void SoundFromMp3(string path, ref SoundEffect sound)
{ {
if (File.Exists(path)) if (File.Exists(path))
@ -27,5 +45,18 @@ namespace Galactic_Colors_Control_GUI
} }
} }
} }
public static bool DoubleTo(ref double value, double target, double speed)
{
speed = Math.Abs(speed);
bool up = value < target;
value += (up ? 1 : -1) * speed;
if ((up && value >= target) || (!up && value <= target))
{
value = target;
return true;
}
return false;
}
} }
} }

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<configuration> <configuration>
<startup> <startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup> </startup>
</configuration> </configuration>

View File

@ -0,0 +1,14 @@
namespace Galactic_Colors_Control_Server
{
public class Client
{
public int status = -1;
public string pseudo = "";
public int partyID = -1;
public Party party
{
get { if (partyID != -1) { return Program.parties[partyID]; } else { return null; } }
}
}
}

View File

@ -0,0 +1,26 @@
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
{
public class BroadcastCommand : ICommand
{
public string DescText { get { return "Sends message to all clients."; } }
public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } }
public string HelpText { get { return "Use 'broadcast [text]' to send message to all clients."; } }
public bool IsClient { get { return false; } }
public bool IsClientSide { get { return false; } }
public bool IsNoConnect { get { return false; } }
public bool IsServer { get { return true; } }
public int maxArgs { get { return 1; } }
public int minArgs { get { return 1; } }
public string Name { get { return "broadcast"; } }
public RequestResult Execute(string[] args, Socket soc, bool server = false)
{
Utilities.Broadcast(new EventData(EventTypes.ChatMessage, Common.Strings("Server : " + args[1])));
return new RequestResult(ResultTypes.OK);
}
}
}

View File

@ -1,4 +1,6 @@
using System; using Galactic_Colors_Control_Common;
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
@ -7,7 +9,8 @@ namespace Galactic_Colors_Control_Server.Commands
{ {
public string Name { get { return "clear"; } } public string Name { get { return "clear"; } }
public string DescText { get { return "Clears the console screen."; } } public string DescText { get { return "Clears the console screen."; } }
public string HelpText { get { return "Use /clear to execute Console.Clear()."; } } public string HelpText { get { return "Use 'clear' to execute Console.Clear()."; } }
public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } }
public bool IsServer { get { return true; } } public bool IsServer { get { return true; } }
public bool IsClient { get { return true; } } public bool IsClient { get { return true; } }
public bool IsClientSide { get { return true; } } public bool IsClientSide { get { return true; } }
@ -15,10 +18,18 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { get { return 0; } } public int minArgs { get { return 0; } }
public int maxArgs { get { return 0; } } public int maxArgs { get { return 0; } }
public void Execute(string[] args, Socket soc, bool server = false) public RequestResult Execute(string[] args, Socket soc, bool server = false)
{ {
Console.Clear(); if (server)
Console.Write(">"); {
Console.Clear();
Console.Write(">");
return new RequestResult(ResultTypes.OK);
}
else
{
return new RequestResult(ResultTypes.Error, Common.Strings("ClientSide"));
}
} }
} }
} }

View File

@ -0,0 +1,25 @@
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
{
public class ClientCountCommand : ICommand
{
public string Name { get { return "count"; } }
public string DescText { get { return "Counts connected clients."; } }
public string HelpText { get { return "Use 'client count' to show connected clients count and size"; } }
public Manager.CommandGroup Group { get { return Manager.CommandGroup.client; } }
public bool IsServer { get { return true; } }
public bool IsClient { get { return true; } }
public bool IsClientSide { get { return false; } }
public bool IsNoConnect { get { return false; } }
public int minArgs { get { return 0; } }
public int maxArgs { get { return 0; } }
public RequestResult Execute(string[] args, Socket soc, bool server = false)
{
return new RequestResult(ResultTypes.OK, Common.Strings(Program.clients.Count.ToString(), Program.config.size.ToString()));
}
}
}

View File

@ -0,0 +1,43 @@
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
{
public class ClientKickCommand : ICommand
{
public string Name { get { return "kick"; } }
public string DescText { get { return "Kicks selected client."; } }
public string HelpText { get { return "Use 'client kick [username] <reason>' to kick client from server."; } }
public Manager.CommandGroup Group { get { return Manager.CommandGroup.client; } }
public bool IsServer { get { return true; } }
public bool IsClient { get { return false; } }
public bool IsClientSide { get { return false; } }
public bool IsNoConnect { get { return true; } }
public int minArgs { get { return 1; } }
public int maxArgs { get { return 2; } }
public RequestResult Execute(string[] args, Socket soc, bool server = false)
{
Socket target = null;
foreach (Socket client in Program.clients.Keys)
{
if (Utilities.GetName(client) == args[2]) { target = client; }
}
if (target == null)
return new RequestResult(ResultTypes.Error, Common.Strings("CantFind"));
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])));
Program.logger.Write("because" + args[3], Logger.logType.debug);
}
else
{
Utilities.Send(target, new EventData(EventTypes.ServerKick));
}
return new RequestResult(ResultTypes.OK);
}
}
}

View File

@ -0,0 +1,45 @@
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
{
public class ClientListCommand : ICommand
{
public string Name { get { return "list"; } }
public string DescText { get { return "Lists connected clients."; } }
public string HelpText { get { return "Use 'client list' to display all connected client username or IP."; } }
public Manager.CommandGroup Group { get { return Manager.CommandGroup.client; } }
public bool IsServer { get { return true; } }
public bool IsClient { get { return true; } }
public bool IsClientSide { get { return false; } }
public bool IsNoConnect { get { return false; } }
public int minArgs { get { return 0; } }
public int maxArgs { get { return 0; } }
public RequestResult Execute(string[] args, Socket soc, bool server = false)
{
if (server)
{
string text = " ";
foreach (Socket socket in Program.clients.Keys)
{
text += (Utilities.GetName(socket) + ", ");
}
text = text.Remove(text.Length - 2, 2);
return new RequestResult(ResultTypes.OK, Common.Strings(text));
}
else
{
string[] data = new string[Program.clients.Count];
int i = 0;
foreach (Socket socket in Program.clients.Keys)
{
data[i] = (Utilities.GetName(socket) + ", ");
i++;
}
return new RequestResult(ResultTypes.OK, data);
}
}
}
}

View File

@ -0,0 +1,42 @@
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System;
using System.Net;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
{
public class ClientStatusCommand : ICommand
{
public string Name { get { return "status"; } }
public string DescText { get { return "Get client status."; } }
public string HelpText { get { return "Use 'client status [username]' to show client status."; } }
public Manager.CommandGroup Group { get { return Manager.CommandGroup.client; } }
public bool IsServer { get { return true; } }
public bool IsClient { get { return false; } }
public bool IsClientSide { get { return false; } }
public bool IsNoConnect { get { return false; } }
public int minArgs { get { return 1; } }
public int maxArgs { get { return 1; } }
public RequestResult Execute(string[] args, Socket soc, bool server = false)
{
Socket target = null;
foreach (Socket client in Program.clients.Keys)
{
if (Utilities.GetName(client) == args[2]) { target = client; }
}
if (target == null)
return new RequestResult(ResultTypes.Error, Common.Strings("CantFind"));
string text = "";
text += ("Name : " + Utilities.GetName(target) + Environment.NewLine);
text += ("IP : " + ((IPEndPoint)target.LocalEndPoint).Address.ToString() + Environment.NewLine);
if (Program.clients[target].party != null)
{
text += ("Party : " + Program.clients[target].party + Environment.NewLine);
}
return new RequestResult(ResultTypes.OK, Common.Strings(text));
}
}
}

View File

@ -1,31 +0,0 @@
using System;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
{
public class CloseCommand : ICommand
{
public string Name { get { return "close"; } }
public string DescText { get { return "Closes server from connections."; } }
public string HelpText { get { return "Use /close to stop connection process"; } }
public bool IsServer { get { return true; } }
public bool IsClient { get { return false; } }
public bool IsClientSide { get { return false; } }
public bool IsNoConnect { get { return false; } }
public int minArgs { get { return 0; } }
public int maxArgs { get { return 0; } }
public void Execute(string[] args, Socket soc, bool server = false)
{
if (Program._open)
{
Program._open = false;
Logger.Write("Server closed", Logger.logType.warm);
}
else
{
Utilities.ConsoleWrite("Server already close");
}
}
}
}

View File

@ -1,4 +1,5 @@
using System; using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System.Net; using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
@ -8,7 +9,8 @@ namespace Galactic_Colors_Control_Server.Commands
{ {
public string Name { get { return "connect"; } } public string Name { get { return "connect"; } }
public string DescText { get { return "Gets an username."; } } public string DescText { get { return "Gets an username."; } }
public string HelpText { get { return "Use /connect [username] to start identification"; } } public string HelpText { get { return "Use 'connect [username]' to start identification"; } }
public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } }
public bool IsServer { get { return false; } } public bool IsServer { get { return false; } }
public bool IsClient { get { return true; } } public bool IsClient { get { return true; } }
public bool IsClientSide { get { return false; } } public bool IsClientSide { get { return false; } }
@ -16,34 +18,29 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { get { return 1; } } public int minArgs { get { return 1; } }
public int maxArgs { get { return 1; } } public int maxArgs { get { return 1; } }
public void Execute(string[] args, Socket soc, bool server = false) public RequestResult Execute(string[] args, Socket soc, bool server = false)
{ {
if (!Utilities.IsConnect(soc)) if (Utilities.IsConnect(soc))
return new RequestResult(ResultTypes.Error, Common.Strings("Connected"));
if (args[1].Length < 3)
return new RequestResult(ResultTypes.Error, Common.Strings("TooShort"));
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)
{ {
Logger.Write("Identifiaction request from " + Utilities.GetName(soc), Logger.logType.debug); if (client.pseudo == args[1]) { allreadyconnected = true; break; }
bool allreadyconnected = false;
foreach(Data client in Program.clients.Values)
{
if(client.pseudo == args[1]) { allreadyconnected = true; break; }
}
if (!allreadyconnected)
{
Program.clients[soc].status = 0;
//args[1] = args[1][0].ToString().ToUpper()[0] + args[1].Substring(1);
Program.clients[soc].pseudo = args[1];
Utilities.Send(soc, "/connected", Utilities.dataType.message);
Utilities.Broadcast(args[1] + " joined the server", Utilities.dataType.message);
Logger.Write("Identified as " + Utilities.GetName(soc) + " form " + ((IPEndPoint)soc.LocalEndPoint).Address.ToString(), Logger.logType.info);
}
else
{
Utilities.Send(soc, "/allreadytaken", Utilities.dataType.message);
}
}
else
{
Utilities.Send(soc, "You are allready " + Utilities.GetName(soc), Utilities.dataType.message);
} }
if (allreadyconnected)
return new RequestResult(ResultTypes.Error, Common.Strings("AllreadyTaken"));
Program.clients[soc].status = 0;
Program.clients[soc].pseudo = args[1];
Utilities.Broadcast(new EventData(EventTypes.ServerJoin, Common.Strings(args[1])));
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

@ -1,23 +0,0 @@
using System;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
{
public class CountCommand : ICommand
{
public string Name { get { return "count"; } }
public string DescText { get { return "Counts connected clients."; } }
public string HelpText { get { return "Use /count to show connected clients count and size"; } }
public bool IsServer { get { return true; } }
public bool IsClient { get { return false; } }
public bool IsClientSide { get { return false; } }
public bool IsNoConnect { get { return false; } }
public int minArgs { get { return 0; } }
public int maxArgs { get { return 0; } }
public void Execute(string[] args, Socket soc, bool server = false)
{
Utilities.ConsoleWrite(Program.clients.Count + "/" + Program.config.size);
}
}
}

View File

@ -1,4 +1,5 @@
using System; using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System.Net.Sockets; using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands namespace Galactic_Colors_Control_Server.Commands
@ -6,33 +7,27 @@ namespace Galactic_Colors_Control_Server.Commands
public class ExitCommand : ICommand public class ExitCommand : ICommand
{ {
public string Name { get { return "exit"; } } public string Name { get { return "exit"; } }
public string DescText { get { return "Leave the program."; } } public string DescText { get { return "Leave the server."; } }
public string HelpText { get { return "Use /exit to stop actual program."; } } public string HelpText { get { return "Use 'exit' to stop actual program."; } }
public bool IsServer { get { return true; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } }
public bool IsServer { get { return false; } }
public bool IsClient { get { return true; } } public bool IsClient { get { return true; } }
public bool IsClientSide { get { return false; } } public bool IsClientSide { get { return false; } }
public bool IsNoConnect { get { return true; } } public bool IsNoConnect { get { return true; } }
public int minArgs { get { return 0; } } public int minArgs { get { return 0; } }
public int maxArgs { get { return 0; } } public int maxArgs { get { return 0; } }
public void Execute(string[] args, Socket soc, bool server = false) public RequestResult Execute(string[] args, Socket soc, bool server = false)
{ {
if (server) soc.Shutdown(SocketShutdown.Both);
{ Program.logger.Write("Client disconnected from " + Utilities.GetName(soc), Logger.logType.info);
Program._run = false; string username = Utilities.GetName(soc);
Utilities.ConsoleWrite("Exit server"); bool connected = Program.clients[soc].status != -1;
} soc.Close();
else Program.clients.Remove(soc);
{ if (connected) { Utilities.Broadcast(new EventData(EventTypes.ServerLeave, Common.Strings(username))); }
soc.Shutdown(SocketShutdown.Both); Program.logger.Write("Size: " + Program.clients.Count + "/" + Program.config.size, Logger.logType.debug);
Logger.Write("Client disconnected from " + Utilities.GetName(soc), Logger.logType.info); return new RequestResult(ResultTypes.OK);
string username = Utilities.GetName(soc);
bool connected = Program.clients[soc].status != -1;
soc.Close();
Program.clients.Remove(soc);
if (connected) { Utilities.Broadcast(username + " leave the server", Utilities.dataType.message); }
Logger.Write("Size: " + Program.clients.Count + "/" + Program.config.size, Logger.logType.debug);
}
} }
} }
} }

View File

@ -1,4 +1,6 @@
using System; using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net.Sockets; using System.Net.Sockets;
@ -9,54 +11,68 @@ namespace Galactic_Colors_Control_Server.Commands
{ {
public string Name { get { return "help"; } } public string Name { get { return "help"; } }
public string DescText { get { return "Shows the help."; } } public string DescText { get { return "Shows the help."; } }
public string HelpText { get { return "Use /help [command] to display command help."; } } public string HelpText { get { return "Use 'help [command]' to display command help. ('hell -all' for full help)"; } }
public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } }
public bool IsServer { get { return true; } } public bool IsServer { get { return true; } }
public bool IsClient { get { return true; } } public bool IsClient { get { return true; } }
public bool IsClientSide { get { return false; } } public bool IsClientSide { get { return false; } }
public bool IsNoConnect { get { return false; } } public bool IsNoConnect { get { return false; } }
public int minArgs { get { return 0; } } public int minArgs { get { return 0; } }
public int maxArgs { get { return 1; } } public int maxArgs { get { return 2; } }
public void Execute(string[] args, Socket soc, bool server = false) public RequestResult Execute(string[] args, Socket soc, bool server = false)
{ {
if(args.Length == 1) bool isGroup = false;
bool isAll = false;
if (args.Length == 2)
{
isGroup = Enum.GetNames(typeof(Manager.CommandGroup)).Contains(args[1]);
isAll = (args[1] == "-all");
}
if (args.Length == 1 || (isGroup || isAll))
{ {
List<string> list = new List<string>();
int maxLen = 0; int maxLen = 0;
foreach (string com in Manager.commands.Keys) List<ICommand> list = new List<ICommand>();
foreach (ICommand com in Manager.commands)
{ {
if(Manager.CanAccess(Manager.commands[com], soc, server)) if (Manager.CanAccess(com, soc, server))
{ {
list.Add(com); if (!isGroup || (isGroup && com.Group == (Manager.CommandGroup)Enum.Parse(typeof(Manager.CommandGroup), args[1])))
if(com.Length > maxLen) { maxLen = com.Length; } {
list.Add(com);
if (com.Name.Length + (com.Group == 0 ? 0 : 4) > maxLen) { maxLen = com.Name.Length + (com.Group == 0 ? 0 : 4); }
}
} }
} }
list.Sort(); list.Sort((x, y) => x.Group.CompareTo(y.Group));
string text = "Use /help [command] for more informations." + Environment.NewLine + "Available commands:" + Environment.NewLine; string text = "Use 'help [command]' for more informations." + Environment.NewLine + "Available commands:" + Environment.NewLine;
foreach (var key in list) Manager.CommandGroup actualGroup = 0;
foreach (ICommand com in list)
{ {
text += (" " + key + new string(' ', maxLen - key.Length) + " : " + Manager.commands[key].DescText + Environment.NewLine); if (com.Group != actualGroup)
{
text += (Environment.NewLine + " " + com.Group.ToString() + Environment.NewLine + ((isGroup || isAll) ? "" : (" Use 'help " + com.Group.ToString() + "'")));
actualGroup = com.Group;
}
if ((!(isGroup || isAll) && com.Group == 0) || (isGroup || isAll))
{
text += (" " + (com.Group != 0 ? new string(' ', 4) : "") + com.Name + new string(' ', maxLen - com.Name.Length - (com.Group == 0 ? 0 : 4)) + " : " + com.DescText + Environment.NewLine);
}
} }
Utilities.Return(text, soc, server); return new RequestResult(ResultTypes.OK, Common.Strings(text));
} }
else else
{ {
if (Manager.commands.ContainsKey(args[1])) ICommand command = null;
{ args = args.Skip(1).ToArray();
if (Manager.CanAccess(Manager.commands[args[1]], soc, server)) if (!Manager.TryGetCommand(args, ref command))
{ return new RequestResult(ResultTypes.Error, Common.Strings("AnyCommand"));
Utilities.Return(Manager.commands[args[1]].HelpText, soc, server);
} if (!Manager.CanAccess(command, soc, server))
else return new RequestResult(ResultTypes.Error, Common.Strings("AnyCommand"));
{
Utilities.Return("Any help for " + args[1], soc, server); return new RequestResult(ResultTypes.OK, Common.Strings(command.HelpText));
}
}
else
{
Utilities.Return("Any help for " + args[1], soc, server);
}
} }
} }
} }
} }

View File

@ -1,4 +1,5 @@
using System.Net.Sockets; using Galactic_Colors_Control_Common.Protocol;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands namespace Galactic_Colors_Control_Server.Commands
{ {
@ -7,6 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands
string Name { get; } string Name { get; }
string DescText { get; } string DescText { get; }
string HelpText { get; } string HelpText { get; }
Manager.CommandGroup Group { get; }
bool IsServer { get; } bool IsServer { get; }
bool IsClient { get; } bool IsClient { get; }
bool IsClientSide { get; } bool IsClientSide { get; }
@ -14,6 +16,6 @@ namespace Galactic_Colors_Control_Server.Commands
int minArgs { get; } int minArgs { get; }
int maxArgs { get; } int maxArgs { get; }
void Execute(string[] args, Socket soc = null, bool server = false); RequestResult Execute(string[] args, Socket soc = null, bool server = false);
} }
} }

View File

@ -1,45 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
{
public class KickCommand : ICommand
{
public string Name { get { return "kick"; } }
public string DescText { get { return "Kicks selected client."; } }
public string HelpText { get { return "Use /kick [username] <reason> to kick client from server."; } }
public bool IsServer { get { return true; } }
public bool IsClient { get { return false; } }
public bool IsClientSide { get { return false; } }
public bool IsNoConnect { get { return true; } }
public int minArgs { get { return 1; } }
public int maxArgs { get { return 2; } }
public void Execute(string[] args, Socket soc, bool server = false)
{
Socket target = null;
foreach(Socket client in Program.clients.Keys)
{
if(Utilities.GetName(client) == args[1]) { target = client; }
}
if (target != null)
{
Logger.Write(args[1] + " was kick by server.", Logger.logType.info);
if (args.Length > 2)
{
Utilities.Send(target, "/kick " + args[2], Utilities.dataType.message);
Logger.Write("because" + args[1], Logger.logType.debug);
}
else {
Utilities.Send(target, "/kick", Utilities.dataType.message);
}
}
else
{
Utilities.Return("Can't find " + args[1], soc, server);
}
}
}
}

View File

@ -1,29 +0,0 @@
using System;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
{
public class ListCommand : ICommand
{
public string Name { get { return "list"; } }
public string DescText { get { return "Lists connected clients."; } }
public string HelpText { get { return "Use /list to display all connected client username or IP."; } }
public bool IsServer { get { return true; } }
public bool IsClient { get { return false; } }
public bool IsClientSide { get { return false; } }
public bool IsNoConnect { get { return false; } }
public int minArgs { get { return 0; } }
public int maxArgs { get { return 0; } }
public void Execute(string[] args, Socket soc, bool server = false)
{
string text = " ";
foreach (Socket socket in Program.clients.Keys)
{
text += (Utilities.GetName(socket) + ", ");
}
text = text.Remove(text.Length - 2, 2);
Utilities.ConsoleWrite(text);
}
}
}

View File

@ -1,4 +1,6 @@
using System; using Galactic_Colors_Control_Common;
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
@ -7,7 +9,8 @@ namespace Galactic_Colors_Control_Server.Commands
{ {
public string Name { get { return "loglevel"; } } public string Name { get { return "loglevel"; } }
public string DescText { get { return "Change console loglevel."; } } public string DescText { get { return "Change console loglevel."; } }
public string HelpText { get { return "Use /loglevel [loglevel] to change Loglevel."; } } public string HelpText { get { return "Use 'loglevel [loglevel]' to change Loglevel. (dev ,debug, info, warm, error, fatal)"; } }
public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } }
public bool IsServer { get { return true; } } public bool IsServer { get { return true; } }
public bool IsClient { get { return false; } } public bool IsClient { get { return false; } }
public bool IsClientSide { get { return true; } } public bool IsClientSide { get { return true; } }
@ -15,16 +18,17 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { get { return 1; } } public int minArgs { get { return 1; } }
public int maxArgs { get { return 1; } } public int maxArgs { get { return 1; } }
public void Execute(string[] args, Socket soc, bool server = false) public RequestResult Execute(string[] args, Socket soc, bool server = false)
{ {
if (Enum.TryParse(args[1], true, out Program.config.logLevel)) if (Enum.TryParse(args[1], true, out Program.config.logLevel))
{ {
Utilities.ConsoleWrite("LogLevel: " + Program.config.logLevel.ToString()); Program.logger.ChangeLevel(Program.config.logLevel);
return new RequestResult(ResultTypes.OK, Common.Strings(Program.config.logLevel.ToString()));
} }
else else
{ {
Utilities.ConsoleWrite("Incorrect argument (debug, info, important, error, fatal)"); return new RequestResult(ResultTypes.Error, Common.Strings("IncorrectArgs"));
} }
} }
} }
} }

View File

@ -1,4 +1,6 @@
using System; using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net.Sockets; using System.Net.Sockets;
@ -6,9 +8,13 @@ using System.Reflection;
namespace Galactic_Colors_Control_Server.Commands namespace Galactic_Colors_Control_Server.Commands
{ {
class Manager public class Manager
{ {
public static Dictionary<string, ICommand> commands { get; private set; } = new Dictionary<string, ICommand>(); public static List<ICommand> commands { get; private set; } = new List<ICommand>();
public enum CommandGroup { root, server, party, client }
private static RequestResult AnyCommand = new RequestResult(ResultTypes.Error, Common.Strings("AnyCommand"));
/// <summary> /// <summary>
/// Find all ICommand and add them to commands /// Find all ICommand and add them to commands
@ -19,8 +25,8 @@ namespace Galactic_Colors_Control_Server.Commands
IEnumerable<ICommand> coms = Assembly.GetExecutingAssembly().GetTypes().Where(x => x.GetInterfaces().Contains(typeof(ICommand)) && x.GetConstructor(Type.EmptyTypes) != null).Select(x => Activator.CreateInstance(x) as ICommand); IEnumerable<ICommand> coms = Assembly.GetExecutingAssembly().GetTypes().Where(x => x.GetInterfaces().Contains(typeof(ICommand)) && x.GetConstructor(Type.EmptyTypes) != null).Select(x => Activator.CreateInstance(x) as ICommand);
foreach (ICommand com in coms) foreach (ICommand com in coms)
{ {
commands.Add(com.Name, com); commands.Add(com);
Logger.Write("Added command " + com.GetType().Name, Logger.logType.debug); Program.logger.Write("Added command " + com.Group.ToString() + " " + com.Name, Logger.logType.debug);
} }
} }
@ -30,45 +36,97 @@ namespace Galactic_Colors_Control_Server.Commands
/// <param name="args">command with args</param> /// <param name="args">command with args</param>
/// <param name="soc">Sender socket</param> /// <param name="soc">Sender socket</param>
/// <param name="server">Is server?</param> /// <param name="server">Is server?</param>
public static void Execute(string[] args, Socket soc = null, bool server = false) public static RequestResult Execute(string[] args, Socket soc = null, bool server = false)
{ {
if (commands.ContainsKey(args[0])) ICommand command = null;
{ if (!TryGetCommand(args, ref command))
ICommand command = commands[args[0]]; return AnyCommand;
if (CanAccess(command, soc, server))
{
if (command.IsClientSide)
{
Utilities.Return("It's a client side command", soc, server);
}
else
{
if (args.Length > command.minArgs)
{
if (args.Length - 1 <= command.maxArgs)
{
command.Execute(args, soc, server);
}
else
{
Utilities.Return("Command " + command.Name + " require at most " + command.minArgs + " argument(s).", soc, server);
}
}
else if (!CanAccess(command, soc, server))
{ return AnyCommand;
Utilities.Return("Command " + command.Name + " require at least " + command.minArgs + " argument(s).", soc, server);
} if (!server && command.IsClientSide)
return new RequestResult(ResultTypes.Error, Common.Strings("ClientSide"));
if (args.Length - (command.Group == 0 ? 0 : 1) <= command.minArgs)
return new RequestResult(ResultTypes.Error, new string[2] { "TooShort", command.minArgs.ToString() });
if (args.Length - (command.Group == 0 ? 1 : 2) > command.maxArgs)
return new RequestResult(ResultTypes.Error, new string[2] { "TooLong", command.maxArgs.ToString() });
try
{
return command.Execute(args, soc, server);
}
catch (Exception e)
{
Program.logger.Write("Command " + args[0] + " Exception : " + e.Message, Logger.logType.error);
return new RequestResult(ResultTypes.Error, Common.Strings("ExecuteException"));
}
}
public static string CommandToString(ICommand command)
{
string text = "";
if (command.Group != 0) { text += (command.Group.ToString() + " "); }
text += command.Name;
return text;
}
/// <summary>
/// Convert command args in readable string
/// </summary>
/// <param name="args">Command args</param>
public static string CommandToString(string[] args)
{
if (args.Length > 0)
{
string text = "";
foreach (string arg in args)
{
text += (arg + " ");
}
return text;
}
else
{
return null;
}
}
/// <summary>
/// Try to get a command
/// </summary>
/// <param name="args">command args</param>
/// <param name="command">Command result</param>
/// <returns>Correct command</returns>
public static bool TryGetCommand(string[] args, ref ICommand command)
{
if (args.Length > 0)
{
List<string> groups = Enum.GetNames(typeof(CommandGroup)).ToList();
CommandGroup group = 0;
if (groups.Contains(args[0]))
{
if (args.Length > 1)
{
group = (CommandGroup)Enum.Parse(typeof(CommandGroup), args[0]);
} }
} }
IEnumerable<ICommand> coms = commands.Where(p => (p.Name == args[group == 0 ? 0 : 1] && p.Group == group));
if (coms.Count() == 1)
{
command = coms.First();
return true;
}
else else
{ {
Utilities.Return("Unknown command : " + args[0], soc, server); return false;
} }
} }
else else
{ {
Utilities.Return("Unknown command : " + args[0], soc, server); return false;
} }
} }
@ -85,7 +143,7 @@ namespace Galactic_Colors_Control_Server.Commands
{ {
if (command.IsClient) if (command.IsClient)
{ {
if(!Utilities.IsConnect(soc)) if (!Utilities.IsConnect(soc))
{ {
return command.IsNoConnect; return command.IsNoConnect;
} }
@ -101,4 +159,4 @@ namespace Galactic_Colors_Control_Server.Commands
} }
} }
} }
} }

View File

@ -1,31 +0,0 @@
using System;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
{
public class OpenCommand : ICommand
{
public string Name { get { return "open"; } }
public string DescText { get { return "Opens server for connections."; } }
public string HelpText { get { return "Use /open to restart connection process"; } }
public bool IsServer { get { return true; } }
public bool IsClient { get { return false; } }
public bool IsClientSide { get { return false; } }
public bool IsNoConnect { get { return false; } }
public int minArgs { get { return 0; } }
public int maxArgs { get { return 0; } }
public void Execute(string[] args, Socket soc, bool server = false)
{
if (!Program._open)
{
Program._open = true;
Logger.Write("Server opened", Logger.logType.warm);
}
else
{
Utilities.ConsoleWrite("Server already open");
}
}
}
}

View File

@ -0,0 +1,36 @@
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
{
public class PartyClientCommand : ICommand
{
public string Name { get { return "client"; } }
public string DescText { get { return "Lists party clients."; } }
public string HelpText { get { return "Use 'party client' to show party clients list."; } }
public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } }
public bool IsServer { get { return true; } }
public bool IsClient { get { return true; } }
public bool IsClientSide { get { return false; } }
public bool IsNoConnect { get { return false; } }
public int minArgs { get { return 0; } }
public int maxArgs { get { return 0; } }
public RequestResult Execute(string[] args, Socket soc, bool server = false)
{
int partyId = -1;
if (!Utilities.AccessParty(ref partyId, args, false, soc, server))
return new RequestResult(ResultTypes.Error, Common.Strings("Access"));
string[] data = new string[Program.parties[partyId].clients.Count];
int i = 0;
foreach (Socket client in Program.parties[partyId].clients)
{
data[i] = Utilities.GetName(client);
i++;
}
return new RequestResult(ResultTypes.OK, data);
}
}
}

View File

@ -0,0 +1,33 @@
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
{
public class PartyCloseCommand : ICommand
{
public string Name { get { return "close"; } }
public string DescText { get { return "Closes party."; } }
public string HelpText { get { return "Use 'party close' to close party for join."; } }
public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } }
public bool IsServer { get { return true; } }
public bool IsClient { get { return true; } }
public bool IsClientSide { get { return false; } }
public bool IsNoConnect { get { return false; } }
public int minArgs { get { return 0; } }
public int maxArgs { get { return 0; } }
public RequestResult Execute(string[] args, Socket soc, bool server = false)
{
int partyId = -1;
if (!Utilities.AccessParty(ref partyId, args, true, soc, server))
return new RequestResult(ResultTypes.Error, Common.Strings("Access"));
if (!Program.parties[partyId].open)
return new RequestResult(ResultTypes.Error, Common.Strings("Allready"));
Program.parties[partyId].open = false;
return new RequestResult(ResultTypes.OK);
}
}
}

View File

@ -0,0 +1,51 @@
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
{
public class PartyCreateCommand : ICommand
{
public string Name { get { return "create"; } }
public string DescText { get { return "Create new party."; } }
public string HelpText { get { return "Use 'party create [name] [size]' to create new party."; } }
public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } }
public bool IsServer { get { return true; } }
public bool IsClient { get { return true; } }
public bool IsClientSide { get { return false; } }
public bool IsNoConnect { get { return false; } }
public int minArgs { get { return 2; } }
public int maxArgs { get { return 2; } }
public RequestResult Execute(string[] args, Socket soc, bool server = false)
{
if (!server && Program.clients[soc].partyID != -1)
return new RequestResult(ResultTypes.Error, Common.Strings("Allready"));
int size;
if (!int.TryParse(args[3], out size))
return new RequestResult(ResultTypes.Error, Common.Strings("Format"));
if (size < 1)
return new RequestResult(ResultTypes.Error, Common.Strings("TooSmall"));
if (size > Program.config.size)
return new RequestResult(ResultTypes.Error, Common.Strings("TooBig"));
if (Program.parties.Count >= Program.config.partysize)
return new RequestResult(ResultTypes.Error, Common.Strings("Full"));
Program.AddParty(new Party(args[2], size, Utilities.GetName(soc)));
Program.logger.Write("Party " + args[2] + " create with " + size + " slots as " + Program.GetPartyID(false), Logger.logType.info);
if (server)
{
Program.selectedParty = Program.GetPartyID(false);
}
else
{
Program.clients[soc].partyID = Program.GetPartyID(false);
}
return new RequestResult(ResultTypes.OK, new string[3] { args[2], size.ToString(), (Program.GetPartyID(false)).ToString() });
}
}
}

View File

@ -0,0 +1,61 @@
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
{
public class PartyJoinCommand : ICommand
{
public string Name { get { return "join"; } }
public string DescText { get { return "Join a party."; } }
public string HelpText { get { return "Use 'party join [id] <password>' to join a party."; } }
public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } }
public bool IsServer { get { return true; } }
public bool IsClient { get { return true; } }
public bool IsClientSide { get { return false; } }
public bool IsNoConnect { get { return false; } }
public int minArgs { get { return 1; } }
public int maxArgs { get { return 2; } }
public RequestResult Execute(string[] args, Socket soc, bool server = false)
{
if ((server && Program.selectedParty != -1) || (!server && Program.clients[soc].partyID != -1))
return new RequestResult(ResultTypes.Error, Common.Strings("Allready"));
int id;
if (!int.TryParse(args[2], out id))
return new RequestResult(ResultTypes.Error, Common.Strings("Format"));
if (!Program.parties.ContainsKey(id))
return new RequestResult(ResultTypes.Error, Common.Strings("CantFind"));
Party party = Program.parties[id];
if (args.Length == 3)
{
Array.Resize(ref args, 4);
args[3] = "";
}
if (!server && !party.TestPassword(args[3]))
return new RequestResult(ResultTypes.Error, Common.Strings("Password"));
if (server)
{
Program.selectedParty = id;
return new RequestResult(ResultTypes.OK);
}
else
{
if (!party.open)
return new RequestResult(ResultTypes.Error, Common.Strings("Close"));
if (party.clients.Count + 1 > party.size)
return new RequestResult(ResultTypes.Error, Common.Strings("Full"));
Program.clients[soc].partyID = id;
Utilities.BroadcastParty(new EventData(EventTypes.PartyJoin, Common.Strings(Utilities.GetName(soc))), id);
return new RequestResult(ResultTypes.OK);
}
}
}
}

View File

@ -0,0 +1,38 @@
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
{
public class PartyKickCommand : ICommand
{
public string Name { get { return "kick"; } }
public string DescText { get { return "Kick player from party."; } }
public string HelpText { get { return "Use 'party kick [name] <reason>' to kick palyer from party"; } }
public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } }
public bool IsServer { get { return true; } }
public bool IsClient { get { return true; } }
public bool IsClientSide { get { return false; } }
public bool IsNoConnect { get { return false; } }
public int minArgs { get { return 1; } }
public int maxArgs { get { return 2; } }
public RequestResult Execute(string[] args, Socket soc, bool server = false)
{
int partyId = -1;
if (!Utilities.AccessParty(ref partyId, args, true, soc, server))
return new RequestResult(ResultTypes.Error, Common.Strings("Access"));
Socket target = null;
foreach (Socket client in Program.parties[partyId].clients)
{
if (Utilities.GetName(client) == args[2]) { target = client; }
}
if (target == null)
return new RequestResult(ResultTypes.Error, Common.Strings("CantFind"));
Utilities.Send(target, new EventData(EventTypes.PartyKick, args.Length > 3 ? Common.Strings(args[2]) : null));
return Manager.Execute(new string[2] { "party", "leave" }, target, false);
}
}
}

View File

@ -0,0 +1,42 @@
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
{
public class PartyLeaveCommand : ICommand
{
public string Name { get { return "leave"; } }
public string DescText { get { return "Leave party."; } }
public string HelpText { get { return "Use 'party leave' to leave current party"; } }
public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } }
public bool IsServer { get { return true; } }
public bool IsClient { get { return true; } }
public bool IsClientSide { get { return false; } }
public bool IsNoConnect { get { return false; } }
public int minArgs { get { return 0; } }
public int maxArgs { get { return 0; } }
public RequestResult Execute(string[] args, Socket soc, bool server = false)
{
if (server)
{
Program.selectedParty = -1;
return new RequestResult(ResultTypes.OK);
}
else
{
int partyId = -1;
if (!Utilities.AccessParty(ref partyId, args, false, soc, server))
return new RequestResult(ResultTypes.Error, Common.Strings("Access"));
if (Program.parties[partyId].IsOwner(Utilities.GetName(soc)))
return new RequestResult(ResultTypes.Error, Common.Strings("Owner"));
Program.clients[soc].partyID = -1;
Utilities.BroadcastParty(new EventData(EventTypes.PartyLeave, Common.Strings(Utilities.GetName(soc))), partyId);
return new RequestResult(ResultTypes.OK);
}
}
}
}

View File

@ -0,0 +1,37 @@
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
{
public class PartyListCommand : ICommand
{
public string Name { get { return "list"; } }
public string DescText { get { return "Shows parties list."; } }
public string HelpText { get { return "Use 'party list' to show parties list."; } }
public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } }
public bool IsServer { get { return true; } }
public bool IsClient { get { return true; } }
public bool IsClientSide { get { return false; } }
public bool IsNoConnect { get { return false; } }
public int minArgs { get { return 0; } }
public int maxArgs { get { return 0; } }
public RequestResult Execute(string[] args, Socket soc, bool server = false)
{
if (Program.parties.Keys.Count == 0)
return new RequestResult(ResultTypes.Error, Common.Strings("AnyParty"));
string[] text = new string[Program.parties.Keys.Count];
int i = 0;
foreach (int key in Program.parties.Keys)
{
Party party = Program.parties[key];
text[i] = (key + " : " + party.name + " : " + party.count + "/" + party.size + " : " + (party.open ? (party.isPrivate ? "private" : "open") : "close"));
i++;
}
return new RequestResult(ResultTypes.OK, text);
}
}
}

View File

@ -0,0 +1,33 @@
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
{
public class PartyOpenCommand : ICommand
{
public string Name { get { return "open"; } }
public string DescText { get { return "Opens party."; } }
public string HelpText { get { return "Use 'party open' to open party for join."; } }
public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } }
public bool IsServer { get { return true; } }
public bool IsClient { get { return true; } }
public bool IsClientSide { get { return false; } }
public bool IsNoConnect { get { return false; } }
public int minArgs { get { return 0; } }
public int maxArgs { get { return 0; } }
public RequestResult Execute(string[] args, Socket soc, bool server = false)
{
int partyId = -1;
if (!Utilities.AccessParty(ref partyId, args, true, soc, server))
return new RequestResult(ResultTypes.Error, Common.Strings("Access"));
if (Program.parties[partyId].open)
return new RequestResult(ResultTypes.Error, Common.Strings("Allready"));
Program.parties[partyId].open = true;
return new RequestResult(ResultTypes.OK);
}
}
}

View File

@ -0,0 +1,39 @@
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
{
public class PartyPasswordCommand : ICommand
{
public string Name { get { return "password"; } }
public string DescText { get { return "Set party password."; } }
public string HelpText { get { return "Use 'party password [newPass] <oldPass>' to set party private with password."; } }
public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } }
public bool IsServer { get { return true; } }
public bool IsClient { get { return true; } }
public bool IsClientSide { get { return false; } }
public bool IsNoConnect { get { return false; } }
public int minArgs { get { return 1; } }
public int maxArgs { get { return 2; } }
public RequestResult Execute(string[] args, Socket soc, bool server = false)
{
int partyId = -1;
if (!Utilities.AccessParty(ref partyId, args, true, soc, server))
return new RequestResult(ResultTypes.Error, Common.Strings("Access"));
if (args.Length == 3)
{
Array.Resize(ref args, 4);
args[3] = "";
}
if (!Program.parties[partyId].SetPassword(args[2], args[3]))
return new RequestResult(ResultTypes.Error, Common.Strings("Password"));
return new RequestResult(ResultTypes.OK);
}
}
}

View File

@ -0,0 +1,42 @@
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
{
public class PartyStatusCommand : ICommand
{
public string Name { get { return "status"; } }
public string DescText { get { return "Shows party status."; } }
public string HelpText { get { return "Use 'party status' to show party status."; } }
public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } }
public bool IsServer { get { return true; } }
public bool IsClient { get { return true; } }
public bool IsClientSide { get { return false; } }
public bool IsNoConnect { get { return false; } }
public int minArgs { get { return 0; } }
public int maxArgs { get { return 0; } }
public RequestResult Execute(string[] args, Socket soc, bool server = false)
{
int partyId = -1;
if (!Utilities.AccessParty(ref partyId, args, false, soc, server))
return new RequestResult(ResultTypes.Error, Common.Strings("Access"));
Party party = Program.parties[partyId];
if (server)
{
string text = "";
text += ("Name: " + party.name + Environment.NewLine);
text += ("Count: " + party.count + "/" + party.size + Environment.NewLine);
text += ("Status: " + (party.isPrivate ? "private" : (party.open ? "open" : "close")));
return new RequestResult(ResultTypes.OK, Common.Strings(text));
}
else
{
return new RequestResult(ResultTypes.OK, new string[4] { party.name, party.count.ToString(), party.size.ToString(), (party.isPrivate ? "private" : (party.open ? "open" : "close")) });
}
}
}
}

View File

@ -0,0 +1,36 @@
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
{
public class PartyStopCommand : ICommand
{
public string Name { get { return "stop"; } }
public string DescText { get { return "Stop party."; } }
public string HelpText { get { return "Use 'party stop' to stop current party"; } }
public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } }
public bool IsServer { get { return true; } }
public bool IsClient { get { return true; } }
public bool IsClientSide { get { return false; } }
public bool IsNoConnect { get { return false; } }
public int minArgs { get { return 0; } }
public int maxArgs { get { return 0; } }
public RequestResult Execute(string[] args, Socket soc, bool server = false)
{
int partyId = -1;
if (!Utilities.AccessParty(ref partyId, args, true, soc, server))
return new RequestResult(ResultTypes.Error, Common.Strings("Access"));
foreach (Socket client in Program.parties[partyId].clients)
{
Manager.Execute(new string[4] { "party", "kick", Utilities.GetName(client), "stop_party" }, soc, server);
}
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

@ -1,4 +1,6 @@
using System.Net.Sockets; using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands namespace Galactic_Colors_Control_Server.Commands
{ {
@ -6,7 +8,8 @@ namespace Galactic_Colors_Control_Server.Commands
{ {
public string Name { get { return "ping"; } } public string Name { get { return "ping"; } }
public string DescText { get { return "Clears the console screen."; } } public string DescText { get { return "Clears the console screen."; } }
public string HelpText { get { return "Use /ping to display our ping."; } } public string HelpText { get { return "Use 'ping' to display our ping."; } }
public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } }
public bool IsServer { get { return false; } } public bool IsServer { get { return false; } }
public bool IsClient { get { return true; } } public bool IsClient { get { return true; } }
public bool IsClientSide { get { return true; } } public bool IsClientSide { get { return true; } }
@ -14,9 +17,9 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { get { return 0; } } public int minArgs { get { return 0; } }
public int maxArgs { get { return 0; } } public int maxArgs { get { return 0; } }
public void Execute(string[] args, Socket soc, bool server = false) public RequestResult Execute(string[] args, Socket soc, bool server = false)
{ {
return new RequestResult(ResultTypes.Error, Common.Strings("ClientSide"));
} }
} }
} }

View File

@ -0,0 +1,34 @@
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
{
public class SayCommand : ICommand
{
public string Name { get { return "say"; } }
public string DescText { get { return "Said something."; } }
public string HelpText { get { return "Use 'say [text]' to said something."; } }
public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } }
public bool IsServer { get { return true; } }
public bool IsClient { get { return true; } }
public bool IsClientSide { get { return false; } }
public bool IsNoConnect { get { return false; } }
public int minArgs { get { return 1; } }
public int maxArgs { get { return 1; } }
public RequestResult Execute(string[] args, Socket soc, bool server = false)
{
if (args[1].Length == 0)
return new RequestResult(ResultTypes.Error, Common.Strings("AnyMessage"));
if (!Utilities.IsConnect(soc))
return new RequestResult(ResultTypes.Error, Common.Strings("MustBeConnected"));
int party = -1;
party = Utilities.GetParty(soc);
Utilities.BroadcastParty(new EventData(EventTypes.ChatMessage, Common.Strings(Utilities.GetName(soc) + " : " + args[1])), party);
return new RequestResult(ResultTypes.OK);
}
}
}

View File

@ -0,0 +1,30 @@
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
{
public class ServerCloseCommand : ICommand
{
public string Name { get { return "close"; } }
public string DescText { get { return "Close server."; } }
public string HelpText { get { return "Use 'server close' to close server for connections"; } }
public Manager.CommandGroup Group { get { return Manager.CommandGroup.server; } }
public bool IsServer { get { return true; } }
public bool IsClient { get { return false; } }
public bool IsClientSide { get { return false; } }
public bool IsNoConnect { get { return false; } }
public int minArgs { get { return 0; } }
public int maxArgs { get { return 0; } }
public RequestResult Execute(string[] args, Socket soc, bool server = false)
{
if (!Program._open)
return new RequestResult(ResultTypes.Error, Common.Strings("Allready"));
Program._open = false;
Program.logger.Write("Server closed", Logger.logType.warm, Logger.logConsole.show);
return new RequestResult(ResultTypes.OK);
}
}
}

View File

@ -0,0 +1,30 @@
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
{
public class ServerOpenCommand : ICommand
{
public string Name { get { return "open"; } }
public string DescText { get { return "Open server."; } }
public string HelpText { get { return "Use 'server open' to open server for connections"; } }
public Manager.CommandGroup Group { get { return Manager.CommandGroup.server; } }
public bool IsServer { get { return true; } }
public bool IsClient { get { return false; } }
public bool IsClientSide { get { return false; } }
public bool IsNoConnect { get { return false; } }
public int minArgs { get { return 0; } }
public int maxArgs { get { return 0; } }
public RequestResult Execute(string[] args, Socket soc, bool server = false)
{
if (Program._open)
return new RequestResult(ResultTypes.Error, Common.Strings("Allready"));
Program._open = true;
Program.logger.Write("Server opened", Logger.logType.warm, Logger.logConsole.show);
return new RequestResult(ResultTypes.OK);
}
}
}

View File

@ -0,0 +1,29 @@
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
{
public class ServerStatusCommand : ICommand
{
public string Name { get { return "status"; } }
public string DescText { get { return "Shows server status."; } }
public string HelpText { get { return "Use 'server status' to display server actual status."; } }
public Manager.CommandGroup Group { get { return Manager.CommandGroup.server; } }
public bool IsServer { get { return true; } }
public bool IsClient { get { return false; } }
public bool IsClientSide { get { return false; } }
public bool IsNoConnect { get { return false; } }
public int minArgs { get { return 0; } }
public int maxArgs { get { return 0; } }
public RequestResult Execute(string[] args, Socket soc, bool server = false)
{
string text = "";
text += "Server : " + (Program._open ? "open" : "close");
text += "Clients : " + Program.clients.Count + "/" + Program.config.size;
text += "Parties : " + Program.parties.Count;
return new RequestResult(ResultTypes.OK, Common.Strings(text));
}
}
}

View File

@ -0,0 +1,25 @@
using Galactic_Colors_Control_Common.Protocol;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
{
public class ServerStopCommand : ICommand
{
public string Name { get { return "stop"; } }
public string DescText { get { return "Stop the server."; } }
public string HelpText { get { return "Use 'server stop' to completly stop server."; } }
public Manager.CommandGroup Group { get { return Manager.CommandGroup.server; } }
public bool IsServer { get { return true; } }
public bool IsClient { get { return false; } }
public bool IsClientSide { get { return false; } }
public bool IsNoConnect { get { return false; } }
public int minArgs { get { return 0; } }
public int maxArgs { get { return 0; } }
public RequestResult Execute(string[] args, Socket soc, bool server = false)
{
Program._run = false;
return new RequestResult(ResultTypes.OK);
}
}
}

View File

@ -1,29 +0,0 @@
using System;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
{
public class StatusCommand : ICommand
{
public string Name { get { return "status"; } }
public string DescText { get { return "Shows server status."; } }
public string HelpText { get { return "Use /status to display server actual status."; } }
public bool IsServer { get { return true; } }
public bool IsClient { get { return false; } }
public bool IsClientSide { get { return false; } }
public bool IsNoConnect { get { return false; } }
public int minArgs { get { return 0; } }
public int maxArgs { get { return 0; } }
public void Execute(string[] args, Socket soc, bool server = false)
{
if (Program._open)
{
Utilities.ConsoleWrite("Server open");
}
else {
Utilities.ConsoleWrite("Server close");
}
}
}
}

View File

@ -1,4 +1,6 @@
using System; using Galactic_Colors_Control_Common;
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
@ -7,7 +9,8 @@ namespace Galactic_Colors_Control_Server.Commands
{ {
public string Name { get { return "time"; } } public string Name { get { return "time"; } }
public string DescText { get { return "Gives server time."; } } public string DescText { get { return "Gives server time."; } }
public string HelpText { get { return "Use /time to display server time. (format is server dependent)"; } } public string HelpText { get { return "Use 'time' to display server time."; } }
public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } }
public bool IsServer { get { return true; } } public bool IsServer { get { return true; } }
public bool IsClient { get { return true; } } public bool IsClient { get { return true; } }
public bool IsClientSide { get { return false; } } public bool IsClientSide { get { return false; } }
@ -15,9 +18,9 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { get { return 0; } } public int minArgs { get { return 0; } }
public int maxArgs { get { return 0; } } public int maxArgs { get { return 0; } }
public void Execute(string[] args, Socket soc, bool server = false) public RequestResult Execute(string[] args, Socket soc, bool server = false)
{ {
Utilities.Return(DateTime.Now.ToLongTimeString(), soc, server); return new RequestResult(ResultTypes.OK, Common.Strings(DateTime.Now.ToLongTimeString()));
} }
} }
} }

View File

@ -1,14 +1,12 @@
using System; using Galactic_Colors_Control_Common;
using System.Collections.Generic; using System;
using System.IO; using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml; using System.Xml;
using System.Xml.Serialization; using System.Xml.Serialization;
namespace Galactic_Colors_Control_Server namespace Galactic_Colors_Control_Server
{ {
//TODO Common config
[XmlRoot("config")] [XmlRoot("config")]
public class Config public class Config
{ {
@ -16,8 +14,10 @@ namespace Galactic_Colors_Control_Server
public Logger.logType logLevel = Logger.logType.info; public Logger.logType logLevel = Logger.logType.info;
public int port = 25001; public int port = 25001;
public int size = 20; public int size = 20;
public ConsoleColor[] logForeColor = new ConsoleColor[5] {ConsoleColor.Gray , ConsoleColor.White, ConsoleColor.Yellow, ConsoleColor.Red, ConsoleColor.White}; public ConsoleColor[] logForeColor = new ConsoleColor[6] { ConsoleColor.DarkGray, ConsoleColor.Gray, ConsoleColor.White, ConsoleColor.Yellow, ConsoleColor.Red, ConsoleColor.White };
public ConsoleColor[] logBackColor = new ConsoleColor[5] { ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Red }; public ConsoleColor[] logBackColor = new ConsoleColor[6] { ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Red };
public int lang = 1;
public int partysize = 10;
/// <summary> /// <summary>
/// Load config from xml file /// Load config from xml file
@ -26,7 +26,7 @@ namespace Galactic_Colors_Control_Server
/// <returns>Loaded config</returns> /// <returns>Loaded config</returns>
public Config Load() public Config Load()
{ {
Logger.Write("Loading config", Logger.logType.info); Program.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"))
{ {
@ -40,17 +40,19 @@ namespace Galactic_Colors_Control_Server
} }
else 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"); File.Move(AppDomain.CurrentDomain.BaseDirectory + "Config.xml", AppDomain.CurrentDomain.BaseDirectory + "Config.xml.old");
config.Save(); config.Save();
} }
} }
else else
{ {
Logger.Write("Any config file", Logger.logType.error); Program.logger.Write("Any config file", Logger.logType.error);
config.Save(); config.Save();
} }
if (Program._debug) { config.logLevel = Logger.logType.debug; } if (Program._debug) { config.logLevel = Logger.logType.debug; }
if (Program._dev) { config.logLevel = Logger.logType.dev; }
return config; return config;
} }
@ -60,12 +62,13 @@ namespace Galactic_Colors_Control_Server
public void Save() public void Save()
{ {
XmlSerializer xs = new XmlSerializer(typeof(Config)); XmlSerializer xs = new XmlSerializer(typeof(Config));
if (Program._debug) { logLevel = Logger.logType.info; } if (Program._debug || Program._dev) { logLevel = Logger.logType.info; }
using (StreamWriter st = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "Config.xml")) using (StreamWriter st = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "Config.xml"))
{ {
xs.Serialize(st,this); xs.Serialize(st, this);
}; };
if (Program._debug) { logLevel = Logger.logType.debug; } if (Program._debug) { logLevel = Logger.logType.debug; }
if (Program._dev) { logLevel = Logger.logType.dev; }
} }
/// <summary> /// <summary>
@ -86,7 +89,7 @@ namespace Galactic_Colors_Control_Server
catch (XmlException e) catch (XmlException e)
{ {
isCorrect = false; isCorrect = false;
Logger.Write("Error: " + e.Message, Logger.logType.error); Program.logger.Write("Error: " + e.Message, Logger.logType.error);
} }
} }
@ -100,18 +103,18 @@ namespace Galactic_Colors_Control_Server
d.Validate((o, e) => d.Validate((o, e) =>
{ {
Logger.Write("Error: " + e.Message, Logger.logType.error); Program.logger.Write("Error: " + e.Message, Logger.logType.error);
isCorrect = false; isCorrect = false;
}); });
} }
catch (XmlException e) catch (XmlException e)
{ {
isCorrect = false; isCorrect = false;
Logger.Write("Error: " + e.Message, Logger.logType.error); Program.logger.Write("Error: " + e.Message, Logger.logType.error);
} }
} }
return isCorrect; return isCorrect;
} }
} }
} }

View File

@ -21,7 +21,9 @@
</xsd:sequence> </xsd:sequence>
</xsd:complexType> </xsd:complexType>
</xsd:element> </xsd:element>
<xsd:element name="lang" type="xsd:unsignedInt" />
<xsd:element name="partysize" type="xsd:unsignedShort" />
</xsd:sequence> </xsd:sequence>
</xsd:complexType> </xsd:complexType>
</xsd:element> </xsd:element>
</xs:schema> </xs:schema>

View File

@ -1,11 +0,0 @@
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server
{
public class Data
{
public int id;
public int status = -1;
public string pseudo = "";
}
}

View File

@ -53,24 +53,42 @@
<Reference Include="System.XML" /> <Reference Include="System.XML" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="..\AssemblyInfoCommon.cs">
<Link>Properties\AssemblyInfoCommon.cs</Link>
</Compile>
<Compile Include="Client.cs" />
<Compile Include="Commands\ClearCommand.cs" /> <Compile Include="Commands\ClearCommand.cs" />
<Compile Include="Commands\Client\StatusCommand.cs" />
<Compile Include="Commands\BroadcastCommand.cs" />
<Compile Include="Commands\SayCommand.cs" />
<Compile Include="Commands\Party\PartyLeaveCommand.cs" />
<Compile Include="Commands\Party\PartyCreateCommand.cs" />
<Compile Include="Commands\Party\PartyJoinCommand.cs" />
<Compile Include="Commands\Party\PartyCloseCommand.cs" />
<Compile Include="Commands\Party\PartyClientCommand.cs" />
<Compile Include="Commands\Party\PartyStopCommand.cs" />
<Compile Include="Commands\Party\PartyPasswordCommand.cs" />
<Compile Include="Commands\Party\PartyListCommand.cs" />
<Compile Include="Commands\Party\PartyOpenCommand.cs" />
<Compile Include="Commands\Party\PartyStatusCommand.cs" />
<Compile Include="Commands\Party\PartyKickCommand.cs" />
<Compile Include="Commands\PingCommand.cs" /> <Compile Include="Commands\PingCommand.cs" />
<Compile Include="Commands\CloseCommand.cs" /> <Compile Include="Commands\Server\ServerOpenCommand.cs" />
<Compile Include="Commands\ConnectCommand.cs" /> <Compile Include="Commands\ConnectCommand.cs" />
<Compile Include="Commands\CountCommand.cs" /> <Compile Include="Commands\Client\CountCommand.cs" />
<Compile Include="Commands\ExitCommand.cs" /> <Compile Include="Commands\ExitCommand.cs" />
<Compile Include="Commands\HelpCommand.cs" /> <Compile Include="Commands\HelpCommand.cs" />
<Compile Include="Commands\ICommand.cs" /> <Compile Include="Commands\ICommand.cs" />
<Compile Include="Commands\KickCommand.cs" /> <Compile Include="Commands\Client\KickCommand.cs" />
<Compile Include="Commands\ListCommand.cs" /> <Compile Include="Commands\Client\ListCommand.cs" />
<Compile Include="Commands\LogLevelCommand.cs" /> <Compile Include="Commands\LogLevelCommand.cs" />
<Compile Include="Commands\Manager.cs" /> <Compile Include="Commands\Manager.cs" />
<Compile Include="Commands\OpenCommand.cs" /> <Compile Include="Commands\Server\ServerCloseCommand.cs" />
<Compile Include="Commands\StatusCommand.cs" /> <Compile Include="Commands\Server\ServerStopCommand.cs" />
<Compile Include="Commands\Server\ServerStatusCommand.cs" />
<Compile Include="Commands\TimeCommand.cs" /> <Compile Include="Commands\TimeCommand.cs" />
<Compile Include="Config.cs" /> <Compile Include="Config.cs" />
<Compile Include="Data.cs" /> <Compile Include="Party.cs" />
<Compile Include="Logger.cs" />
<Compile Include="Program.cs" /> <Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Utilities.cs" /> <Compile Include="Utilities.cs" />
@ -94,6 +112,13 @@
<Install>false</Install> <Install>false</Install>
</BootstrapperPackage> </BootstrapperPackage>
</ItemGroup> </ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Galactic Colors Control Common\Galactic Colors Control Common.csproj">
<Project>{022a69ce-22b5-4934-be9f-a9c6df9557ed}</Project>
<Name>Galactic Colors Control Common</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it. <!-- 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. Other similar extension points exist, see Microsoft.Common.targets.

View File

@ -1,131 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
namespace Galactic_Colors_Control_Server
{
public class Logger
{
public enum logType { debug, info, warm, error, fatal }
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;
public logType type;
public Log(string p1, logType p2)
{
text = p1;
type = p2;
}
}
/// <summary>
/// Create log file and start logger thread
/// </summary>
public static void Initialise()
{
if (!Directory.Exists(Program.config.logPath)) {
Directory.CreateDirectory(Program.config.logPath);
Write("Log Directory Created" ,logType.info);
}
else
{
//Sort old logs
string[] files = Directory.GetFiles(Program.config.logPath);
foreach(string file in files)
{
if (Path.GetExtension(file) == ".log")
{
string name = Path.GetFileName(file);
name = name.Substring(0, Math.Min(name.Length, 10));
if (name.Length == 10)
{
if (name != DateTime.UtcNow.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))
{
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(Program.config.logPath + "/" + y + "/" + m + "/" + d))
{
Directory.CreateDirectory(Program.config.logPath + "/" + y + "/" + m + "/" + d);
}
File.Move(file, Program.config.logPath + "/" + y + "/" + m + "/" + d + "/" + Path.GetFileName(file));
}
}
}
}
}
}
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";
Write("Log path:" + logPath, logType.debug);
Updater = new Thread(new ThreadStart(UpdaterLoop));
Updater.Start();
}
/// <summary>
/// Add log to log pile
/// </summary>
/// <param name="text">Log text</param>
/// <param name="type">Log status</param>
public static void Write(string text, logType type)
{
Write(new Log(text, type));
}
/// <summary>
/// Add log to log pile
/// </summary>
/// <param name="log">Log struct</param>
public static void Write(Log log)
{
if (log.type != logType.debug || Program.config.logLevel == logType.debug)
{
if(Program._debug)
{
//Add Source Method
log.text = "[" + new StackTrace().GetFrame(2).GetMethod().Name + "]: " + log.text;
}
toWriteLogs.Add(log);
}
}
/// <summary>
/// Write log pile to logfile and console
/// </summary>
public static void UpdaterLoop()
{
while (_run || toWriteLogs.Count > 0)
{
while(toWriteLogs.Count > 0)
{
Log log = toWriteLogs[0];
File.AppendAllText(logPath,DateTime.UtcNow.ToString("[yyyy-MM-dd]", CultureInfo.InvariantCulture) + " [" + log.type.ToString().ToUpper() + "]: " + log.text + Environment.NewLine);
if(log.type >= Program.config.logLevel) {
Console.BackgroundColor = Program.config.logBackColor[(int)log.type];
Console.ForegroundColor = Program.config.logForeColor[(int)log.type];
Console.Write("\b");
Console.WriteLine(DateTime.UtcNow.ToString("[yyyy-MM-dd]", CultureInfo.InvariantCulture) + ": " + log.text);
Utilities.ConsoleResetColor();
Console.Write(">");
}
toWriteLogs.Remove(log);
}
Thread.Sleep(200);
}
}
}
}

View File

@ -0,0 +1,73 @@
using System.Collections.Generic;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server
{
public class Party
{
public string name = "";
private string password = "";
public int size = 0;
public bool open = false;
private string owner = "";
public bool isPrivate { get { return password != ""; } }
public Party(string Name, int Size, string Owner)
{
name = Name;
size = Size;
owner = Owner;
}
public bool IsOwner(string name)
{
return owner == name;
}
public bool TestPassword(string pass)
{
if (isPrivate)
{
return (password == pass);
}
else
{
return true;
}
}
public bool SetPassword(string newPass, string oldPass)
{
if (TestPassword(oldPass))
{
password = newPass;
return true;
}
else
{
return false;
}
}
public int count
{
get
{
return clients.Count;
}
}
public List<Socket> clients
{
get
{
List<Socket> list = new List<Socket>();
foreach (Socket soc in Program.clients.Keys)
{
if (Program.clients[soc].party == this) { list.Add(soc); }
}
return list;
}
}
}
}

View File

@ -1,244 +1,264 @@
using System; using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using System.Reflection; using System.Reflection;
using System.Text; using System.Threading;
//TODO gui parties pages
namespace Galactic_Colors_Control_Server namespace Galactic_Colors_Control_Server
{ {
internal class Program internal class Program
{ {
private const int BUFFER_SIZE = 2048; private const int BUFFER_SIZE = 2048;
private static readonly Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); private static readonly Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public static bool _debug = false;
public static bool _run = true;
public static bool _open = true;
private static readonly byte[] buffer = new byte[BUFFER_SIZE];
public static Dictionary<Socket, Data> clients { get; private set; } = new Dictionary<Socket, Data>();
public static Config config = new Config();
private static void Main(string[] args) public static bool _debug = false;
{ public static bool _dev = false;
Console.Title = "Galactic Colors Control Server";
Logger.Write("Galactic Colors Control Server " + Assembly.GetEntryAssembly().GetName().Version.ToString(), Logger.logType.fatal);
if (args.Length > 0)
{
switch (args[0])
{
case "--debug":
_debug = true;
Logger.Write("SERVER IS IN DEBUG MODE !", Logger.logType.error);
break;
default: public static bool _run = true;
Utilities.ConsoleWrite("Use --debug or any argument"); public static bool _open = true;
break; private static readonly byte[] buffer = new byte[BUFFER_SIZE];
}
}
if(Type.GetType("Mono.Runtime") != null) { Logger.Write("Using Mono", Logger.logType.warm); }
Console.Write(">");
SetupServer();
ConsoleLoop();
CloseAllSockets();
}
/// <summary> public static Dictionary<Socket, Client> clients { get; private set; } = new Dictionary<Socket, Client>();
/// Initialise server and start threads.
/// </summary>
private static void SetupServer()
{
config = config.Load();
Logger.Initialise();
Commands.Manager.Load();
Logger.Write("Setting up server on *:" + config.port, Logger.logType.warm);
Logger.Write("Size:" + config.size, Logger.logType.debug);
serverSocket.Bind(new IPEndPoint(IPAddress.Any, config.port));
serverSocket.Listen(0);
serverSocket.BeginAccept(AcceptCallback, null);
Logger.Write("Server setup complete", Logger.logType.info);
}
/// <summary> private static int partyID = 0;
/// Wait console commands and execute them.
/// </summary>
private static void ConsoleLoop()
{
while (_run)
{
string ConsoleInput = Console.ReadLine();
Console.Write(">");
ExecuteMessage(ConsoleInput, null, true);
ConsoleInput = null;
}
}
/// <summary> public static Dictionary<int, Party> parties { get; private set; } = new Dictionary<int, Party>();
/// Close all connected client. public static int selectedParty = -1;
/// </summary>
private static void CloseAllSockets()
{
Logger.Write("Stoping server", Logger.logType.warm);
config.Save();
foreach (Socket socket in clients.Keys)
{
socket.Shutdown(SocketShutdown.Both);
Logger.Write("Shutdown " + Utilities.GetName(socket),Logger.logType.debug);
}
serverSocket.Close();
Logger.Write("Server stoped", Logger.logType.info);
Logger._run = false;
Logger.Updater.Join();
}
/// <summary> public static Config config = new Config();
/// Wait a client and check if is correct public static Logger logger = new Logger();
/// </summary> public static MultiLang multilang = new MultiLang();
private static void AcceptCallback(IAsyncResult AR) public static Thread CheckConnected = new Thread(CheckConnectedLoop);
{
Socket socket;
try /// <summary>
{ /// Server Main thread
socket = serverSocket.EndAccept(AR); /// </summary>
} private static void Main(string[] args)
catch (ObjectDisposedException) // I cannot seem to avoid this (on exit when properly closing sockets) {
{ Console.Title = "Galactic Colors Control Server";
return; logger.Write(Console.Title + " " + Assembly.GetEntryAssembly().GetName().Version.ToString(), Logger.logType.fatal);
} config = config.Load();
if (_open) logger.Initialise(config.logPath, config.logBackColor, config.logForeColor, config.logLevel, _debug, _dev);
{ multilang.Load();
if (clients.Count < config.size) if (args.Length > 0)
{ {
AddClient(socket); switch (args[0])
} {
else case "--debug":
{ _debug = true;
Logger.Write("Client can't join from " + ((IPEndPoint)socket.LocalEndPoint).Address.ToString() + " no more space", Logger.logType.warm); logger.Write("SERVER IS IN DEBUG MODE !", Logger.logType.error, Logger.logConsole.show);
Utilities.Send(socket, "/kick can't_join_no_more_space", Utilities.dataType.message); break;
socket.Close();
}
}
else
{
Logger.Write("Client can't join from " + ((IPEndPoint)socket.LocalEndPoint).Address.ToString() + " server closed", Logger.logType.info);
Utilities.Send(socket, "/kick can't_join_server_closed", Utilities.dataType.message);
socket.Close();
}
serverSocket.BeginAccept(AcceptCallback, null);
}
/// <summary> case "--dev":
/// Add client and initialise receive _dev = true;
/// </summary> logger.Write("SERVER IS IN DEV MODE !", Logger.logType.error, Logger.logConsole.show);
private static void AddClient(Socket socket) break;
{
clients.Add(socket, new Data());
socket.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, socket);
Logger.Write("Client connection from " + Utilities.GetName(socket), Logger.logType.info);
Logger.Write("Size: " + clients.Count + "/" + config.size, Logger.logType.debug);
if (clients.Count >= config.size)
{
Logger.Write("Server full", Logger.logType.warm);
}
}
/// <summary> default:
/// Wait a client commands and execute them Common.ConsoleWrite("Use --debug or --dev");
/// </summary> break;
private static void ReceiveCallback(IAsyncResult AR) }
{ }
Socket current = (Socket)AR.AsyncState; if (Type.GetType("Mono.Runtime") != null) { logger.Write("Using Mono", Logger.logType.warm, Logger.logConsole.show); }
int received; Console.Write(">");
SetupServer();
ConsoleLoop();
CloseAllSockets();
}
try /// <summary>
{ /// Initialise server and start threads.
received = current.EndReceive(AR); /// </summary>
} private static void SetupServer()
catch (SocketException) {
{ Commands.Manager.Load();
Logger.Write("Client forcefully disconnected from " + Utilities.GetName(current), Logger.logType.info); logger.Write("Setting up server on *:" + config.port, Logger.logType.warm);
string username = Utilities.GetName(current); logger.Write("Size:" + config.size, Logger.logType.debug);
bool connected = Program.clients[current].status != -1; serverSocket.Bind(new IPEndPoint(IPAddress.Any, config.port));
Logger.Write("Size: " + clients.Count + "/" + config.size, Logger.logType.debug); serverSocket.Listen(0);
current.Close(); // Don't shutdown because the socket may be disposed and its disconnected anyway. serverSocket.BeginAccept(AcceptCallback, null);
clients.Remove(current); CheckConnected.Start();
if (connected) { Utilities.Broadcast(username + " leave the server", Utilities.dataType.message); } logger.Write("Server setup complete", Logger.logType.info);
return; }
}
var data = new byte[received]; /// <summary>
Array.Copy(buffer, data, received); /// Wait console commands and execute them.
/// </summary>
private static void ConsoleLoop()
{
while (_run)
{
string ConsoleInput = Console.ReadLine();
Console.Write(">");
string[] args = Common.SplitArgs(ConsoleInput);
Common.ConsoleWrite(multilang.GetResultText(new ResultData(-1, Commands.Manager.Execute(args, null, true)), config.lang));
ConsoleInput = null;
}
}
try { /// <summary>
byte[] type = new byte[4]; /// Close all connected client.
type = data.Take(4).ToArray(); /// </summary>
type.Reverse(); private static void CloseAllSockets()
Utilities.dataType dtype = (Utilities.dataType)BitConverter.ToInt32(type, 0); {
byte[] bytes = null; logger.Write("Stoping server", Logger.logType.warm, Logger.logConsole.show);
bytes = data.Skip(4).ToArray(); Utilities.Broadcast(new EventData(EventTypes.ServerKick, Common.Strings("Close")));
switch (dtype) config.Save();
{ foreach (Socket socket in clients.Keys)
case Utilities.dataType.message: {
string text = Encoding.ASCII.GetString(bytes); socket.Shutdown(SocketShutdown.Both);
ExecuteMessage(text, current); logger.Write("Shutdown " + Utilities.GetName(socket), Logger.logType.debug);
break; }
serverSocket.Close();
CheckConnected.Join(2000);
logger.Write("Server stoped", Logger.logType.info);
logger.Join();
}
case Utilities.dataType.data: /// <summary>
Console.WriteLine("data"); /// Wait a client and check if is correct
break; /// </summary>
private static void AcceptCallback(IAsyncResult AR)
{
Socket socket;
try
{
socket = serverSocket.EndAccept(AR);
}
catch (ObjectDisposedException)
{
return;
}
if (_open)
{
if (clients.Count < config.size)
{
AddClient(socket);
}
else
{
logger.Write("Client can't join from " + ((IPEndPoint)socket.LocalEndPoint).Address.ToString() + " no more space", Logger.logType.warm);
Utilities.Send(socket, new EventData(EventTypes.ServerKick, Common.Strings("Space")));
socket.Close();
}
}
else
{
logger.Write("Client can't join from " + ((IPEndPoint)socket.LocalEndPoint).Address.ToString() + " server closed", Logger.logType.info);
Utilities.Send(socket, new EventData(EventTypes.ServerKick, Common.Strings("Close")));
socket.Close();
}
serverSocket.BeginAccept(AcceptCallback, null);
}
default: /// <summary>
Logger.Write("Unknow type data form" + Utilities.GetName(current), Logger.logType.error); /// Add client and initialise receive
break; /// </summary>
} private static void AddClient(Socket socket)
{
Client client = new Client();
clients.Add(socket, client);
socket.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, socket);
logger.Write("Client connection from " + Utilities.GetName(socket), Logger.logType.info);
logger.Write("Size: " + clients.Count + "/" + config.size, Logger.logType.dev);
if (clients.Count >= config.size)
{
logger.Write("Server full", Logger.logType.warm, Logger.logConsole.show);
}
}
if (clients.ContainsKey(current)) { current.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, current); } /// <summary>
} /// Wait a client commands and execute them
catch (Exception) { /// </summary>
Logger.Write("Client forcefully disconnected from " + Utilities.GetName(current), Logger.logType.info); private static void ReceiveCallback(IAsyncResult AR)
if (clients.ContainsKey(current)) { clients.Remove(current); } {
} Socket current = (Socket)AR.AsyncState;
} int received;
/// <summary> try
/// Execute send command {
/// <param name="text">Command</param> received = current.EndReceive(AR);
/// <param name="soc">Sender socket</param> }
/// <param name="server">Is sender server?</param> catch (SocketException)
/// </summary> {
private static void ExecuteMessage(string text, Socket soc = null, bool server = false) logger.Write("Client forcefully disconnected from " + Utilities.GetName(current) + " : SocketException", Logger.logType.info);
{ string username = Utilities.GetName(current);
if (text.Length > 0) bool connected = clients[current].status != -1;
{ logger.Write("Size: " + clients.Count + "/" + config.size, Logger.logType.debug);
if (text[0] == '/') current.Close(); // Don't shutdown because the socket may be disposed and its disconnected anyway.
{ clients.Remove(current);
text = text.Substring(1); if (connected) { Utilities.Broadcast(new EventData(EventTypes.ServerLeave, Common.Strings(username))); }
text = text.ToLower(); return;
string[] array = text.Split(new char[1] { ' ' }, 4, StringSplitOptions.RemoveEmptyEntries); }
if (array.Length > 0)
{ var data = new byte[received];
Commands.Manager.Execute(array, soc, server); Array.Copy(buffer, data, received);
}
else Data packet = Data.FromBytes(ref data);
{ if (packet != null)
Utilities.Return("Any command",soc , server); {
} switch (packet.GetType().Name)
} {
else case "RequestData":
{ RequestData req = (RequestData)packet;
if (!Utilities.IsConnect(soc)) Utilities.Send(current, new ResultData(req.id, Commands.Manager.Execute(req.args, current)));
{ break;
Utilities.Send(soc, "Only identified clients can talk.", Utilities.dataType.message);
} default:
else logger.Write("Wrong packet from " + Utilities.GetName(current), Logger.logType.error);
{ break;
Logger.Write(Utilities.GetName(soc) + " : " + text, Logger.logType.info); }
Utilities.Broadcast(Utilities.GetName(soc) + " : " + text, Utilities.dataType.message); }
} else
} {
} 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); }
}
private static void CheckConnectedLoop()
{
while (_run)
{
foreach (Socket current in clients.Keys.ToArray())
{
try
{
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))); }
}
}catch { }
Thread.Sleep(200);
}
}
}
/// <summary>
/// Add new party with index
/// </summary>
/// <param name="party">Party to add</param>
public static void AddParty(Party party)
{
parties.Add(GetPartyID(), party);
}
public static int GetPartyID(bool indent = true)
{
if (indent) { partyID++; }
return partyID;
}
}
} }

View File

@ -1,36 +1,20 @@
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
// Les informations générales relatives à un assembly dépendent de // Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations // l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly. // associées à un assembly.
[assembly: AssemblyTitle("Galactic Colors Control Server")] [assembly: AssemblyTitle("Galactic Colors Control Server")]
[assembly: AssemblyDescription("")] [assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")] [assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("sheychen")]
[assembly: AssemblyProduct("Galactic Colors Control Server")] [assembly: AssemblyProduct("Galactic Colors Control Server")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")] [assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")] [assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly // L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de // aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type. // COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)] [assembly: ComVisible(false)]
// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM // Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM
[assembly: Guid("9e3af4e1-88c6-4139-a15c-b4f633e80612")] [assembly: Guid("9e3af4e1-88c6-4139-a15c-b4f633e80612")]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
// en utilisant '*', comme indiqué ci-dessous :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.1.1")]
[assembly: AssemblyFileVersion("1.0.1.1")]

View File

@ -1,38 +1,27 @@
using System; using Galactic_Colors_Control_Common;
using System.IO; using Galactic_Colors_Control_Common.Protocol;
using System;
using System.Net; using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
namespace Galactic_Colors_Control_Server namespace Galactic_Colors_Control_Server
{ {
class Utilities internal class Utilities
{ {
public enum dataType { message, data };
/// <summary> /// <summary>
/// Check if socket is connect /// Check if socket is connect
/// </summary> /// </summary>
/// <param name="soc">Client socket</param> /// <param name="soc">Client socket</param>
public static bool IsConnect(Socket soc) public static bool IsConnect(Socket soc)
{ {
if(soc == null) if (soc == null)
{
return true; return true;
}
else if (Program.clients.ContainsKey(soc))
{ return Program.clients[soc].status != -1;
if (Program.clients.ContainsKey(soc))
{ Program.logger.Write("IsConnect : Unknown client", Logger.logType.error);
return Program.clients[soc].status != -1; return false;
}
else
{
Logger.Write("IsConnect : Unknown client", Logger.logType.error);
return true;
}
}
} }
/// <summary> /// <summary>
@ -42,47 +31,23 @@ namespace Galactic_Colors_Control_Server
/// <returns>Name</returns> /// <returns>Name</returns>
public static string GetName(Socket soc) public static string GetName(Socket soc)
{ {
if (soc != null) if (soc == null)
{ return Program.multilang.Get("Server",Program.config.lang);
if (Program.clients.ContainsKey(soc))
{ if (!Program.clients.ContainsKey(soc))
string res = Program.clients[soc].pseudo; return "?";
if (res == "") { res = ((IPEndPoint)soc.LocalEndPoint).Address.ToString(); }
return res; string res = Program.clients[soc].pseudo;
} if (res == "") { res = ((IPEndPoint)soc.LocalEndPoint).Address.ToString(); }
else return res;
{
return "?";
}
}
else
{
return "Server";
}
} }
/// <summary> public static int GetParty(Socket soc)
/// Write line in console with correct colors
/// </summary>
/// <param name="v">Text to write</param>
public static void ConsoleWrite(string v)
{ {
Console.Write("\b"); if (soc == null)
Console.ForegroundColor = ConsoleColor.White; return Program.selectedParty;
Console.BackgroundColor = ConsoleColor.Black;
Console.WriteLine(v);
ConsoleResetColor();
Console.Write(">");
}
/// <summary> return Program.clients[soc].partyID;
/// Reset Console Colors
/// For non black background console as Ubuntu
/// </summary>
public static void ConsoleResetColor()
{
Console.ResetColor();
Console.BackgroundColor = ConsoleColor.Black;
} }
/// <summary> /// <summary>
@ -90,40 +55,23 @@ namespace Galactic_Colors_Control_Server
/// </summary> /// </summary>
/// <param name="soc">Target socket</param> /// <param name="soc">Target socket</param>
/// <param name="data">Data to send</param> /// <param name="data">Data to send</param>
/// <param name="dtype">Type of data</param> public static void Send(Socket soc, Data packet)
public static void Send(Socket soc, object data, dataType dtype)
{ {
/* if (soc.Connected)
Format:
0-3: dataType
4-x: data
*/
byte[] type = new byte[4];
type = BitConverter.GetBytes((int)dtype);
byte[] bytes = null;
switch (dtype)
{ {
case dataType.message: try
bytes = Encoding.ASCII.GetBytes((string)data); {
break; soc.Send(packet.ToBytes());
if (Program.config.logLevel == Logger.logType.dev)
case dataType.data:
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{ {
bf.Serialize(ms, data); Program.logger.Write("Send to " + GetName(soc) + " : " + packet.ToLongString(), Logger.logType.dev);
bytes = ms.ToArray();
} }
break; }
catch (Exception e)
default: {
bytes = new byte[] { 1 }; Program.logger.Write("Send exception to " + GetName(soc) + " : " + e.Message, Logger.logType.error);
break; }
} }
byte[] final = new byte[type.Length + bytes.Length];
type.CopyTo(final, 0);
bytes.CopyTo(final, type.Length);
soc.Send(final);
} }
/// <summary> /// <summary>
@ -131,30 +79,116 @@ namespace Galactic_Colors_Control_Server
/// </summary> /// </summary>
/// <param name="data">Data to send</param> /// <param name="data">Data to send</param>
/// <param name="dtype">Type of data</param> /// <param name="dtype">Type of data</param>
public static void Broadcast(object data, dataType dtype) /// <param name="message">Message to display for server</param>
public static void Broadcast(Data packet)
{ {
foreach (Socket soc in Program.clients.Keys) foreach (Socket soc in Program.clients.Keys)
{ {
Send(soc, data, dtype); Send(soc, packet);
}
switch (packet.GetType().Name)
{
case "EventData":
Common.ConsoleWrite(Program.multilang.GetEventText((EventData)packet, Program.config.lang));
break;
default:
Common.ConsoleWrite(packet.ToSmallString());
break;
}
}
/// <summary>
/// Send data to all client of the party
/// </summary>
/// <param name="data">Data to send</param>
/// <param name="dtype">Type of data</param>
/// <param name="party">Id of the party</param>
/// <param name="message">Message to display for server</param>
public static void BroadcastParty(Data data, int party)
{
foreach (Socket soc in Program.clients.Keys)
{
if (Program.clients[soc].partyID == party)
{
Send(soc, data);
}
}
if (Program.selectedParty == party)
{
switch (data.GetType().Name)
{
case "EventData":
Common.ConsoleWrite(Program.multilang.GetEventText((EventData)data, Program.config.lang));
break;
default:
Common.ConsoleWrite(data.ToSmallString());
break;
}
} }
} }
/// <summary> /// <summary>
/// Send or display if server /// Send or display if server
/// </summary> /// </summary>
/// <param name="message">Text to send</param> /// <param name="message">Text to display if server</param>
/// <param name="data">Data to send if client</param>
/// <param name="soc">Target socket</param> /// <param name="soc">Target socket</param>
/// <param name="server">Is server?</param> /// <param name="server">Is server?</param>
public static void Return(string message, Socket soc = null, bool server = false) public static void Return(Data data, Socket soc = null, bool server = false)
{ {
if (server) if (server)
{ {
ConsoleWrite(message); Common.ConsoleWrite(data.ToSmallString());
} }
else else
{ {
Send(soc, message, dataType.message); Send(soc, data);
}
}
/// <summary>
/// Try get party of the socket
/// </summary>
/// <param name="partyId">Result party ID</param>
/// <param name="needOwn">Return true only for owner and server</param>
/// <param name="soc">Target socket</param>
/// <param name="server">Is server?</param>
/// <returns>Can access?</returns>
public static bool AccessParty(ref int partyId, string[] args, bool needOwn, Socket soc = null, bool server = false)
{
if (server)
{
if (Program.selectedParty == -1)
return false;
if (Program.parties.ContainsKey(Program.selectedParty))
{
partyId = Program.selectedParty;
return true;
}
else
{
Program.selectedParty = -1;
return false;
}
}
else
{
if (Program.clients[soc].partyID == -1)
return false;
if (!Program.parties.ContainsKey(Program.clients[soc].partyID))
return false;
if (Program.parties[Program.clients[soc].partyID].IsOwner(GetName(soc)) || !needOwn)
{
partyId = Program.clients[soc].partyID;
return true;
}
else { return false; }
} }
} }
} }
} }

View File

@ -1,19 +1,39 @@
 
Microsoft Visual Studio Solution File, Format Version 12.00 Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14 # Visual Studio 14
VisualStudioVersion = 14.0.24720.0 VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Galactic Colors Control Server", "Galactic Colors Control Server\Galactic Colors Control Server.csproj", "{9E3AF4E1-88C6-4139-A15C-B4F633E80612}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Galactic Colors Control Server", "Galactic Colors Control Server\Galactic Colors Control Server.csproj", "{9E3AF4E1-88C6-4139-A15C-B4F633E80612}"
ProjectSection(ProjectDependencies) = postProject
{022A69CE-22B5-4934-BE9F-A9C6DF9557ED} = {022A69CE-22B5-4934-BE9F-A9C6DF9557ED}
EndProjectSection
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Galactic Colors Control", "Galactic Colors Control\Galactic Colors Control.csproj", "{93582CE8-C8C8-4E19-908B-D671ECBADE25}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Galactic Colors Control", "Galactic Colors Control\Galactic Colors Control.csproj", "{93582CE8-C8C8-4E19-908B-D671ECBADE25}"
ProjectSection(ProjectDependencies) = postProject
{022A69CE-22B5-4934-BE9F-A9C6DF9557ED} = {022A69CE-22B5-4934-BE9F-A9C6DF9557ED}
EndProjectSection
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Galactic Colors Control GUI", "Galactic Colors Control GUI\Galactic Colors Control GUI.csproj", "{F6CDDF1B-5A57-4A84-B57C-749FFF9AE031}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Galactic Colors Control GUI", "Galactic Colors Control GUI\Galactic Colors Control GUI.csproj", "{F6CDDF1B-5A57-4A84-B57C-749FFF9AE031}"
ProjectSection(ProjectDependencies) = postProject ProjectSection(ProjectDependencies) = postProject
{022A69CE-22B5-4934-BE9F-A9C6DF9557ED} = {022A69CE-22B5-4934-BE9F-A9C6DF9557ED}
{93582CE8-C8C8-4E19-908B-D671ECBADE25} = {93582CE8-C8C8-4E19-908B-D671ECBADE25} {93582CE8-C8C8-4E19-908B-D671ECBADE25} = {93582CE8-C8C8-4E19-908B-D671ECBADE25}
EndProjectSection EndProjectSection
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Galactic Colors Control Console", "Galactic Colors Control Console\Galactic Colors Control Console.csproj", "{5D6A09D1-DCAB-4FD8-B4E6-62D9F41AE8F0}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Galactic Colors Control Console", "Galactic Colors Control Console\Galactic Colors Control Console.csproj", "{5D6A09D1-DCAB-4FD8-B4E6-62D9F41AE8F0}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Galactic Colors Control Common", "Galactic Colors Control Common\Galactic Colors Control Common.csproj", "{022A69CE-22B5-4934-BE9F-A9C6DF9557ED}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Common", "Common", "{75A0ADCB-CB9B-48DA-AF82-C58F2105848B}"
ProjectSection(SolutionItems) = preProject
AssemblyInfoCommon.cs = AssemblyInfoCommon.cs
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{4E46A1CB-6F9C-4E4E-8A9A-D62DAB09FF64}"
ProjectSection(SolutionItems) = preProject
License.md = License.md
Readme.md = Readme.md
EndProjectSection
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@ -22,8 +42,8 @@ Global
Release|x86 = Release|x86 Release|x86 = Release|x86
EndGlobalSection EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution GlobalSection(ProjectConfigurationPlatforms) = postSolution
{9E3AF4E1-88C6-4139-A15C-B4F633E80612}.Debug|Any CPU.ActiveCfg = Release|Any CPU {9E3AF4E1-88C6-4139-A15C-B4F633E80612}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9E3AF4E1-88C6-4139-A15C-B4F633E80612}.Debug|Any CPU.Build.0 = Release|Any CPU {9E3AF4E1-88C6-4139-A15C-B4F633E80612}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9E3AF4E1-88C6-4139-A15C-B4F633E80612}.Debug|x86.ActiveCfg = Debug|Any CPU {9E3AF4E1-88C6-4139-A15C-B4F633E80612}.Debug|x86.ActiveCfg = Debug|Any CPU
{9E3AF4E1-88C6-4139-A15C-B4F633E80612}.Debug|x86.Build.0 = Debug|Any CPU {9E3AF4E1-88C6-4139-A15C-B4F633E80612}.Debug|x86.Build.0 = Debug|Any CPU
{9E3AF4E1-88C6-4139-A15C-B4F633E80612}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E3AF4E1-88C6-4139-A15C-B4F633E80612}.Release|Any CPU.ActiveCfg = Release|Any CPU
@ -54,6 +74,14 @@ Global
{5D6A09D1-DCAB-4FD8-B4E6-62D9F41AE8F0}.Release|Any CPU.Build.0 = Release|Any CPU {5D6A09D1-DCAB-4FD8-B4E6-62D9F41AE8F0}.Release|Any CPU.Build.0 = Release|Any CPU
{5D6A09D1-DCAB-4FD8-B4E6-62D9F41AE8F0}.Release|x86.ActiveCfg = Release|Any CPU {5D6A09D1-DCAB-4FD8-B4E6-62D9F41AE8F0}.Release|x86.ActiveCfg = Release|Any CPU
{5D6A09D1-DCAB-4FD8-B4E6-62D9F41AE8F0}.Release|x86.Build.0 = Release|Any CPU {5D6A09D1-DCAB-4FD8-B4E6-62D9F41AE8F0}.Release|x86.Build.0 = Release|Any CPU
{022A69CE-22B5-4934-BE9F-A9C6DF9557ED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{022A69CE-22B5-4934-BE9F-A9C6DF9557ED}.Debug|Any CPU.Build.0 = Debug|Any CPU
{022A69CE-22B5-4934-BE9F-A9C6DF9557ED}.Debug|x86.ActiveCfg = Debug|Any CPU
{022A69CE-22B5-4934-BE9F-A9C6DF9557ED}.Debug|x86.Build.0 = Debug|Any CPU
{022A69CE-22B5-4934-BE9F-A9C6DF9557ED}.Release|Any CPU.ActiveCfg = Release|Any CPU
{022A69CE-22B5-4934-BE9F-A9C6DF9557ED}.Release|Any CPU.Build.0 = Release|Any CPU
{022A69CE-22B5-4934-BE9F-A9C6DF9557ED}.Release|x86.ActiveCfg = Release|Any CPU
{022A69CE-22B5-4934-BE9F-A9C6DF9557ED}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<configuration> <configuration>
<startup> <startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup> </startup>
</configuration> </configuration>

View File

@ -56,6 +56,9 @@
<Reference Include="System" /> <Reference Include="System" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="..\AssemblyInfoCommon.cs">
<Link>Properties\AssemblyInfoCommon.cs</Link>
</Compile>
<Compile Include="Program.cs" /> <Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup> </ItemGroup>
@ -74,6 +77,12 @@
<Install>false</Install> <Install>false</Install>
</BootstrapperPackage> </BootstrapperPackage>
</ItemGroup> </ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Galactic Colors Control Common\Galactic Colors Control Common.csproj">
<Project>{022a69ce-22b5-4934-be9f-a9c6df9557ed}</Project>
<Name>Galactic Colors Control Common</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it. <!-- 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. Other similar extension points exist, see Microsoft.Common.targets.

View File

@ -1,45 +1,71 @@
using System; using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Net.NetworkInformation; using System.Net.NetworkInformation;
using System.Net.Sockets; using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading; using System.Threading;
namespace Galactic_Colors_Control namespace Galactic_Colors_Control
{ {
/// <summary>
/// Client CrossPlatform Core
/// </summary>
public class Client public class Client
{ {
private Socket ClientSocket = new Socket private Socket ClientSocket = new Socket
(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public int PORT = 0; public string IP = null; //Server IP
private int _errorCount = 0; public int PORT = 0; //Server Port
private bool _run = true;
public string IP = null;
public struct CoreConfig
{
public int resultsBuffer; //Max amount of waiting results
public int timeout; //Request timeout in ms
public int refresh; //Threads sleep in ms
public CoreConfig(int buffer, int time, int speed)
{
resultsBuffer = buffer;
timeout = time;
refresh = speed;
}
}
public CoreConfig config = new CoreConfig(20, 2000, 200); //Set default config
private int _errorCount = 0; //Leave if > 5
private bool _run = true; //Thread Stop
public bool isRunning { get { return _run; } } public bool isRunning { get { return _run; } }
private enum dataType { message, data }; private int RequestId = 0;
private List<ResultData> Results = new List<ResultData>();
public List<string> Output = new List<string>(); private Thread RecieveThread; //Main Thread
public EventHandler OnEvent; //Execute on EventData reception (must be short or async)
private Thread RecieveThread;
/// <summary>
/// Soft Server Reset
/// </summary>
public void ResetHost() public void ResetHost()
{ {
IP = null; IP = null;
PORT = 0; PORT = 0;
} }
/// <summary>
/// Test and Convert Hostname to Address
/// </summary>
/// <param name="text">Hostname</param>
/// <returns>Address(IP:PORT) or Error(*'text')</returns>
public string ValidateHost(string text) public string ValidateHost(string text)
{ {
if (text == null) { text = ""; } if (text == null) { text = ""; } //Prevent NullException
string[] parts = text.Split(new char[] { ':' }, 2, StringSplitOptions.RemoveEmptyEntries); string[] parts = text.Split(new char[] { ':' }, 2, StringSplitOptions.RemoveEmptyEntries); //Split IP and Port
if (parts.Length == 0) if (parts.Length == 0) //Default config (localhost)
{ {
parts = new string[] { "" }; parts = new string[] { "" };
PORT = 25001; PORT = 25001;
@ -48,7 +74,7 @@ namespace Galactic_Colors_Control
{ {
if (parts.Length > 1) if (parts.Length > 1)
{ {
if (!int.TryParse(parts[1], out PORT)) { PORT = 0; } if (!int.TryParse(parts[1], out PORT)) { PORT = 0; } //Check Port
if (PORT < 0 || PORT > 65535) { PORT = 0; } if (PORT < 0 || PORT > 65535) { PORT = 0; }
} }
else else
@ -60,29 +86,28 @@ namespace Galactic_Colors_Control
{ {
try try
{ {
IPHostEntry ipHostEntry = Dns.GetHostEntry(parts[0]); IPHostEntry ipHostEntry = Dns.GetHostEntry(parts[0]);//Resolve Hostname
IPAddress host = ipHostEntry.AddressList.First(a => a.AddressFamily == AddressFamily.InterNetwork); IPAddress host = ipHostEntry.AddressList.First(a => a.AddressFamily == AddressFamily.InterNetwork);//Get IPv4
IP = host.ToString(); IP = host.ToString();
return IP + ":" + PORT; return IP + ":" + PORT;
} }
catch (Exception e) catch (Exception e)
{ {
Output.Add(e.Message);
PORT = 0; PORT = 0;
return null; return "*" + e.Message;
} }
} }
else else
{ {
Output.Add("Incorrect port"); return "*Port Format";
return null;
} }
} }
/// <summary> /// <summary>
/// Set IP and PORT before /// Start Server connection
/// </summary> /// </summary>
/// <returns>Connection succes</returns> /// <remarks>Setup IP and Port before</remarks>
/// <returns>connection success</returns>
public bool ConnectHost() public bool ConnectHost()
{ {
int attempts = 0; int attempts = 0;
@ -92,32 +117,27 @@ namespace Galactic_Colors_Control
try try
{ {
attempts++; attempts++;
Output.Add("Connection attempt " + attempts);
ClientSocket.Connect(IP, PORT); ClientSocket.Connect(IP, PORT);
} }
catch (SocketException) catch (SocketException) { }
{
Output.Clear();
}
} }
if (attempts < 5) if (attempts < 5) //Connection success
{ {
Output.Clear();
Output.Add("Connected to " + IP.ToString());
_run = true; _run = true;
RecieveThread = new Thread(ReceiveLoop); RecieveThread = new Thread(ReceiveLoop); //Starting Main Thread
RecieveThread.Start(); RecieveThread.Start();
return true; return true;
} }
else else
{ {
Output.Clear();
Output.Add("Can't connected to " + IP.ToString());
ResetSocket(); ResetSocket();
return false; return false;
} }
} }
/// <summary>
/// Hard Reset (unsafe)
/// </summary>
private void ResetSocket() private void ResetSocket()
{ {
ClientSocket.Close(); ClientSocket.Close();
@ -130,93 +150,98 @@ namespace Galactic_Colors_Control
/// </summary> /// </summary>
public void ExitHost() public void ExitHost()
{ {
Send("/exit", dataType.message); // Tell the server we are exiting try { Send(new RequestData(GetRequestId(), new string[1] { "exit" })); } catch { }// Tell the server we are exiting
_run = false; _run = false; //Stopping Thread
RecieveThread.Join(); RecieveThread.Join(2000);
ClientSocket.Shutdown(SocketShutdown.Both); ClientSocket.Shutdown(SocketShutdown.Both);
ClientSocket.Close(); ClientSocket.Close();
Output.Add("Bye");
ResetHost(); ResetHost();
} }
public void SendRequest(string request) /// <summary>
/// Send RequestData to server
/// </summary>
/// <param name="args">Request args</param>
/// <returns>ResultData or Timeout</returns>
public ResultData Request(string[] args)
{ {
switch (request.ToLower()) switch(args[0])
{ {
case "/exit": case "exit":
ExitHost(); ExitHost();
break; return new ResultData(GetRequestId(), ResultTypes.OK);
case "/ping": case "ping":
PingHost(); return PingHost();
break;
case "/clear":
Output.Add("/clear");
break;
default: default:
Send(request, dataType.message); return Execute(args);
break;
} }
} }
private void PingHost() /// <summary>
/// Send row command to server
/// </summary>
private ResultData Execute(string[] args)
{ {
Ping p = new Ping(); RequestData req = new RequestData(GetRequestId(), args);
PingReply r; if (!Send(req))
return new ResultData(req.id, ResultTypes.Error, Common.Strings("Send Exception"));
r = p.Send(IP); DateTime timeoutDate = DateTime.Now.AddMilliseconds(config.timeout); //Create timeout DataTime
while (timeoutDate > DateTime.Now)
if (r.Status == IPStatus.Success)
{ {
Output.Add(r.RoundtripTime.ToString() + " ms."); foreach (ResultData res in Results.ToArray()) //Check all results
} {
else if (res.id == req.id)
{
Output.Add("Time out");
}
}
private void Send(object data, dataType dtype)
{
byte[] type = new byte[4];
type = BitConverter.GetBytes((int)dtype);
byte[] bytes = null;
switch (dtype)
{
case dataType.message:
bytes = Encoding.ASCII.GetBytes((string)data);
break;
case dataType.data:
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{ {
bf.Serialize(ms, data); Results.Remove(res);
bytes = ms.ToArray(); return res;
} }
break; }
Thread.Sleep(config.refresh);
} }
byte[] final = new byte[type.Length + bytes.Length]; return new ResultData(req.id, ResultTypes.Error, Common.Strings("Timeout"));
type.CopyTo(final, 0); }
bytes.CopyTo(final, type.Length);
try /// <summary>
/// Ping Current Server IP
/// </summary>
/// <returns>Time in ms or 'Timeout'</returns>
private ResultData PingHost()
{
Ping ping = new Ping();
PingReply reply;
reply = ping.Send(IP);
if (reply.Status == IPStatus.Success)
return new ResultData(GetRequestId(), ResultTypes.OK, Common.SplitArgs(reply.RoundtripTime.ToString() + "ms"));
return new ResultData(GetRequestId(), ResultTypes.Error, Common.SplitArgs("Timeout"));
}
/// <summary>
/// Send Data object to server
/// </summary>
/// <returns>Send success</returns>
private bool Send(Data packet)
{
//try
//{
ClientSocket.Send(packet.ToBytes());
return true;
/*}
catch //Can't contact server
{ {
ClientSocket.Send(final);
}
catch
{
Output.Add("Can't contact server : " + _errorCount);
_errorCount++; _errorCount++;
} }
if (_errorCount >= 5) return false;*/
{
Output.Add("Kick : too_much_errors");
_run = false;
}
} }
/// <summary>
/// Main Thread
/// </summary>
private void ReceiveLoop() private void ReceiveLoop()
{ {
while (_run) while (_run)
@ -229,67 +254,55 @@ namespace Galactic_Colors_Control
} }
catch catch
{ {
Output.Add("Server timeout"); _errorCount++;
}
if (_errorCount >= 5)
{
_run = false;
} }
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);
byte[] type = new byte[4];
type = data.Take(4).ToArray(); Data packet = Data.FromBytes(ref data); //Create Data object from recieve bytes
type.Reverse(); if (packet != null)
dataType dtype = (dataType)BitConverter.ToInt32(type, 0);
byte[] bytes = null;
bytes = data.Skip(4).ToArray();
switch (dtype)
{ {
case dataType.message: switch (packet.GetType().Name)
string text = Encoding.ASCII.GetString(bytes); {
if (text[0] == '/') case "EventData":
{ EventData eve = (EventData)packet;
text = text.Substring(1); if (OnEvent != null)
text = text.ToLower(); OnEvent.Invoke(this, new EventDataArgs(eve));
string[] array = text.Split(new char[1] { ' ' }, 4, StringSplitOptions.RemoveEmptyEntries); break;
switch (array[0])
{
case "connected":
Output.Add("Identifiaction succes");
break;
case "allreadytaken": case "ResultData":
Output.Add("Username Allready Taken"); ResultData res = (ResultData)packet;
break; ResultAdd(res);
break;
case "kick": default: //Ignore others Packets
if (array.Length > 1) break;
{ }
Output.Add("Kick : " + array[1]);
}
else
{
Output.Add("Kick by server");
}
_run = false;
break;
default:
Output.Add("Unknown action from server");
break;
}
}
else
{
Output.Add(text);
}
break;
case dataType.data:
Console.WriteLine("data");
break;
} }
Thread.Sleep(200); Thread.Sleep(config.refresh);
} }
Output.Add("/*exit*/"); //TODOOutput.Add("/*exit*/");
}
public int GetRequestId(bool indent = true)
{
if (indent) { RequestId++; }
return RequestId;
}
/// <summary>
/// Add to Results
/// </summary>
public void ResultAdd(ResultData res)
{
while (Results.Count + 1 > config.resultsBuffer) { Results.RemoveAt(0); } //Removes firsts
Results.Add(res);
} }
} }
} }

View File

@ -1,36 +1,20 @@
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
// Les informations générales relatives à un assembly dépendent de // Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations // l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly. // associées à un assembly.
[assembly: AssemblyTitle("Galactic Colors Control")] [assembly: AssemblyTitle("Galactic Colors Control")]
[assembly: AssemblyDescription("")] [assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")] [assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("sheychen")]
[assembly: AssemblyProduct("Galactic Colors Control")] [assembly: AssemblyProduct("Galactic Colors Control")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")] [assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")] [assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly // L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de // aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type. // COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)] [assembly: ComVisible(false)]
// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM // Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM
[assembly: Guid("93582ce8-c8c8-4e19-908b-d671ecbade25")] [assembly: Guid("93582ce8-c8c8-4e19-908b-d671ecbade25")]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
// en utilisant '*', comme indiqué ci-dessous :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.1.0")]
[assembly: AssemblyFileVersion("1.0.1.0")]

View File

@ -16,11 +16,16 @@ For GUI
Download last version for your system Download last version for your system
Linux
```
sudo apt-get install libopenal-dev mono-runtime
```
## Running ## Running
* Galactic_Colors_Control.exe => Client without GUI * Galactic_Colors_Control_Console.exe => Client without GUI
* Galactic_Colors_Control_GUI.exe => Client * Galactic_Colors_Control_GUI.exe => Client
* Galactic_Colors_Control_Server.exe => Server (Use --debug for DEBUG MODE) * Galactic_Colors_Control_Server.exe => Server (Use --debug for DEBUG MODE or --dev at your risks)
Linux Linux
``` ```
@ -34,6 +39,7 @@ mono <program>.exe --args
## Contributing ## Contributing
Get [Monogame](https://github.com/MonoGame/MonoGame) sdk and [MyMonoGame.GUI](https://github.com/sheychen290/MyMonoGame)
As you wish, I am opened to new ideas. As you wish, I am opened to new ideas.
## Author ## Author