1
0
Fork 0

Creation du protocol (WIP)

Creation d'un protocol (en cours)
This commit is contained in:
sheychen 2016-11-12 12:33:10 +01:00
parent 1cee2fc962
commit 493e16b9c5
62 changed files with 1456 additions and 1073 deletions

View File

@ -1,9 +1,7 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
//Common AssemblyInfo
// 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
// associées à un assembly.
[assembly: AssemblyCompany("sheychen")]
@ -12,11 +10,11 @@ using System.Runtime.InteropServices;
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// 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
// 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")]

View File

@ -0,0 +1,125 @@
using System;
using System.Linq;
using System.Text;
namespace Galactic_Colors_Control_Common
{
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;
}
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;
}
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);
}
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

@ -1,13 +1,45 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Galactic_Colors_Control_Common
{
public static class Common
{
public enum dataType { message, data };
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 += (str + Environment.NewLine);
}
}
return text;
}
public static string ArrayToString(int[] array)
{
string text = "";
foreach (int i in array)
{
text += (i.ToString() + Environment.NewLine);
}
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

@ -47,8 +47,14 @@
<Compile Include="..\AssemblyInfoCommon.cs">
<Link>Properties\AssemblyInfoCommon.cs</Link>
</Compile>
<Compile Include="Binary.cs" />
<Compile Include="Common.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Protocol\Data.cs" />
<Compile Include="Protocol\EventData.cs" />
<Compile Include="Protocol\RequestData.cs" />
<Compile Include="Protocol\RequestResult.cs" />
<Compile Include="Protocol\ResultData.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.

View File

@ -1,8 +1,7 @@
using System.Reflection;
using System.Runtime.CompilerServices;
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
// associées à un assembly.
[assembly: AssemblyTitle("Galactic Colors Control Common")]
@ -12,10 +11,10 @@ using System.Runtime.InteropServices;
[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
// 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")]
[assembly: Guid("022a69ce-22b5-4934-be9f-a9c6df9557ed")]

View File

@ -0,0 +1,40 @@
namespace Galactic_Colors_Control_Common.Protocol
{
public class Data
{
public enum DataType { Request, Result, Event };
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;
}
}
public virtual string ToSmallString()
{
return null;
}
public virtual string ToLongString()
{
return null;
}
public virtual byte[] ToBytes()
{
return new byte[0];
}
}
}

View File

