diff --git a/Galactic Colors Control Common/Binary.cs b/Galactic Colors Control Common/Binary.cs
index 0de67f7..9d9b905 100644
--- a/Galactic Colors Control Common/Binary.cs
+++ b/Galactic Colors Control Common/Binary.cs
@@ -4,6 +4,9 @@ using System.Text;
namespace Galactic_Colors_Control_Common
{
+ ///
+ /// All used types - byte[] convertions
+ ///
public static class Binary
{
public static bool ToBool(ref byte[] bytes)
@@ -14,6 +17,7 @@ namespace Galactic_Colors_Control_Common
return data[1] == 1 ? true : false;
}
+ ///1 byte
public static byte[] FromBool(bool x)
{
return x ? new byte[1] { 1 } : new byte[1] { 0 };
@@ -27,6 +31,7 @@ namespace Galactic_Colors_Control_Common
return text;
}
+ ///len(in bytes) + string
public static byte[] FromString(string text)
{
byte[] data = Encoding.ASCII.GetBytes(text);
@@ -48,6 +53,7 @@ namespace Galactic_Colors_Control_Common
return BitConverter.ToInt32(data, 0);
}
+ ///4 bytes
public static byte[] FromInt(int x)
{
byte[] data = new byte[4];
diff --git a/Galactic Colors Control Common/Common.cs b/Galactic Colors Control Common/Common.cs
index 8c63ca2..8bf281f 100644
--- a/Galactic Colors Control Common/Common.cs
+++ b/Galactic Colors Control Common/Common.cs
@@ -5,6 +5,35 @@ namespace Galactic_Colors_Control_Common
{
public static class Common
{
+ ///
+ /// Write line in console with correct colors
+ ///
+ /// Text to write
+ /// Foreground color
+ /// Background color
+ public static void ConsoleWrite(string v, ConsoleColor Fore = ConsoleColor.White, ConsoleColor Back = ConsoleColor.Black)
+ {
+ Console.Write("\b");
+ Console.ForegroundColor = Fore;
+ Console.BackgroundColor = Back;
+ Console.WriteLine(v);
+ ConsoleResetColor();
+ Console.Write(">");
+ }
+
+ ///
+ /// Reset Console Colors
+ /// For non black background console as Ubuntu
+ ///
+ public static void ConsoleResetColor()
+ {
+ Console.ResetColor();
+ Console.BackgroundColor = ConsoleColor.Black;
+ }
+
+ ///
+ /// Simpler string array creation
+ ///
public static string[] Strings(params string[] args)
{
return args;
@@ -17,7 +46,7 @@ namespace Galactic_Colors_Control_Common
{
foreach (string str in array)
{
- text += (str + Environment.NewLine);
+ text += ((text == "" ? "" : Environment.NewLine) + str);
}
}
return text;
@@ -28,7 +57,7 @@ namespace Galactic_Colors_Control_Common
string text = "";
foreach (int i in array)
{
- text += (i.ToString() + Environment.NewLine);
+ text += ((text == "" ? "" : Environment.NewLine) + i.ToString());
}
return text;
}
diff --git a/Galactic Colors Control Common/Galactic Colors Control Common.csproj b/Galactic Colors Control Common/Galactic Colors Control Common.csproj
index 3455210..293857c 100644
--- a/Galactic Colors Control Common/Galactic Colors Control Common.csproj
+++ b/Galactic Colors Control Common/Galactic Colors Control Common.csproj
@@ -52,6 +52,7 @@
+
diff --git a/Galactic Colors Control Common/Protocol/Data.cs b/Galactic Colors Control Common/Protocol/Data.cs
index 6d91be8..951f671 100644
--- a/Galactic Colors Control Common/Protocol/Data.cs
+++ b/Galactic Colors Control Common/Protocol/Data.cs
@@ -1,9 +1,16 @@
namespace Galactic_Colors_Control_Common.Protocol
{
+ ///
+ /// Packet Master Class
+ ///
public class Data
{
public enum DataType { Request, Result, Event };
-
+
+ ///
+ /// Create Packet from bytes
+ ///
+ /// row bytes (remove used bytes)
public static Data FromBytes(ref byte[] bytes)
{
switch ((DataType)Binary.ToInt(ref bytes))
@@ -22,16 +29,25 @@
}
}
+ ///
+ /// Small readable text
+ ///
public virtual string ToSmallString()
{
return null;
}
+ ///
+ /// Long readble text
+ ///
public virtual string ToLongString()
{
return null;
}
+ ///
+ /// Generate bytes to send
+ ///
public virtual byte[] ToBytes()
{
return new byte[0];
diff --git a/Galactic Colors Control Common/Protocol/EventData.cs b/Galactic Colors Control Common/Protocol/EventData.cs
index 57c6175..7918063 100644
--- a/Galactic Colors Control Common/Protocol/EventData.cs
+++ b/Galactic Colors Control Common/Protocol/EventData.cs
@@ -1,16 +1,28 @@
namespace Galactic_Colors_Control_Common.Protocol
{
- public enum EventTypes { ChatMessage, ServerJoin, ServerLeave, ServerKick, PartyJoin, PartyLeave, PartyKick }
+ public enum EventTypes
+ {
+ ChatMessage, //To displat in chatbox
+ ServerJoin, //A player join server
+ ServerLeave, //A player leave server
+ ServerKick, //You are kick from server
+ PartyJoin, //A player join your party
+ PartyLeave, //A player leave your party
+ PartyKick //Tou are jick from your party
+ }
+ ///
+ /// Server to Client Packet
+ ///
public class EventData : Data
{
public EventTypes type;
- public string[] data;
+ public string[] data; //EventArgs like
- public EventData(EventTypes p1, string[] p2 = null)
+ public EventData(EventTypes Type, string[] Data = null)
{
- type = p1;
- data = p2;
+ type = Type;
+ data = Data;
}
public EventData(ref byte[] bytes)
diff --git a/Galactic Colors Control Common/Protocol/EventDataArgs.cs b/Galactic Colors Control Common/Protocol/EventDataArgs.cs
new file mode 100644
index 0000000..e17413b
--- /dev/null
+++ b/Galactic Colors Control Common/Protocol/EventDataArgs.cs
@@ -0,0 +1,23 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Galactic_Colors_Control_Common.Protocol
+{
+ ///
+ /// Hide EventData in EventArgs
+ /// for OnEvent Handler
+ ///
+ public class EventDataArgs : EventArgs
+ {
+ private EventData m_Data;
+ public EventDataArgs(EventData _myData)
+ {
+ m_Data = _myData;
+ }
+
+ public EventData Data { get { return m_Data; } }
+ }
+}
diff --git a/Galactic Colors Control Common/Protocol/RequestData.cs b/Galactic Colors Control Common/Protocol/RequestData.cs
index 6ceb701..d686c05 100644
--- a/Galactic Colors Control Common/Protocol/RequestData.cs
+++ b/Galactic Colors Control Common/Protocol/RequestData.cs
@@ -1,14 +1,17 @@
namespace Galactic_Colors_Control_Common.Protocol
{
+ ///
+ /// Client to Server Data request packet 'allways' return ResultData
+ ///
public class RequestData : Data
{
- public int id;
+ public int id; //Client Size autoindent id
public string[] args;
- public RequestData(int p1, string[] p2)
+ public RequestData(int Id, string[] Args)
{
- id = p1;
- args = p2;
+ id = Id;
+ args = Args;
}
public RequestData(ref byte[] bytes)
diff --git a/Galactic Colors Control Common/Protocol/RequestResult.cs b/Galactic Colors Control Common/Protocol/RequestResult.cs
index 9a97914..ac90e00 100644
--- a/Galactic Colors Control Common/Protocol/RequestResult.cs
+++ b/Galactic Colors Control Common/Protocol/RequestResult.cs
@@ -1,5 +1,9 @@
namespace Galactic_Colors_Control_Common.Protocol
{
+ ///
+ /// Part of RequestData
+ /// Commands return
+ ///
public class RequestResult
{
public ResultTypes type;
diff --git a/Galactic Colors Control Common/Protocol/ResultData.cs b/Galactic Colors Control Common/Protocol/ResultData.cs
index 58c9f4e..137891e 100644
--- a/Galactic Colors Control Common/Protocol/ResultData.cs
+++ b/Galactic Colors Control Common/Protocol/ResultData.cs
@@ -2,24 +2,27 @@
{
public enum ResultTypes { Error, OK }
+ ///
+ /// Server to Client Result from RequestData
+ ///
public class ResultData : Data
{
- public int id;
+ public int id; //Client Side Autoindent
public ResultTypes type;
public string[] result;
- public ResultData(int p1, ResultTypes p2, string[] p3 = null)
+ public ResultData(int Id, ResultTypes Type, string[] Result = null)
{
- id = p1;
- type = p2;
- result = p3;
+ id = Id;
+ type = Type;
+ result = Result;
}
- public ResultData(int p1, RequestResult p2)
+ public ResultData(int Id, RequestResult Result)
{
- id = p1;
- type = p2.type;
- result = p2.result;
+ id = Id;
+ type = Result.type;
+ result = Result.result;
}
public ResultData(ref byte[] bytes)
diff --git a/Galactic Colors Control Console/Galactic Colors Control Console.csproj b/Galactic Colors Control Console/Galactic Colors Control Console.csproj
index 7f677b3..50b8893 100644
--- a/Galactic Colors Control Console/Galactic Colors Control Console.csproj
+++ b/Galactic Colors Control Console/Galactic Colors Control Console.csproj
@@ -51,6 +51,10 @@
+
+ {022A69CE-22B5-4934-BE9F-A9C6DF9557ED}
+ Galactic Colors Control Common
+
{93582ce8-c8c8-4e19-908b-d671ecbade25}
Galactic Colors Control
diff --git a/Galactic Colors Control Console/Program.cs b/Galactic Colors Control Console/Program.cs
index fd0dce0..9b1a550 100644
--- a/Galactic Colors Control Console/Program.cs
+++ b/Galactic Colors Control Console/Program.cs
@@ -1,40 +1,43 @@
using Galactic_Colors_Control;
+using Galactic_Colors_Control_Common;
+using Galactic_Colors_Control_Common.Protocol;
using System;
using System.Reflection;
using System.Threading;
namespace Galactic_Colors_Control_Console
{
+ ///
+ /// Console Client
+ ///
internal class Program
{
private static Client client;
private static bool run = true;
- private static Thread Writer;
+ private static char commandChar = '/';
private static void Main()
{
client = new Client();
- Console.Title = "Galactic Colors Control Client";
+ client.OnEvent += new EventHandler(OnEvent); //Set OnEvent function
+ Console.Title = "Galactic Colors Control Client"; //Start display
Console.Write(">");
- Write("Galactic Colors Control Client");
- Write("Console " + Assembly.GetEntryAssembly().GetName().Version.ToString());
+ Common.ConsoleWrite("Galactic Colors Control Client", ConsoleColor.Red);
+ Common.ConsoleWrite("Console " + Assembly.GetEntryAssembly().GetName().Version.ToString(), ConsoleColor.DarkYellow);
bool hostSet = false;
- while (!hostSet)
+ while (!hostSet) //Request hostname
{
- Write("Enter server host:");
+ Common.ConsoleWrite("Enter server host:");
string host = client.ValidateHost(Console.ReadLine());
- if (host == null)
+ if (host[0] == '*')
{
- foreach (string output in client.Output.ToArray())
- {
- Write(output);
- }
- client.Output.Clear();
+ host = host.Substring(1);
+ Common.ConsoleWrite(host, ConsoleColor.Red);
client.ResetHost();
}
else
{
- Write("Use " + host + "? y/n");
+ Common.ConsoleWrite("Use " + host + "? y/n");
ConsoleKeyInfo c = new ConsoleKeyInfo();
while (c.Key != ConsoleKey.Y && c.Key != ConsoleKey.N)
{
@@ -50,58 +53,48 @@ namespace Galactic_Colors_Control_Console
}
}
}
- if (client.ConnectHost())
+ if (client.ConnectHost()) //Try connection
{
run = true;
- Writer = new Thread(OutputWriter);
- Writer.Start();
while (run)
{
- client.SendRequest(Console.ReadLine());
+ Execute(Console.ReadLine()); //Process console input
if (!client.isRunning) { run = false; }
}
- Writer.Join();
Console.Read();
}
else
{
- foreach (string output in client.Output.ToArray())
- {
- Write(output);
- }
- client.Output.Clear();
+ Common.ConsoleWrite("Can't connect sorry. Bye", ConsoleColor.Red);
Console.Read();
}
}
- private static void OutputWriter()
+ private static void Execute(string input)
{
- while (run || client.Output.Count > 0)
- {
- if (client.Output.Count > 0)
- {
- string text = client.Output[0];
- switch (text)
- {
- case "/clear":
- Console.Clear();
- break;
+ if (input == null)
+ return;
- default:
- Write(text);
- break;
- }
- client.Output.Remove(text);
- }
- Thread.Sleep(200);
+ if (input.Length == 0)
+ return;
+
+ string[] req;
+ if(input[0] == commandChar)
+ {
+ input = input.Substring(1);
+ req = Common.SplitArgs(input);
}
+ else
+ {
+ req = Common.Strings("say", input);
+ }
+ Common.ConsoleWrite(client.Request(req).ToSmallString()); //Add processing (common)
}
- private static void Write(string text)
+ private static void OnEvent(object sender, EventArgs e)
{
- Console.Write("\b");
- Console.WriteLine(text);
- Console.Write(">");
+ EventData eve = ((EventDataArgs)e).Data;
+ Common.ConsoleWrite(eve.ToSmallString()); //TODO add processing (common)
}
}
}
\ No newline at end of file
diff --git a/Galactic Colors Control GUI/Game1.cs b/Galactic Colors Control GUI/Game1.cs
index 9b900a4..57e86c2 100644
--- a/Galactic Colors Control GUI/Game1.cs
+++ b/Galactic Colors Control GUI/Game1.cs
@@ -1,4 +1,5 @@
-using Galactic_Colors_Control;
+//TODO comment and update for new clientcore
+using Galactic_Colors_Control;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
@@ -211,7 +212,8 @@ namespace Galactic_Colors_Control_GUI
case GameStatus.Game:
if (showOutput)
- if (client.Output.Count > 0)
+ //TODO
+ /*if (client.Output.Count > 0)
{
string text = client.Output[0];
switch (text)
@@ -225,7 +227,7 @@ namespace Galactic_Colors_Control_GUI
break;
}
client.Output.Remove(text);
- }
+ }*/
if (!client.isRunning) { gameStatus = GameStatus.Kick; }
break;
}
@@ -327,7 +329,7 @@ namespace Galactic_Colors_Control_GUI
}
if (GUI.Button(new Rectangle(ScreenWidth / 2 + 5, ScreenHeight / 4 + 100, 135, 40), buttonsSprites[0], "No", basicFont))
{
- client.Output.Clear();
+ //TODO client.Output.Clear();
client.ResetHost();
GUI.ResetFocus();
showYNMessage = false;
@@ -406,7 +408,7 @@ namespace Galactic_Colors_Control_GUI
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; } }
+ //TODO 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);
}
@@ -446,9 +448,9 @@ namespace Galactic_Colors_Control_GUI
{
messageTitle = "Error";
messageText = string.Empty;
- foreach (string line in client.Output.ToArray()) { messageText += (line + Environment.NewLine); }
+ //TODO foreach (string line in client.Output.ToArray()) { messageText += (line + Environment.NewLine); }
showOKMessage = true;
- client.Output.Clear();
+ //TODO client.Output.Clear();
client.ResetHost(); ;
}
else
@@ -470,9 +472,9 @@ namespace Galactic_Colors_Control_GUI
{
messageTitle = "Error";
messageText = string.Empty;
- foreach (string line in client.Output.ToArray()) { messageText += (line + Environment.NewLine); }
+ //TODO foreach (string line in client.Output.ToArray()) { messageText += (line + Environment.NewLine); }
showOKMessage = true;
- client.Output.Clear();
+ //TODO client.Output.Clear();
client.ResetHost();
}
showLoading = false;
@@ -485,9 +487,9 @@ namespace Galactic_Colors_Control_GUI
{
if (username.Length > 3)
{
- client.Output.Clear();
- client.SendRequest("/connect " + username);
- int wait = 0;
+ //TODO client.Output.Clear();
+ //TODO client.SendRequest("/connect " + username);
+ /*int wait = 0;
while (wait < 20)
{
if (client.Output.Count > 0)
@@ -523,7 +525,7 @@ namespace Galactic_Colors_Control_GUI
showOKMessage = true;
showLoading = false;
client.Output.Clear();
- }
+ }*/
}
}
showLoading = false;
@@ -533,6 +535,8 @@ namespace Galactic_Colors_Control_GUI
{
showLoading = true;
GUI.ResetFocus();
+ //TODO
+ /*
if (showParty)
{
client.SendRequest("/party leave");
@@ -584,7 +588,7 @@ namespace Galactic_Colors_Control_GUI
showLoading = false;
client.Output.Clear();
}
- }
+ }*/
}
private void ChatAdd(string text)
diff --git a/Galactic Colors Control Server/Logger.cs b/Galactic Colors Control Server/Logger.cs
index 3c84d79..176ceee 100644
--- a/Galactic Colors Control Server/Logger.cs
+++ b/Galactic Colors Control Server/Logger.cs
@@ -1,4 +1,5 @@
-using System;
+using Galactic_Colors_Control_Common;
+using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
@@ -125,7 +126,7 @@ namespace Galactic_Colors_Control_Server
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();
+ Common.ConsoleResetColor();
Console.Write(">");
}
}
diff --git a/Galactic Colors Control Server/Program.cs b/Galactic Colors Control Server/Program.cs
index b8d26dc..729be6b 100644
--- a/Galactic Colors Control Server/Program.cs
+++ b/Galactic Colors Control Server/Program.cs
@@ -54,7 +54,7 @@ namespace Galactic_Colors_Control_Server
break;
default:
- Utilities.ConsoleWrite("Use --debug or --dev");
+ Common.ConsoleWrite("Use --debug or --dev");
break;
}
}
@@ -92,7 +92,7 @@ namespace Galactic_Colors_Control_Server
string ConsoleInput = Console.ReadLine();
Console.Write(">");
string[] args = Common.SplitArgs(ConsoleInput);
- Utilities.ConsoleWrite(new ResultData(-1, Commands.Manager.Execute(args, null, true)).ToSmallString());
+ Common.ConsoleWrite(new ResultData(-1, Commands.Manager.Execute(args, null, true)).ToSmallString());
ConsoleInput = null;
}
}
diff --git a/Galactic Colors Control Server/Utilities.cs b/Galactic Colors Control Server/Utilities.cs
index 78d4bae..cfe562c 100644
--- a/Galactic Colors Control Server/Utilities.cs
+++ b/Galactic Colors Control Server/Utilities.cs
@@ -1,4 +1,5 @@
-using Galactic_Colors_Control_Common.Protocol;
+using Galactic_Colors_Control_Common;
+using Galactic_Colors_Control_Common.Protocol;
using System;
using System.Net;
using System.Net.Sockets;
@@ -49,32 +50,6 @@ namespace Galactic_Colors_Control_Server
return Program.clients[soc].partyID;
}
- ///
- /// Write line in console with correct colors
- ///
- /// Text to write
- /// Foreground color
- /// Background color
- public static void ConsoleWrite(string v, ConsoleColor Fore = ConsoleColor.White, ConsoleColor Back = ConsoleColor.Black)
- {
- Console.Write("\b");
- Console.ForegroundColor = Fore;
- Console.BackgroundColor = Back;
- Console.WriteLine(v);
- ConsoleResetColor();
- Console.Write(">");
- }
-
- ///
- /// Reset Console Colors
- /// For non black background console as Ubuntu
- ///
- public static void ConsoleResetColor()
- {
- Console.ResetColor();
- Console.BackgroundColor = ConsoleColor.Black;
- }
-
///
/// Send data to specified socket
///
@@ -111,7 +86,7 @@ namespace Galactic_Colors_Control_Server
{
Send(soc, packet);
}
- ConsoleWrite(packet.ToSmallString());
+ Common.ConsoleWrite(packet.ToSmallString());
}
///
@@ -132,7 +107,7 @@ namespace Galactic_Colors_Control_Server
}
if (Program.selectedParty == party)
{
- ConsoleWrite(data.ToSmallString());
+ Common.ConsoleWrite(data.ToSmallString());
}
}
@@ -147,7 +122,7 @@ namespace Galactic_Colors_Control_Server
{
if (server)
{
- ConsoleWrite(data.ToSmallString());
+ Common.ConsoleWrite(data.ToSmallString());
}
else
{
diff --git a/Galactic Colors Control/Program.cs b/Galactic Colors Control/Program.cs
index 52f66b7..099e81a 100644
--- a/Galactic Colors Control/Program.cs
+++ b/Galactic Colors Control/Program.cs
@@ -1,4 +1,5 @@
-using Galactic_Colors_Control_Common.Protocol;
+using Galactic_Colors_Control_Common;
+using Galactic_Colors_Control_Common.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -9,34 +10,62 @@ using System.Threading;
namespace Galactic_Colors_Control
{
+ ///
+ /// Client CrossPlatform Core
+ ///
public class Client
{
private Socket ClientSocket = new Socket
(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- public int PORT = 0;
- private int _errorCount = 0;
- private bool _run = true;
- public string IP = null;
+ public string IP = null; //Server IP
+ public int PORT = 0; //Server Port
+ public struct CoreConfig
+ {
+ public int resultsBuffer; //Max amount of waiting results
+ public int timeout; //Request timeout in ms
+ public int refresh; //Threads sleep in ms
+
+ public CoreConfig(int buffer, int time, int speed)
+ {
+ resultsBuffer = buffer;
+ timeout = time;
+ refresh = speed;
+ }
+ }
+
+ public CoreConfig config = new CoreConfig(20, 2000, 200); //Set default config
+
+ private int _errorCount = 0; //Leave if > 5
+
+ private bool _run = true; //Thread Stop
public bool isRunning { get { return _run; } }
- public List Output = new List();
private int RequestId = 0;
+ private List Results = new List();
+ private Thread RecieveThread; //Main Thread
+ public EventHandler OnEvent; //Execute on EventData reception (must be short or async)
- private Thread RecieveThread;
-
+ ///
+ /// Soft Server Reset
+ ///
public void ResetHost()
{
IP = null;
PORT = 0;
}
+ ///
+ /// Test and Convert Hostname to Address
+ ///
+ /// Hostname
+ /// Address(IP:PORT) or Error(*'text')
public string ValidateHost(string text)
{
- if (text == null) { text = ""; }
- string[] parts = text.Split(new char[] { ':' }, 2, StringSplitOptions.RemoveEmptyEntries);
- if (parts.Length == 0)
+ if (text == null) { text = ""; } //Prevent NullException
+ string[] parts = text.Split(new char[] { ':' }, 2, StringSplitOptions.RemoveEmptyEntries); //Split IP and Port
+ if (parts.Length == 0) //Default config (localhost)
{
parts = new string[] { "" };
PORT = 25001;
@@ -45,7 +74,7 @@ namespace Galactic_Colors_Control
{
if (parts.Length > 1)
{
- if (!int.TryParse(parts[1], out PORT)) { PORT = 0; }
+ if (!int.TryParse(parts[1], out PORT)) { PORT = 0; } //Check Port
if (PORT < 0 || PORT > 65535) { PORT = 0; }
}
else
@@ -57,29 +86,28 @@ namespace Galactic_Colors_Control
{
try
{
- IPHostEntry ipHostEntry = Dns.GetHostEntry(parts[0]);
- IPAddress host = ipHostEntry.AddressList.First(a => a.AddressFamily == AddressFamily.InterNetwork);
+ IPHostEntry ipHostEntry = Dns.GetHostEntry(parts[0]);//Resolve Hostname
+ IPAddress host = ipHostEntry.AddressList.First(a => a.AddressFamily == AddressFamily.InterNetwork);//Get IPv4
IP = host.ToString();
return IP + ":" + PORT;
}
catch (Exception e)
{
PORT = 0;
- Output.Add(e.Message);
- return null;
+ return "*" + e.Message;
}
}
else
{
- Output.Add("Incorrect Port");
- return null;
+ return "*Port Format";
}
}
///
- /// Set IP and PORT before
+ /// Start Server connection
///
- /// Connection succes
+ /// Setup IP and Port before
+ /// connection success
public bool ConnectHost()
{
int attempts = 0;
@@ -89,32 +117,27 @@ namespace Galactic_Colors_Control
try
{
attempts++;
- Output.Add("Connection attempt " + attempts);
ClientSocket.Connect(IP, PORT);
}
- catch (SocketException)
- {
- Output.Clear();
- }
+ catch (SocketException) { }
}
- if (attempts < 5)
+ if (attempts < 5) //Connection success
{
- Output.Clear();
- Output.Add("Connected to " + IP.ToString());
_run = true;
- RecieveThread = new Thread(ReceiveLoop);
+ RecieveThread = new Thread(ReceiveLoop); //Starting Main Thread
RecieveThread.Start();
return true;
}
else
{
- Output.Clear();
- Output.Add("Can't connected to " + IP.ToString());
ResetSocket();
return false;
}
}
+ ///
+ /// Hard Reset (unsafe)
+ ///
private void ResetSocket()
{
ClientSocket.Close();
@@ -128,91 +151,78 @@ namespace Galactic_Colors_Control
public void ExitHost()
{
Send(new RequestData(GetRequestId(), new string[1] { "exit" }));// Tell the server we are exiting
- _run = false;
+ _run = false; //Stopping Thread
RecieveThread.Join(2000);
ClientSocket.Shutdown(SocketShutdown.Both);
ClientSocket.Close();
- Output.Add("Bye");
ResetHost();
}
- public void SendRequest(string request)
+ ///
+ /// Send RequestData to server
+ ///
+ /// Request args
+ /// ResultData or Timeout
+ public ResultData Request(string[] args)
{
- switch (request.ToLower())
+ // TODO filter Client Side Requests
+ RequestData req = new RequestData(GetRequestId(), args);
+ if (!Send(req))
+ return new ResultData(req.id, ResultTypes.Error, Common.Strings("Send Exception"));
+
+ DateTime timeoutDate = DateTime.Now.AddMilliseconds(config.timeout); //Create timeout DataTime
+ while (timeoutDate > DateTime.Now)
{
- case "/exit":
- ExitHost();
- break;
-
- case "/ping":
- PingHost();
- break;
-
- case "/clear":
- Output.Add("/clear");
- break;
-
- default:
- //TODO add key and send error here
- if (request.Length > 0)
+ foreach (ResultData res in Results.ToArray()) //Check all results
+ {
+ if (res.id == req.id)
{
- 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 }));
- }
+ Results.Remove(res);
+ return res;
}
- break;
+ }
+ Thread.Sleep(config.refresh);
}
+ return new ResultData(req.id, ResultTypes.Error, Common.Strings("Timeout"));
}
- private void PingHost()
+ ///
+ /// Ping Current Server IP
+ ///
+ /// Time in ms or 'Timeout'
+ private string PingHost()
{
- Ping p = new Ping();
- PingReply r;
+ Ping ping = new Ping();
+ PingReply reply;
- r = p.Send(IP);
+ reply = ping.Send(IP);
+ if (reply.Status == IPStatus.Success)
+ return reply.RoundtripTime.ToString();
- if (r.Status == IPStatus.Success)
- {
- Output.Add(r.RoundtripTime.ToString() + " ms.");
- }
- else
- {
- Output.Add("Time out");
- }
+ return "Timeout";
}
- private void Send(Data packet)
+ ///
+ /// Send Data object to server
+ ///
+ /// Send success
+ private bool Send(Data packet)
{
try
{
ClientSocket.Send(packet.ToBytes());
+ return true;
}
- catch
+ catch //Can't contact server
{
- Output.Add("Can't contact server : " + _errorCount);
_errorCount++;
}
- if (_errorCount >= 5)
- {
- Output.Add("Kick : too_much_errors");
- _run = false;
- }
+ return false;
}
+ ///
+ /// Main Thread
+ ///
private void ReceiveLoop()
{
while (_run)
@@ -225,40 +235,40 @@ namespace Galactic_Colors_Control
}
catch
{
- Output.Add("Server timeout");
+ _errorCount++;
+ }
+ if (_errorCount >= 5)
+ {
+ _run = false;
}
if (received == 0) return;
_errorCount = 0;
var data = new byte[received];
Array.Copy(buffer, data, received);
- Data packet = Data.FromBytes(ref data);
+ Data packet = Data.FromBytes(ref data); //Create Data object from recieve bytes
if (packet != null)
{
switch (packet.GetType().Name)
{
case "EventData":
EventData eve = (EventData)packet;
- Output.Add(eve.ToSmallString());
+ if (OnEvent != null)
+ OnEvent.Invoke(this, new EventDataArgs(eve));
break;
case "ResultData":
ResultData res = (ResultData)packet;
- Output.Add(res.ToSmallString());
+ ResultAdd(res);
break;
- default:
- Output.Add("Wrong packet");
+ default: //Ignore others Packets
break;
}
}
- else
- {
- Output.Add("Wrong packet");
- }
- Thread.Sleep(200);
+ Thread.Sleep(config.refresh);
}
- Output.Add("/*exit*/");
+ //TODOOutput.Add("/*exit*/");
}
public int GetRequestId(bool indent = true)
@@ -266,5 +276,14 @@ namespace Galactic_Colors_Control
if (indent) { RequestId++; }
return RequestId;
}
+
+ ///
+ /// Add to Results
+ ///
+ public void ResultAdd(ResultData res)
+ {
+ while (Results.Count + 1 > config.resultsBuffer) { Results.RemoveAt(0); } //Removes firsts
+ Results.Add(res);
+ }
}
}
\ No newline at end of file