@ -0,0 +1,37 @@
namespace Galactic_Colors_Control_Common.Protocol
{
public enum EventTypes { ChatMessage, ServerJoin, ServerLeave, ServerKick, PartyJoin, PartyLeave, PartyKick }
public class EventData : Data
{
public EventTypes type;
public string[] data;
public EventData(EventTypes p1, string[] p2 = null)
{
type = p1;
data = p2;
}
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,35 @@
namespace Galactic_Colors_Control_Common.Protocol
{
public class RequestData : Data
{
public int id;
public string[] args;
public RequestData(int p1, string[] p2)
{
id = p1;
args = p2;
}
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,14 @@
namespace Galactic_Colors_Control_Common.Protocol
{
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,47 @@
namespace Galactic_Colors_Control_Common.Protocol
{
public enum ResultTypes { Error, OK }
public class ResultData : Data
{
public int id;
public ResultTypes type;
public string[] result;
public ResultData(int p1, ResultTypes p2, string[] p3 = null)
{
id = p1;
type = p2;
result = p3;
}
public ResultData(int p1, RequestResult p2)
{
id = p1;
type = p2.type;
result = p2.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

@ -1,7 +1,7 @@
using System;
using Galactic_Colors_Control;
using System.Threading;
using Galactic_Colors_Control;
using System;
using System.Reflection;
using System.Threading;
namespace Galactic_Colors_Control_Console
{
@ -19,11 +19,11 @@ namespace Galactic_Colors_Control_Console
Write("Galactic Colors Control Client");
Write("Console " + Assembly.GetEntryAssembly().GetName().Version.ToString());
bool hostSet = false;
while(!hostSet)
while (!hostSet)
{
Write("Enter server host:");
string host = client.ValidateHost(Console.ReadLine());
if(host == null)
if (host == null)
{
foreach (string output in client.Output.ToArray())
{
@ -36,11 +36,11 @@ namespace Galactic_Colors_Control_Console
{
Write("Use " + host + "? y/n");
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();
}
if(c.Key == ConsoleKey.Y)
if (c.Key == ConsoleKey.Y)
{
hostSet = true;
}
@ -97,7 +97,7 @@ namespace Galactic_Colors_Control_Console
}
}
private static void Write( string text)
private static void Write(string text)
{
Console.Write("\b");
Console.WriteLine(text);

View File

@ -1,8 +1,7 @@
using System.Reflection;
using System.Runtime.CompilerServices;
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
// associées à un assembly.
[assembly: AssemblyTitle("Galactic Colors Control Console")]
@ -12,10 +11,10 @@ using System.Runtime.InteropServices;
[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
// 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("5d6a09d1-dcab-4fd8-b4e6-62d9f41ae8f0")]
[assembly: Guid("5d6a09d1-dcab-4fd8-b4e6-62d9f41ae8f0")]

View File

@ -1,15 +1,14 @@
using System;
using MyMonoGame.GUI;
using Galactic_Colors_Control;
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.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using MyMonoGame.GUI;
using System;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
using System.Threading;
namespace Galactic_Colors_Control_GUI
{
@ -18,9 +17,9 @@ namespace Galactic_Colors_Control_GUI
/// </summary>
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
ContentManager content;
private GraphicsDeviceManager graphics;
private SpriteBatch spriteBatch;
private ContentManager content;
private SoundEffect[] effects = new SoundEffect[4];
@ -44,11 +43,14 @@ namespace Galactic_Colors_Control_GUI
private string skinName;
private bool isFullScren = false;
private enum GameStatus { Home, Connect, Options, Game, Pause, End, Thanks,
private enum GameStatus
{
Home, Connect, Options, Game, Pause, End, Thanks,
Title,
Indentification,
Kick
}
private GameStatus gameStatus = GameStatus.Home;
private int ScreenWidth = 1280;
@ -56,7 +58,6 @@ namespace Galactic_Colors_Control_GUI
private string username = null;
private static Thread Writer;
private bool showOKMessage = false;
private string messageTitle;
private string messageText = string.Empty;
@ -65,6 +66,8 @@ namespace Galactic_Colors_Control_GUI
private bool showChat = false;
private string chatText = string.Empty;
private string chatInput = string.Empty;
private bool showParty = false;
private bool showOutput = true;
public Game1()
{
@ -116,7 +119,8 @@ namespace Galactic_Colors_Control_GUI
basicFont = content.Load<SpriteFont>("Fonts/basic");
titleFont = content.Load<SpriteFont>("Fonts/title");
for (int i = 0; i < pointerSprites.Length; i++) {
for (int i = 0; i < pointerSprites.Length; i++)
{
pointerSprites[i] = content.Load<Texture2D>("Textures/Hub/pointer" + i);
}
@ -154,7 +158,7 @@ namespace Galactic_Colors_Control_GUI
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"))
if (Directory.Exists("Skin/" + skinName + "/Textures/Hub/Buttons"))
{
for (int i = 0; i < buttonsSprites.Length; i++)
{
@ -177,8 +181,6 @@ namespace Galactic_Colors_Control_GUI
}
}
}
// TODO: use this.Content to load your game content here
}
/// <summary>
@ -187,7 +189,7 @@ namespace Galactic_Colors_Control_GUI
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
// Unload any non ContentManager content here
}
/// <summary>
@ -208,21 +210,22 @@ namespace Galactic_Colors_Control_GUI
break;
case GameStatus.Game:
if (client.Output.Count > 0)
{
string text = client.Output[0];
switch (text)
if (showOutput)
if (client.Output.Count > 0)
{
case "/clear":
chatText = string.Empty;
break;
string text = client.Output[0];
switch (text)
{
case "/clear":
chatText = string.Empty;
break;
default:
ChatAdd(text);
break;
default:
ChatAdd(text);
break;
}
client.Output.Remove(text);
}
client.Output.Remove(text);
}
if (!client.isRunning) { gameStatus = GameStatus.Kick; }
break;
}
@ -257,11 +260,13 @@ namespace Galactic_Colors_Control_GUI
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))) {
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(() => {
new Thread(() =>
{
while (acceleratorX < 5)
{
Thread.Sleep(20);
@ -274,10 +279,12 @@ namespace Galactic_Colors_Control_GUI
// 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))) {
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(() => {
new Thread(() =>
{
while (acceleratorX > 0)
{
Thread.Sleep(10);
@ -306,7 +313,8 @@ namespace Galactic_Colors_Control_GUI
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 {
else
{
if (showYNMessage)
{
GUI.Box(new Rectangle(ScreenWidth / 2 - 150, ScreenHeight / 4 + 50, 300, 100), buttonsSprites[0]);
@ -325,7 +333,8 @@ namespace Galactic_Colors_Control_GUI
showYNMessage = false;
}
}
else {
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)))
@ -365,7 +374,8 @@ namespace Galactic_Colors_Control_GUI
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 {
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)))
@ -389,14 +399,32 @@ namespace Galactic_Colors_Control_GUI
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; }
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 (GUI.Button(new Rectangle(65, 5, 50, 20), (showParty ? "Leave" : "Join") + " party", smallFont, new MyMonoGame.Colors(Color.White, Color.LightGray, Color.Gray))) { new Thread(PartyClick).Start(); }
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; } }
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);
}
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; }
}
}
break;
}
@ -412,16 +440,16 @@ namespace Galactic_Colors_Control_GUI
private void ValidateHost()
{
showLoading = true;
if ( username == null) { username = ""; }
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); }
foreach (string line in client.Output.ToArray()) { messageText += (line + Environment.NewLine); }
showOKMessage = true;
client.Output.Clear();
client.ResetHost();;
client.ResetHost(); ;
}
else
{
@ -455,27 +483,43 @@ namespace Galactic_Colors_Control_GUI
showLoading = true;
if (username != null)
{
if(username.Length > 3)
if (username.Length > 3)
{
client.Output.Clear();
client.SendRequest("/connect " + username);
bool wait = true;
while (wait)
int wait = 0;
while (wait < 20)
{
if (client.Output.Count > 0)
{
wait = false;
wait = 20;
}
else
{
wait++;
Thread.Sleep(200);
}
}
if(client.Output.Contains("Identifiaction succes"))
if (client.Output.Count > 0)
{
gameStatus = GameStatus.Game;
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();
}
}
else
{
messageTitle = "Error";
messageText = string.Empty;
foreach (string line in client.Output.ToArray()) { messageText += (line + Environment.NewLine); }
messageTitle = "Timeout";
messageText = "";
showOKMessage = true;
showLoading = false;
client.Output.Clear();
@ -485,6 +529,64 @@ namespace Galactic_Colors_Control_GUI
showLoading = false;
}
private void PartyClick()
{
showLoading = true;
GUI.ResetFocus();
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();
}
}
}
private void ChatAdd(string text)
{
chatText += ((chatText != string.Empty ? Environment.NewLine : "") + text);
@ -505,4 +607,4 @@ namespace Galactic_Colors_Control_GUI
}
}
}
}
}

View File

@ -1,25 +1,25 @@
<configuration>
<dllmap os="linux" dll="opengl32.dll" target="libGL.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="alut.dll" target="libalut.so.0"/>
<dllmap os="linux" dll="opencl.dll" target="libOpenCL.so"/>
<dllmap os="linux" dll="libX11" target="libX11.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="osx" dll="opengl32.dll" target="/System/Library/Frameworks/OpenGL.framework/OpenGL"/>
<dllmap os="linux" dll="opengl32.dll" target="libGL.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="alut.dll" target="libalut.so.0" />
<dllmap os="linux" dll="opencl.dll" target="libOpenCL.so" />
<dllmap os="linux" dll="libX11" target="libX11.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="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="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="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="opencl.dll" target="/System/Library/Frameworks/OpenCL.framework/OpenCL"/>
<dllmap os="osx" dll="SDL2.dll" target="libSDL2.dylib"/>
<dllmap os="osx" dll="opencl.dll" target="/System/Library/Frameworks/OpenCL.framework/OpenCL" />
<dllmap os="osx" dll="SDL2.dll" target="libSDL2.dylib" />
<!-- XQuartz compatibility (X11 on Mac) -->
<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="libXcursor.so.1" target="/usr/X11/lib/libXcursor.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="libXrandr.so.2" target="/usr/X11/lib/libXrandr.dylib"/>
</configuration>
<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="libXcursor.so.1" target="/usr/X11/lib/libXcursor.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="libXrandr.so.2" target="/usr/X11/lib/libXrandr.dylib" />
</configuration>

View File

@ -11,10 +11,10 @@ namespace Galactic_Colors_Control_GUI
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
private static void Main()
{
using (var game = new Game1())
game.Run();
}
}
}
}

View File

@ -1,8 +1,7 @@
using System.Reflection;
using System.Runtime.CompilerServices;
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
// associated with an assembly.
[assembly: AssemblyTitle("Galactic Colors Control GUI")]
@ -12,10 +11,10 @@ using System.Runtime.InteropServices;
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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
// 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
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// 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")]

View File

@ -4,7 +4,7 @@ using System.IO;
namespace Galactic_Colors_Control_GUI
{
static class Utilities
internal static class Utilities
{
/// <summary>
/// Load Texture2D from files
@ -38,4 +38,4 @@ namespace Galactic_Colors_Control_GUI
}
}
}
}
}

View File

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

View File

@ -1,6 +1,4 @@
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server
namespace Galactic_Colors_Control_Server
{
public class Client
{

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;
namespace Galactic_Colors_Control_Server.Commands
@ -7,7 +9,7 @@ namespace Galactic_Colors_Control_Server.Commands
{
public string Name { get { return "clear"; } }
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 IsClient { get { return true; } }
@ -16,10 +18,18 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { 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();
Console.Write(">");
if (server)
{
Console.Clear();
Console.Write(">");
return new RequestResult(ResultTypes.OK);
}
else
{
return new RequestResult(ResultTypes.Error, Common.Strings("Client Side"));
}
}
}
}
}

View File

@ -1,4 +1,5 @@
using System;
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
@ -7,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands
{
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 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; } }
@ -16,9 +17,9 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { 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(Program.clients.Count + "/" + Program.config.size, soc, server);
return new RequestResult(ResultTypes.OK, Common.Strings(Program.clients.Count.ToString(), Program.config.size.ToString()));
}
}
}
}

View File

@ -1,7 +1,5 @@
using Galactic_Colors_Control_Common;
using System;
using System.Collections.Generic;
using System.Linq;
using Galactic_Colors_Control_Common.Protocol;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
@ -10,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands
{
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 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; } }
@ -19,29 +17,27 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { 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)
{
Socket target = null;
foreach(Socket client in Program.clients.Keys)
foreach (Socket client in Program.clients.Keys)
{
if(Utilities.GetName(client) == args[2]) { target = client; }
if (Utilities.GetName(client) == args[2]) { target = client; }
}
if (target != null)
if (target == null)
return new RequestResult(ResultTypes.Error, Common.Strings("Can't find"));
Logger.Write(args[2] + " was kick by server.", Logger.logType.info, Logger.logConsole.show);
if (args.Length > 2)
{
Logger.Write(args[2] + " was kick by server.", Logger.logType.info);
if (args.Length > 2)
{
Utilities.Send(target, "/kick " + args[3], Common.dataType.message);
Logger.Write("because" + args[2], Logger.logType.debug);
}
else {
Utilities.Send(target, "/kick", Common.dataType.message);
}
Utilities.Send(target, new EventData(EventTypes.ServerKick, Common.Strings(args[3])));
Logger.Write("because" + args[3], Logger.logType.debug);
}
else
{
Utilities.Return("Can't find " + args[2], soc, server);
Utilities.Send(target, new EventData(EventTypes.ServerKick));
}
return new RequestResult(ResultTypes.OK);
}
}
}
}

View File

@ -1,4 +1,5 @@
using System;
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
@ -7,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands
{
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 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; } }
@ -16,15 +17,29 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { 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)
{
string text = " ";
foreach (Socket socket in Program.clients.Keys)
if (server)
{
text += (Utilities.GetName(socket) + ", ");
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);
}
text = text.Remove(text.Length - 2, 2);
Utilities.Return(text, soc, server);
}
}
}
}

View File

@ -1,4 +1,5 @@
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System;
using System.Net;
using System.Net.Sockets;
@ -9,37 +10,33 @@ namespace Galactic_Colors_Control_Server.Commands
{
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 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 true; } }
public bool IsNoConnect { get { return false; } }
public int minArgs { 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)
{
Socket target = null;
foreach (Socket client in Program.clients.Keys)
{
if (Utilities.GetName(client) == args[2]) { target = client; }
}
if (target != null)
if (target == null)
return new RequestResult(ResultTypes.Error, Common.Strings("Can't find"));
string text = "";
text += ("Name : " + Utilities.GetName(target) + Environment.NewLine);
text += ("IP : " + ((IPEndPoint)target.LocalEndPoint).Address.ToString() + Environment.NewLine);
if (Program.clients[target].party != null)
{
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);
}
Utilities.ConsoleWrite(text);
}
else
{
Utilities.Return("Can't find " + args[2], soc, server);
text += ("Party : " + Program.clients[target].party + Environment.NewLine);
}
return new RequestResult(ResultTypes.OK, Common.Strings(text));
}
}
}
}

View File

@ -1,7 +1,7 @@
using System;
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System.Net;
using System.Net.Sockets;
using Galactic_Colors_Control_Common;
namespace Galactic_Colors_Control_Server.Commands
{
@ -9,7 +9,7 @@ namespace Galactic_Colors_Control_Server.Commands
{
public string Name { get { return "connect"; } }
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 IsClient { get { return true; } }
@ -18,34 +18,29 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { 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("Too Short"));
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);
bool allreadyconnected = false;
foreach(Client 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", Common.dataType.message);
Utilities.Broadcast(args[1] + " joined the server", Common.dataType.message);
Logger.Write("Identified as " + Utilities.GetName(soc) + " form " + ((IPEndPoint)soc.LocalEndPoint).Address.ToString(), Logger.logType.info);
}
else
{
Utilities.Send(soc, "/allreadytaken", Common.dataType.message);
}
}
else
{
Utilities.Send(soc, "You are allready " + Utilities.GetName(soc), Common.dataType.message);
if (client.pseudo == args[1]) { allreadyconnected = true; break; }
}
if (allreadyconnected)
return new RequestResult(ResultTypes.Error, Common.Strings("Taken"));
Program.clients[soc].status = 0;
Program.clients[soc].pseudo = args[1];
Utilities.Broadcast(new EventData(EventTypes.ServerJoin, Common.Strings(args[1])));
Logger.Write("Identified as " + Utilities.GetName(soc) + " form " + ((IPEndPoint)soc.LocalEndPoint).Address.ToString(), Logger.logType.info);
return new RequestResult(ResultTypes.OK, Common.Strings(args[1]));
}
}
}
}

View File

@ -1,5 +1,5 @@
using Galactic_Colors_Control_Common;
using System;
using Galactic_Colors_Control_Common.Protocol;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
@ -8,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands
{
public string Name { get { return "exit"; } }
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 Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } }
public bool IsServer { get { return false; } }
public bool IsClient { get { return true; } }
@ -17,7 +17,7 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { 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)
{
soc.Shutdown(SocketShutdown.Both);
Logger.Write("Client disconnected from " + Utilities.GetName(soc), Logger.logType.info);
@ -25,8 +25,9 @@ namespace Galactic_Colors_Control_Server.Commands
bool connected = Program.clients[soc].status != -1;
soc.Close();
Program.clients.Remove(soc);
if (connected) { Utilities.Broadcast(username + " leave the server", Common.dataType.message); }
if (connected) { Utilities.Broadcast(new EventData(EventTypes.ServerLeave, Common.Strings(username))); }
Logger.Write("Size: " + Program.clients.Count + "/" + Program.config.size, Logger.logType.debug);
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.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
@ -9,7 +11,7 @@ namespace Galactic_Colors_Control_Server.Commands
{
public string Name { get { return "help"; } }
public string DescText { get { return "Shows the help."; } }
public string HelpText { get { return "Use /help [command] to display command help. (-all for full 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 IsClient { get { return true; } }
@ -18,7 +20,7 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { get { return 0; } }
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)
{
bool isGroup = false;
bool isAll = false;
@ -33,7 +35,7 @@ namespace Galactic_Colors_Control_Server.Commands
List<ICommand> list = new List<ICommand>();
foreach (ICommand com in Manager.commands)
{
if(Manager.CanAccess(com, soc, server))
if (Manager.CanAccess(com, soc, server))
{
if (!isGroup || (isGroup && com.Group == (Manager.CommandGroup)Enum.Parse(typeof(Manager.CommandGroup), args[1])))
{
@ -42,14 +44,14 @@ namespace Galactic_Colors_Control_Server.Commands
}
}
}
list.Sort((x,y) => x.Group.CompareTo(y.Group));
string text = "Use /help [command] for more informations." + Environment.NewLine + "Available commands:" + Environment.NewLine;
list.Sort((x, y) => x.Group.CompareTo(y.Group));
string text = "Use 'help [command]' for more informations." + Environment.NewLine + "Available commands:" + Environment.NewLine;
Manager.CommandGroup actualGroup = 0;
foreach (ICommand com in list)
{
if(com.Group != actualGroup)
if (com.Group != actualGroup)
{
text += (Environment.NewLine + " " + com.Group.ToString() + Environment.NewLine + ((isGroup || isAll) ? "" : (" Use /help " + com.Group.ToString())));
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))
@ -57,28 +59,20 @@ namespace Galactic_Colors_Control_Server.Commands
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
{
ICommand command = null;
args = args.Skip(1).ToArray();
if (Manager.TryGetCommand(args, ref command))
{
if (Manager.CanAccess(command, soc, server))
{
Utilities.Return(command.HelpText, soc, server);
}
else
{
Utilities.Return("Any help for " + Manager.CommandToString(args), soc, server);
}
}
else
{
Utilities.Return("Any help for " + Manager.CommandToString(args), soc, server);
}
if (!Manager.TryGetCommand(args, ref command))
return new RequestResult(ResultTypes.Error, Common.Strings("Any Command"));
if (!Manager.CanAccess(command, soc, server))
return new RequestResult(ResultTypes.Error, Common.Strings("Any Command"));
return new RequestResult(ResultTypes.OK, Common.Strings(command.HelpText));
}
}
}
}
}

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
{
@ -15,6 +16,6 @@ namespace Galactic_Colors_Control_Server.Commands
int minArgs { 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,4 +1,6 @@
using System;
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
@ -7,7 +9,7 @@ namespace Galactic_Colors_Control_Server.Commands
{
public string Name { get { return "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 IsClient { get { return false; } }
@ -16,16 +18,16 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { 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))
{
Utilities.ConsoleWrite("LogLevel: " + Program.config.logLevel.ToString());
return new RequestResult(ResultTypes.OK, Common.Strings(Program.config.logLevel.ToString()));
}
else
{
Utilities.ConsoleWrite("Incorrect argument (debug, info, important, error, fatal)");
return new RequestResult(ResultTypes.Error, Common.Strings("Incorrect argument"));
}
}
}
}
}

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.Linq;
using System.Net.Sockets;
@ -9,7 +11,10 @@ namespace Galactic_Colors_Control_Server.Commands
public class Manager
{
public static List<ICommand> commands { get; private set; } = new List<ICommand>();
public enum CommandGroup { root, server, party, client}
public enum CommandGroup { root, server, party, client }
private static RequestResult AnyCommand = new RequestResult(ResultTypes.Error, Common.Strings("Any Command"));
/// <summary>
/// Find all ICommand and add them to commands
@ -31,52 +36,39 @@ namespace Galactic_Colors_Control_Server.Commands
/// <param name="args">command with args</param>
/// <param name="soc">Sender socket</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)
{
ICommand command = null;
if (TryGetCommand(args, ref command))
{
if (CanAccess(command, soc, server))
{
if (!server && command.IsClientSide)
{
Utilities.Return("It's a client side command", soc, server);
}
else
{
if (args.Length - (command.Group == 0 ? 0 : 1) > command.minArgs)
{
if (args.Length - (command.Group == 0 ? 1 : 2) <= command.maxArgs)
{
command.Execute(args, soc, server);
}
else
{
Utilities.Return("Command " + CommandToString(command) + " require at most " + command.maxArgs + " argument(s).", soc, server);
}
}
if (!TryGetCommand(args, ref command))
return AnyCommand;
else
{
Utilities.Return("Command " + CommandToString(command) + " require at least " + command.minArgs + " argument(s).", soc, server);
}
}
}
else
{
Utilities.Return("Unknown command : " + CommandToString(args), soc, server);
}
}
else
if (!CanAccess(command, soc, server))
return AnyCommand;
if (!server && command.IsClientSide)
return new RequestResult(ResultTypes.Error, Common.Strings("Client Side"));
if (args.Length - (command.Group == 0 ? 0 : 1) <= command.minArgs)
return new RequestResult(ResultTypes.Error, new string[2] { "Too Short", command.minArgs.ToString() });
if (args.Length - (command.Group == 0 ? 1 : 2) > command.maxArgs)
return new RequestResult(ResultTypes.Error, new string[2] { "Too Long", command.maxArgs.ToString() });
try
{
Utilities.Return("Unknown command : " + CommandToString(args), soc, server);
return command.Execute(args, soc, server);
}
catch (Exception e)
{
Logger.Write("Command " + args[0] + " Exception : " + e.Message, Logger.logType.error);
return new RequestResult(ResultTypes.Error, Common.Strings("Execute Exception"));
}
}
public static string CommandToString(ICommand command)
{
string text = "";
if(command.Group != 0) { text += (command.Group.ToString() + " "); }
if (command.Group != 0) { text += (command.Group.ToString() + " "); }
text += command.Name;
return text;
}
@ -90,7 +82,7 @@ namespace Galactic_Colors_Control_Server.Commands
if (args.Length > 0)
{
string text = "";
foreach(string arg in args)
foreach (string arg in args)
{
text += (arg + " ");
}
@ -151,7 +143,7 @@ namespace Galactic_Colors_Control_Server.Commands
{
if (command.IsClient)
{
if(!Utilities.IsConnect(soc))
if (!Utilities.IsConnect(soc))
{
return command.IsNoConnect;
}
@ -167,4 +159,4 @@ namespace Galactic_Colors_Control_Server.Commands
}
}
}
}
}

View File

@ -1,4 +1,5 @@
using System;
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
@ -7,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands
{
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 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; } }
@ -16,18 +17,20 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { 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)
{
int partyId = -1;
if (Utilities.AccessParty(ref partyId, false, soc, server))
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)
{
string text = " ";
foreach(Socket client in Program.parties[partyId].clients)
{
text += (Utilities.GetName(client) + Environment.NewLine + " ");
}
Utilities.Return(text, soc, server);
data[i] = Utilities.GetName(client);
i++;
}
return new RequestResult(ResultTypes.OK, data);
}
}
}
}

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
{
@ -6,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands
{
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 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; } }
@ -15,21 +17,17 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { 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)
{
int partyId = -1;
if (Utilities.AccessParty(ref partyId, true,soc, server))
{
if (Program.parties[partyId].open)
{
Program.parties[partyId].open = false;
Utilities.Return("Party closed", soc, server);
}
else
{
Utilities.Return("Party allready close", soc, server);
}
}
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

@ -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
{
@ -6,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands
{
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 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; } }
@ -15,48 +17,32 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { get { return 2; } }
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 (server || (!server && Program.clients[soc].partyID == -1))
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("Too Small"));
if (size > Program.config.size)
return new RequestResult(ResultTypes.Error, Common.Strings("Too Big"));
Program.AddParty(new Party(args[2], size, Utilities.GetName(soc)));
Logger.Write("Party " + args[2] + " create with " + size + " slots as " + Program.GetPartyID(false), Logger.logType.info);
if (server)
{
int size;
if (int.TryParse(args[3], out size))
{
if (size > 0)
{
if (size <= Program.config.size)
{
Logger.Write("Party " + args[2] + " create with " + size + " slots as " + Program.partyID, Logger.logType.info);
Program.AddParty(new Party(args[2], size, Utilities.GetName(soc)));
if (server)
{
Program.selectedParty = Program.partyID-1;
}
else
{
Program.clients[soc].partyID = Program.partyID-1;
Utilities.Return("Party " + args[2] + " create with " + size + " slots as " + (Program.partyID-1), soc, server);
}
}
else
{
Utilities.Return("Too big size", soc, server);
}
}
else
{
Utilities.Return("Too small size", soc, server);
}
}
else
{
Utilities.Return("Incorrect argument " + args[3], soc, server);
}
Program.selectedParty = Program.GetPartyID(false);
}
else
{
Utilities.Return("Allready in a party.", soc, server);
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

@ -1,4 +1,6 @@
using System;
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
@ -7,7 +9,7 @@ namespace Galactic_Colors_Control_Server.Commands
{
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 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; } }
@ -16,66 +18,44 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { 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 ((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("Any Party"));
if (!Program.parties.ContainsKey(id))
return new RequestResult(ResultTypes.Error, Common.Strings("Can't Find"));
Party party = Program.parties[id];
if (args.Length == 3)
{
int id;
if (int.TryParse(args[2], out id))
{
if (Program.parties.ContainsKey(id))
{
Party party = Program.parties[id];
if (args.Length == 3)
{
Array.Resize(ref args, 4);
args[3] = "";
}
if (server || (!server && party.TestPassword(args[3])))
{
if(server)
{
Program.selectedParty = id;
}
else
{
if(party.open)
{
if (party.clients.Count < party.size)
{
Program.clients[soc].partyID = id;
Utilities.BroadcastParty(Utilities.GetName(soc) + " join the party", Galactic_Colors_Control_Common.Common.dataType.message, id);
}
else
{
Utilities.Return("Party is full", soc, server);
}
}
else
{
Utilities.Return("Party close", soc, server);
}
}
}
else
{
Utilities.Return("Wrong party password", soc, server);
}
}
else
{
Utilities.Return("Can't find party " + id, soc, server);
}
}
else
{
Utilities.Return("Incorrect argument " + args[3], soc, server);
}
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
{
Utilities.Return("Allready in a party.", soc, server);
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

@ -1,4 +1,5 @@
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
@ -7,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands
{
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 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; } }
@ -16,34 +17,22 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { 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)
{
int partyId = -1;
if (Utilities.AccessParty(ref partyId, true, soc, server))
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)
{
Socket target = null;
foreach (Socket client in Program.parties[partyId].clients)
{
if (Utilities.GetName(client) == args[2]) { target = client; }
}
if (target != null)
{
Utilities.BroadcastParty(args[2] + " was kick", Common.dataType.message, partyId);
if (args.Length > 3)
{
Utilities.Send(target, "/party kick " + args[3], Common.dataType.message);
}
else
{
Utilities.Send(target, "/party kick", Common.dataType.message);
}
Manager.Execute(new string[2] { "party", "leave" },target,false);
}
else
{
Utilities.Return("Can't find " + args[2] + "in party", soc, server);
}
if (Utilities.GetName(client) == args[2]) { target = client; }
}
if (target == null)
return new RequestResult(ResultTypes.Error, Common.Strings("Can't find"));
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

@ -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
{
@ -6,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands
{
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 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; } }
@ -15,28 +17,26 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { 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)
{
Program.selectedParty = -1;
return new RequestResult(ResultTypes.OK);
}
else
{
int partyId = -1;
if (Utilities.AccessParty(ref partyId, false, soc, server))
{
if (!Program.parties[partyId].IsOwner(Utilities.GetName(soc)))
{
Utilities.BroadcastParty(Utilities.GetName(soc) + " leave the party", Galactic_Colors_Control_Common.Common.dataType.message, partyId);
Program.clients[soc].partyID = -1;
}
else
{
Utilities.Return("Owner can't leave party. Look for /party stop", soc, server);
}
}
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

@ -1,4 +1,5 @@
using System;
using Galactic_Colors_Control_Common.Protocol;
using System;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
@ -7,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands
{
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 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; } }
@ -16,15 +17,17 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { 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)
{
string text = " ";
string[] text = new string[Program.parties.Keys.Count];
int i = 0;
foreach (int key in Program.parties.Keys)
{
Party party = Program.parties[key];
text += (key + " : " + party.name + " : " + party.count + "/" + party.size + " : " + (party.open ? (party.isPrivate ? "private" : "open") : "close") + Environment.NewLine + " ");
text[i] = (key + " : " + party.name + " : " + party.count + "/" + party.size + " : " + (party.open ? (party.isPrivate ? "private" : "open") : "close") + Environment.NewLine + " ");
i++;
}
Utilities.Return(text, soc, server);
return new RequestResult(ResultTypes.OK, text);
}
}
}
}

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
{
@ -6,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands
{
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 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; } }
@ -15,21 +17,17 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { 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)
{
int partyId = -1;
if (Utilities.AccessParty(ref partyId, true, soc, server))
{
if (!Program.parties[partyId].open)
{
Program.parties[partyId].open = true;
Utilities.Return("Party opened", soc, server);
}
else
{
Utilities.Return("Party allready open", soc, server);
}
}
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

@ -1,4 +1,6 @@
using System;
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
@ -7,7 +9,7 @@ namespace Galactic_Colors_Control_Server.Commands
{
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 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; } }
@ -16,25 +18,22 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { 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)
{
int partyId = -1;
if (Utilities.AccessParty(ref partyId, true, soc, server))
if (Utilities.AccessParty(ref partyId, args, true, soc, server))
return new RequestResult(ResultTypes.Error, Common.Strings("Access"));
if (args.Length == 3)
{
if (args.Length == 3)
{
Array.Resize(ref args, 4);
args[3] = "";
}
if (Program.parties[partyId].SetPassword(args[2],args[3]))
{
Utilities.Return("Password changed", soc, server);
}
else
{
Utilities.Return("Can't change password", soc, server);
}
Array.Resize(ref args, 4);
args[3] = "";
}
if (!Program.parties[partyId].SetPassword(args[2], args[3]))
return new RequestResult(ResultTypes.Error, Common.Strings("Can't Change"));
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;
namespace Galactic_Colors_Control_Server.Commands
@ -7,7 +9,7 @@ namespace Galactic_Colors_Control_Server.Commands
{
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 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; } }
@ -16,18 +18,25 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { 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)
{
int partyId = -1;
if (Utilities.AccessParty(ref partyId, false, soc, server))
if (!Utilities.AccessParty(ref partyId, args, false, soc, server))
return new RequestResult(ResultTypes.Error, Common.Strings("Access"));
Party party = Program.parties[partyId];
if (server)
{
Party party = Program.parties[partyId];
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")));
Utilities.Return(text,soc,server);
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

@ -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
{
@ -6,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands
{
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 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; } }
@ -15,19 +17,20 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { 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)
{
int partyId = -1;
if (Utilities.AccessParty(ref partyId, true, soc, server))
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)
{
foreach(Socket client in Program.parties[partyId].clients)
{
Manager.Execute(new string[4] { "party","kick",Utilities.GetName(client),"stop_party" } ,soc,server);
}
Logger.Write("Party " + Program.parties[partyId].name + " closed", Logger.logType.info);
if(Program.selectedParty == partyId) { Program.selectedParty = -1; }
Program.parties.Remove(partyId);
Manager.Execute(new string[4] { "party", "kick", Utilities.GetName(client), "stop_party" }, soc, server);
}
Logger.Write("Party " + Program.parties[partyId].name + " closed", Logger.logType.info, server ? Logger.logConsole.show : Logger.logConsole.normal);
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
{
@ -6,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands
{
public string Name { get { return "ping"; } }
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 IsClient { get { return true; } }
@ -15,9 +17,9 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { 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("Client Side"));
}
}
}
}

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("Any Message"));
if (!Utilities.IsConnect(soc))
return new RequestResult(ResultTypes.Error, Common.Strings("Must Be Connected"));
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

@ -1,4 +1,5 @@
using System;
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
@ -7,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands
{
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 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; } }
@ -16,17 +17,14 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { 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 (Program._open)
{
Program._open = false;
Logger.Write("Server closed", Logger.logType.warm);
}
else
{
Utilities.ConsoleWrite("Server allready close");
}
if (!Program._open)
return new RequestResult(ResultTypes.Error, Common.Strings("Allready"));
Program._open = false;
Logger.Write("Server closed", Logger.logType.warm, Logger.logConsole.show);
return new RequestResult(ResultTypes.OK);
}
}
}
}

View File

@ -1,4 +1,5 @@
using System;
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
@ -7,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands
{
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 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; } }
@ -16,17 +17,14 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { 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 (!Program._open)
{
Program._open = true;
Logger.Write("Server opened", Logger.logType.warm);
}
else
{
Utilities.ConsoleWrite("Server allready open");
}
if (Program._open)
return new RequestResult(ResultTypes.Error, Common.Strings("Allready"));
Program._open = true;
Logger.Write("Server opened", Logger.logType.warm, Logger.logConsole.show);
return new RequestResult(ResultTypes.OK);
}
}
}
}

View File

@ -1,4 +1,5 @@
using System;
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
@ -7,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands
{
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 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; } }
@ -16,18 +17,13 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { 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 (Program._open)
{
Utilities.ConsoleWrite("Server : open", ConsoleColor.Green);
}
else
{
Utilities.ConsoleWrite("Server : close", ConsoleColor.Red);
}
Utilities.ConsoleWrite("Clients : " + Program.clients.Count + "/" + Program.config.size);
Utilities.ConsoleWrite("Parties : " + Program.parties.Count);
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

@ -1,5 +1,4 @@
using Galactic_Colors_Control_Common;
using System;
using Galactic_Colors_Control_Common.Protocol;
using System.Net.Sockets;
namespace Galactic_Colors_Control_Server.Commands
@ -8,7 +7,7 @@ namespace Galactic_Colors_Control_Server.Commands
{
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 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; } }
@ -17,10 +16,10 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { 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)
{
Program._run = false;
Utilities.ConsoleWrite("Stop server");
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;
namespace Galactic_Colors_Control_Server.Commands
@ -7,7 +9,7 @@ namespace Galactic_Colors_Control_Server.Commands
{
public string Name { get { return "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 IsClient { get { return true; } }
@ -16,9 +18,9 @@ namespace Galactic_Colors_Control_Server.Commands
public int minArgs { 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,9 +1,5 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
@ -16,8 +12,8 @@ namespace Galactic_Colors_Control_Server
public Logger.logType logLevel = Logger.logType.info;
public int port = 25001;
public int size = 20;
public ConsoleColor[] logForeColor = new ConsoleColor[5] {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[] 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 };
/// <summary>
/// Load config from xml file
@ -41,6 +37,7 @@ namespace Galactic_Colors_Control_Server
else
{
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();
}
@ -51,6 +48,7 @@ namespace Galactic_Colors_Control_Server
config.Save();
}
if (Program._debug) { config.logLevel = Logger.logType.debug; }
if (Program._dev) { config.logLevel = Logger.logType.dev; }
return config;
}
@ -60,12 +58,13 @@ namespace Galactic_Colors_Control_Server
public void Save()
{
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"))
{
xs.Serialize(st,this);
xs.Serialize(st, this);
};
if (Program._debug) { logLevel = Logger.logType.debug; }
if (Program._dev) { logLevel = Logger.logType.dev; }
}
/// <summary>
@ -114,4 +113,4 @@ namespace Galactic_Colors_Control_Server
return isCorrect;
}
}
}
}

View File

@ -24,4 +24,4 @@
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xs:schema>
</xs:schema>

View File

@ -59,6 +59,8 @@
<Compile Include="Client.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" />

View File

@ -4,14 +4,16 @@ 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 }
public enum logType { dev, debug, info, warm, error, fatal }
public enum logConsole { normal, show, hide }
private static List<Log> toWriteLogs = new List<Log>();
private static string logPath;
public static Thread Updater;
@ -21,11 +23,13 @@ namespace Galactic_Colors_Control_Server
{
public string text;
public logType type;
public logConsole console;
public Log(string p1, logType p2)
public Log(string p1, logType p2, logConsole p3 = logConsole.normal)
{
text = p1;
type = p2;
console = p3;
}
}
@ -34,15 +38,16 @@ namespace Galactic_Colors_Control_Server
/// </summary>
public static void Initialise()
{
if (!Directory.Exists(Program.config.logPath)) {
if (!Directory.Exists(Program.config.logPath))
{
Directory.CreateDirectory(Program.config.logPath);
Write("Log Directory Created" ,logType.info);
Write("Log Directory Created", logType.info);
}
else
{
//Sort old logs
string[] files = Directory.GetFiles(Program.config.logPath);
foreach(string file in files)
foreach (string file in files)
{
if (Path.GetExtension(file) == ".log")
{
@ -55,7 +60,7 @@ namespace Galactic_Colors_Control_Server
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 (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))
{
@ -69,7 +74,7 @@ namespace Galactic_Colors_Control_Server
}
}
int i = 0;
while(File.Exists(Program.config.logPath + "/" + DateTime.UtcNow.ToString("yyyy-MM-dd-", CultureInfo.InvariantCulture) + i + ".log")) { i++; }
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));
@ -81,9 +86,10 @@ namespace Galactic_Colors_Control_Server
/// </summary>
/// <param name="text">Log text</param>
/// <param name="type">Log status</param>
public static void Write(string text, logType type)
/// <param name="console">Server display modifier</param>
public static void Write(string text, logType type, logConsole console = logConsole.normal)
{
Write(new Log(text, type));
Write(new Log(text, type, console));
}
/// <summary>
@ -92,15 +98,12 @@ namespace Galactic_Colors_Control_Server
/// <param name="log">Log struct</param>
public static void Write(Log log)
{
if (log.type != logType.debug || Program.config.logLevel == logType.debug)
if (Program.config.logLevel == logType.debug || Program.config.logLevel == logType.dev)
{
if(Program._debug)
{
//Add Source Method
log.text = "[" + new StackTrace().GetFrame(2).GetMethod().Name + "]: " + log.text;
}
toWriteLogs.Add(log);
//Add Source Method
log.text = "[" + new StackTrace().GetFrame(2).GetMethod().Name + "]: " + log.text;
}
toWriteLogs.Add(log);
}
/// <summary>
@ -110,18 +113,36 @@ namespace Galactic_Colors_Control_Server
{
while (_run || toWriteLogs.Count > 0)
{
while(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(">");
if (log.type >= Program.config.logLevel)
{
File.AppendAllText(logPath, DateTime.UtcNow.ToString("[yyyy-MM-dd]", CultureInfo.InvariantCulture) + " [" + log.type.ToString().ToUpper() + "]: " + log.text + Environment.NewLine);
if (log.console != logConsole.hide)
{
Console.BackgroundColor = Program.config.logBackColor[(int)log.type];
Console.ForegroundColor = Program.config.logForeColor[(int)log.type];
Console.Write("\b");
Console.WriteLine(DateTime.UtcNow.ToString("[yyyy-MM-dd]", CultureInfo.InvariantCulture) + ": " + log.text);
Utilities.ConsoleResetColor();
Console.Write(">");
}
}
//TODO reactive show logger
/*
else
{
if(log.console == logConsole.show)
{
Console.BackgroundColor = Program.config.logBackColor[(int)log.type];
Console.ForegroundColor = Program.config.logForeColor[(int)log.type];
Console.Write("\b");
Console.WriteLine(DateTime.UtcNow.ToString("[yyyy-MM-dd]", CultureInfo.InvariantCulture) + ": " + log.text);
Utilities.ConsoleResetColor();
Console.Write(">");
}
}*/
toWriteLogs.Remove(log);
}
Thread.Sleep(200);

View File

@ -28,7 +28,7 @@ namespace Galactic_Colors_Control_Server
{
if (isPrivate)
{
return (password == pass) ;
return (password == pass);
}
else
{
@ -62,9 +62,9 @@ namespace Galactic_Colors_Control_Server
get
{
List<Socket> list = new List<Socket>();
foreach(Socket soc in Program.clients.Keys)
foreach (Socket soc in Program.clients.Keys)
{
if(Program.clients[soc].party == this) { list.Add(soc); }
if (Program.clients[soc].party == this) { list.Add(soc); }
}
return list;
}

View File

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

View File

@ -1,14 +1,11 @@
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
namespace Galactic_Colors_Control_Server
{
class Utilities
internal class Utilities
{
/// <summary>
/// Check if socket is connect
@ -16,22 +13,14 @@ namespace Galactic_Colors_Control_Server
/// <param name="soc">Client socket</param>
public static bool IsConnect(Socket soc)
{
if(soc == null)
{
if (soc == null)
return true;
}
else
{
if (Program.clients.ContainsKey(soc))
{
return Program.clients[soc].status != -1;
}
else
{
Logger.Write("IsConnect : Unknown client", Logger.logType.error);
return true;
}
}
if (Program.clients.ContainsKey(soc))
return Program.clients[soc].status != -1;
Logger.Write("IsConnect : Unknown client", Logger.logType.error);
return false;
}
/// <summary>
@ -41,23 +30,23 @@ namespace Galactic_Colors_Control_Server
/// <returns>Name</returns>
public static string GetName(Socket soc)
{
if (soc != null)
{
if (Program.clients.ContainsKey(soc))
{
string res = Program.clients[soc].pseudo;
if (res == "") { res = ((IPEndPoint)soc.LocalEndPoint).Address.ToString(); }
return res;
}
else
{
return "?";
}
}
else
{
if (soc == null)
return "Server";
}
if (!Program.clients.ContainsKey(soc))
return "?";
string res = Program.clients[soc].pseudo;
if (res == "") { res = ((IPEndPoint)soc.LocalEndPoint).Address.ToString(); }
return res;
}
public static int GetParty(Socket soc)
{
if (soc == null)
return Program.selectedParty;
return Program.clients[soc].partyID;
}
/// <summary>
@ -91,40 +80,23 @@ namespace Galactic_Colors_Control_Server
/// </summary>
/// <param name="soc">Target socket</param>
/// <param name="data">Data to send</param>
/// <param name="dtype">Type of data</param>
public static void Send(Socket soc, object data, Common.dataType dtype)
public static void Send(Socket soc, Data packet)
{
/*
Format:
0-3: dataType
4-x: data
*/
byte[] type = new byte[4];
type = BitConverter.GetBytes((int)dtype);
byte[] bytes = null;
switch (dtype)
if (soc.Connected)
{
case Common.dataType.message:
bytes = Encoding.ASCII.GetBytes((string)data);
break;
case Common.dataType.data:
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
try
{
soc.Send(packet.ToBytes());
if (Program.config.logLevel == Logger.logType.dev)
{
bf.Serialize(ms, data);
bytes = ms.ToArray();
Logger.Write("Send to " + GetName(soc) + " : " + packet.ToLongString(), Logger.logType.dev);
}
break;
default:
bytes = new byte[] { 1 };
break;
}
catch (Exception e)
{
Logger.Write("Send exception to " + GetName(soc) + " : " + e.Message, Logger.logType.error);
}
}
byte[] final = new byte[type.Length + bytes.Length];
type.CopyTo(final, 0);
bytes.CopyTo(final, type.Length);
soc.Send(final);
}
/// <summary>
@ -132,13 +104,14 @@ namespace Galactic_Colors_Control_Server
/// </summary>
/// <param name="data">Data to send</param>
/// <param name="dtype">Type of data</param>
public static void Broadcast(object data, Common.dataType dtype)
/// <param name="message">Message to display for server</param>
public static void Broadcast(Data packet)
{
foreach (Socket soc in Program.clients.Keys)
{
Send(soc, data, dtype);
Send(soc, packet);
}
if (dtype == Common.dataType.message) { ConsoleWrite((string)data); }
ConsoleWrite(packet.ToSmallString());
}
/// <summary>
@ -147,33 +120,38 @@ namespace Galactic_Colors_Control_Server
/// <param name="data">Data to send</param>
/// <param name="dtype">Type of data</param>
/// <param name="party">Id of the party</param>
public static void BroadcastParty(object data, Common.dataType dtype, int party)
/// <param name="message">Message to display for server</param>
public static void BroadcastParty(Data data, int party)
{
foreach(Socket soc in Program.clients.Keys)
foreach (Socket soc in Program.clients.Keys)
{
if (Program.clients[soc].partyID == party)
{
Send(soc, data, dtype);
Send(soc, data);
}
}
if (dtype == Common.dataType.message) { if (Program.selectedParty == party) { ConsoleWrite((string)data); } }
if (Program.selectedParty == party)
{
ConsoleWrite(data.ToSmallString());
}
}
/// <summary>
/// Send or display if server
/// </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="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)
{
ConsoleWrite(message);
ConsoleWrite(data.ToSmallString());
}
else
{
Send(soc, message, Common.dataType.message);
Send(soc, data);
}
}
@ -185,60 +163,39 @@ namespace Galactic_Colors_Control_Server
/// <param name="soc">Target socket</param>
/// <param name="server">Is server?</param>
/// <returns>Can access?</returns>
public static bool AccessParty(ref int partyId, bool needOwn, Socket soc = null, bool server = false)
public static bool AccessParty(ref int partyId, string[] args, bool needOwn, Socket soc = null, bool server = false)
{
if (server)
{
if(Program.selectedParty != -1)
if (Program.selectedParty == -1)
return false;
if (Program.parties.ContainsKey(Program.selectedParty))
{
if (Program.parties.ContainsKey(Program.selectedParty))
{
partyId = Program.selectedParty;
return true;
}
else
{
Logger.Write("Can't find party " + Program.selectedParty, Logger.logType.error);
Program.selectedParty = -1;
return false;
}
partyId = Program.selectedParty;
return true;
}
else
{
ConsoleWrite("Join a party before");
Program.selectedParty = -1;
return false;
}
}
else
{
if(Program.clients[soc].partyID != -1)
{
if (Program.parties.ContainsKey(Program.clients[soc].partyID))
{
if (Program.parties[Program.clients[soc].partyID].IsOwner(GetName(soc)) || !needOwn)
{
partyId = Program.clients[soc].partyID;
return true;
}
else
{
Send(soc, "You are not owner", Common.dataType.message);
return false;
}
}
else
{
Send(soc, "Can't find party " + Program.clients[soc].partyID, Common.dataType.message);
Program.clients[soc].partyID = -1;
return false;
}
}
else
{
Send(soc, "Join a party before", Common.dataType.message);
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

@ -27,6 +27,12 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Common", "Common", "{75A0AD
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
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -35,8 +41,8 @@ Global
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{9E3AF4E1-88C6-4139-A15C-B4F633E80612}.Debug|Any CPU.ActiveCfg = Release|Any CPU
{9E3AF4E1-88C6-4139-A15C-B4F633E80612}.Debug|Any CPU.Build.0 = 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 = 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}.Release|Any CPU.ActiveCfg = Release|Any CPU

View File

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

View File

@ -1,13 +1,10 @@
using Galactic_Colors_Control_Common;
using Galactic_Colors_Control_Common.Protocol;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
namespace Galactic_Colors_Control
@ -25,6 +22,7 @@ namespace Galactic_Colors_Control
public bool isRunning { get { return _run; } }
public List<string> Output = new List<string>();
private int RequestId = 0;
private Thread RecieveThread;
@ -66,14 +64,14 @@ namespace Galactic_Colors_Control
}
catch (Exception e)
{
Output.Add(e.Message);
PORT = 0;
Output.Add(e.Message);
return null;
}
}
else
{
Output.Add("Incorrect port");
Output.Add("Incorrect Port");
return null;
}
}
@ -129,9 +127,9 @@ namespace Galactic_Colors_Control
/// </summary>
public void ExitHost()
{
Send("/exit", Common.dataType.message); // Tell the server we are exiting
Send(new RequestData(GetRequestId(), new string[1] { "exit" }));// Tell the server we are exiting
_run = false;
RecieveThread.Join();
RecieveThread.Join(2000);
ClientSocket.Shutdown(SocketShutdown.Both);
ClientSocket.Close();
Output.Add("Bye");
@ -155,7 +153,27 @@ namespace Galactic_Colors_Control
break;
default:
Send(request, Common.dataType.message);
//TODO add key and send error here
if (request.Length > 0)
{
if (request[0] == '/')
{
request = request.Substring(1);
string[] array = request.Split(new char[1] { ' ' }, 4, StringSplitOptions.RemoveEmptyEntries);
if (array.Length > 0)
{
Send(new RequestData(GetRequestId(), array));
}
else
{
Output.Add("Any Command");
}
}
else
{
Send(new RequestData(GetRequestId(), new string[2] { "say", request }));
}
}
break;
}
}
@ -177,32 +195,11 @@ namespace Galactic_Colors_Control
}
}
private void Send(object data, Common.dataType dtype)
private void Send(Data packet)
{
byte[] type = new byte[4];
type = BitConverter.GetBytes((int)dtype);
byte[] bytes = null;
switch (dtype)
{
case Common.dataType.message:
bytes = Encoding.ASCII.GetBytes((string)data);
break;
case Common.dataType.data:
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
bf.Serialize(ms, data);
bytes = ms.ToArray();
}
break;
}
byte[] final = new byte[type.Length + bytes.Length];
type.CopyTo(final, 0);
bytes.CopyTo(final, type.Length);
try
{
ClientSocket.Send(final);
ClientSocket.Send(packet.ToBytes());
}
catch
{
@ -234,79 +231,40 @@ namespace Galactic_Colors_Control
_errorCount = 0;
var data = new byte[received];
Array.Copy(buffer, data, received);
byte[] type = new byte[4];
type = data.Take(4).ToArray();
type.Reverse();
Common.dataType dtype = (Common.dataType)BitConverter.ToInt32(type, 0);
byte[] bytes = null;
bytes = data.Skip(4).ToArray();
switch (dtype)
Data packet = Data.FromBytes(ref data);
if (packet != null)
{
case Common.dataType.message:
string text = Encoding.ASCII.GetString(bytes);
if (text[0] == '/')
{
text = text.Substring(1);
text = text.ToLower();
string[] array = text.Split(new char[1] { ' ' }, 4, StringSplitOptions.RemoveEmptyEntries);
switch (array[0])
{
case "connected":
Output.Add("Identifiaction succes");
break;
switch (packet.GetType().Name)
{
case "EventData":
EventData eve = (EventData)packet;
Output.Add(eve.ToSmallString());
break;
case "allreadytaken":
Output.Add("Username Allready Taken");
break;
case "ResultData":
ResultData res = (ResultData)packet;
Output.Add(res.ToSmallString());
break;
case "kick":
if (array.Length > 1)
{
Output.Add("Kick : " + array[1]);
}
else
{
Output.Add("Kick by server");
}
_run = false;
break;
case "party":
if (array[1] == "kick")
{
if (array.Length > 2)
{
Output.Add("Kick from party : " + array[2]);
}
else
{
Output.Add("Kick from party");
}
}
else
{
Output.Add("Unknown action from server");
}
break;
default:
Output.Add("Unknown action from server");
break;
}
}
else
{
Output.Add(text);
}
break;
case Common.dataType.data:
Console.WriteLine("data");
break;
default:
Output.Add("Wrong packet");
break;
}
}
else
{
Output.Add("Wrong packet");
}
Thread.Sleep(200);
}
Output.Add("/*exit*/");
}
public int GetRequestId(bool indent = true)
{
if (indent) { RequestId++; }
return RequestId;
}
}
}

View File

@ -1,8 +1,7 @@
using System.Reflection;
using System.Runtime.CompilerServices;
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
// associées à un assembly.
[assembly: AssemblyTitle("Galactic Colors Control")]
@ -12,8 +11,8 @@ using System.Runtime.InteropServices;
[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
// 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)]

View File

@ -21,7 +21,7 @@ sudo apt-get install libopenal-dev mono-runtime
* Galactic_Colors_Control_Console.exe => Client without GUI
* 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
```