Code cleanup

This commit is contained in:
szporowolik
2019-10-20 14:26:38 +02:00
parent ceec3a7616
commit 732f8b5fce

View File

@@ -5,49 +5,49 @@ using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using System.Windows.Forms;
public class TCPController public class TCPController
{ {
// Main class for TCP listener // Main class for TCP listener
public int intListenPort; // Port to connect to public int intListenPort; // Port to connect to
public bool bDone; // Helper to exit main loop without killing thread public bool bCloseConnection; // Helper to exit main loop without killing thread
public string[] arrLogHistory; // Log history for GUI public string[] arrGUILogHistory; // Log history for GUI
public string[] arrSendBuffer; // Mysql send buffer public string[] arrMySQLSendBuffer; // MySQL send buffer
public Thread thrTCPListener; // Seperate thread for TCP public Thread thrTCPListener; // Seperate thread for TCP
public bool bStatus; // TCP connecion status
public void Create(int par_intListenPort, ref string[] par_arrLogHistory, ref string[] par_arrSendBuffer) public void Create(int par_intListenPort, ref string[] par_arrLogHistory, ref string[] par_arrSendBuffer)
{ {
// Create class // Create class and map creation arguments to class
intListenPort = par_intListenPort; intListenPort = par_intListenPort;
arrLogHistory = par_arrLogHistory; arrGUILogHistory = par_arrLogHistory;
arrSendBuffer = par_arrSendBuffer; arrMySQLSendBuffer = par_arrSendBuffer;
bDone = false; bCloseConnection = false;
bStatus = false;
} }
public void StopListen() public void StopListen()
{ {
// Finish listening // Stop listening
bDone = true; bCloseConnection = true;
bStatus = false;
for (int i = 0; i < arrSendBuffer.Length - 1; i++) // Clear send buffer
for (int i = 0; i < arrMySQLSendBuffer.Length - 1; i++)
{ {
arrSendBuffer[i] = null; arrMySQLSendBuffer[i] = null;
} }
} }
public void StartListen() public void StartListen()
{ {
NetworkStream ns=null; // Start listening
NetworkStream nsReadStream=null;
TcpClient tcpClient=null; TcpClient tcpClient=null;
bool bTCPConnectionOnline = false; bool bTCPConnectionOnline = false;
while (!bDone)
// Main loop - do until diconnect button is clicked
while (!bCloseConnection)
{ {
Console.WriteLine("TCP Listen start"); Console.WriteLine("TCP Listen start");
TcpListener tcpServer = new TcpListener(IPAddress.Any, intListenPort); ; // Listener object TcpListener tcpServer = new TcpListener(IPAddress.Any, intListenPort); ; // Create listener object
try try
{ {
@@ -56,29 +56,31 @@ public class TCPController
// Start the main loop // Start the main loop
tcpServer.Start(); tcpServer.Start();
bStatus = true;
while (!bDone) // While user do not clicked Disconnect button
while (!bCloseConnection)
{ {
// Start listening // Start listening
Console.WriteLine("TCP: Waiting for connection"); Console.WriteLine("TCP: Waiting for connection");
Globals.bClientConnected = false; Globals.bClientConnected = false;
// Wait for pending connection // Wait for pending connection
if (tcpServer.Pending()) if (tcpServer.Pending())
{ {
Console.WriteLine("TCP: Connected"); Console.WriteLine("TCP: Connected");
bTCPConnectionOnline = true; bTCPConnectionOnline = true;
tcpClient = tcpServer.AcceptTcpClient(); //if a connection exists, the server will accept it tcpClient = tcpServer.AcceptTcpClient(); //if a connection exists, the server will accept it
ns = tcpClient.GetStream(); //networkstream is used to send/receive messages nsReadStream = tcpClient.GetStream(); //networkstream is used to send/receive messages
ns.ReadTimeout = 6000; nsReadStream.ReadTimeout = 6000;
tcpClient.ReceiveTimeout = 6000; tcpClient.ReceiveTimeout = 6000;
while (tcpClient.Connected && !bDone && bTCPConnectionOnline) //while the client is connected, we look for incoming messages while (tcpClient.Connected && !bCloseConnection && bTCPConnectionOnline) //while the client is connected, we look for incoming messages
{ {
StringBuilder CompleteMessage = new StringBuilder(); StringBuilder CompleteMessage = new StringBuilder();
Globals.bClientConnected = true; Globals.bClientConnected = true;
if (ns.CanRead) if (nsReadStream.CanRead)
{ {
Console.WriteLine("TCP: Can read"); Console.WriteLine("TCP: Can read");
byte[] ReadBuffer = new byte[1024]; byte[] ReadBuffer = new byte[1024];
@@ -89,14 +91,14 @@ public class TCPController
do do
{ {
Console.WriteLine("TCP: Read"); Console.WriteLine("TCP: Read");
numberOfBytesRead = ns.Read(ReadBuffer, 0, ReadBuffer.Length); numberOfBytesRead = nsReadStream.Read(ReadBuffer, 0, ReadBuffer.Length);
CompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(ReadBuffer, 0, numberOfBytesRead)); CompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(ReadBuffer, 0, numberOfBytesRead));
if (numberOfBytesRead == 0) if (numberOfBytesRead == 0)
{ {
break; break;
} }
} }
while (ns.DataAvailable && ns.CanRead && tcpClient.Connected); while (nsReadStream.DataAvailable && nsReadStream.CanRead && tcpClient.Connected);
} }
strReceivedData = CompleteMessage.ToString(); strReceivedData = CompleteMessage.ToString();
Console.WriteLine("Sender: {0} Payload: {1}", null, strReceivedData); Console.WriteLine("Sender: {0} Payload: {1}", null, strReceivedData);
@@ -108,16 +110,16 @@ public class TCPController
dynamic dynamicRawTCPFrame = JsonConvert.DeserializeObject(strReceivedData); // Deserialize received frame dynamic dynamicRawTCPFrame = JsonConvert.DeserializeObject(strReceivedData); // Deserialize received frame
string strRawTCPFrameType = dynamicRawTCPFrame.type; string strRawTCPFrameType = dynamicRawTCPFrame.type;
PerunHelper.LogHistoryAdd(ref arrLogHistory, "#" + Globals.intInstanceId + "> TCP packet received, type: " + strRawTCPFrameType); PerunHelper.LogHistoryAdd(ref arrGUILogHistory, "#" + Globals.intInstanceId + "> TCP packet received, type: " + strRawTCPFrameType);
// Add to mySQL send buffer (find first empty slot) // Add to mySQL send buffer (find first empty slot)
if (Int32.Parse(strRawTCPFrameType) != 0) if (Int32.Parse(strRawTCPFrameType) != 0)
{ {
for (int i = 0; i < arrSendBuffer.Length - 1; i++) for (int i = 0; i < arrMySQLSendBuffer.Length - 1; i++)
{ {
if (arrSendBuffer[i] == null) if (arrMySQLSendBuffer[i] == null)
{ {
arrSendBuffer[i] = strReceivedData; arrMySQLSendBuffer[i] = strReceivedData;
break; break;
} }
} }
@@ -131,7 +133,7 @@ public class TCPController
{ {
Globals.intGameErros++; Globals.intGameErros++;
Console.WriteLine(e.ToString()); Console.WriteLine(e.ToString());
PerunHelper.LogHistoryAdd(ref arrLogHistory, "#" + Globals.intInstanceId + " > TCP ERROR incorrect JSON > " + e.Message); PerunHelper.LogHistoryAdd(ref arrGUILogHistory, "#" + Globals.intInstanceId + " > TCP ERROR incorrect JSON > " + e.Message);
bTCPConnectionOnline = false; bTCPConnectionOnline = false;
} }
} }
@@ -139,25 +141,20 @@ public class TCPController
System.Threading.Thread.Sleep(500); System.Threading.Thread.Sleep(500);
} }
tcpServer.Stop(); tcpServer.Stop();
bStatus = false;
} }
catch (Exception e) catch (Exception e)
{ {
// General exception found Globals.intGameErros++;
//if (e.HResult != -2147467259) Console.WriteLine(e.ToString());
//{ PerunHelper.LogHistoryAdd(ref arrGUILogHistory, "#" + Globals.intInstanceId + " > TCP error - connection closed or port in use > " + e.Message);
Globals.intGameErros++; bTCPConnectionOnline = false;
Console.WriteLine(e.ToString());
PerunHelper.LogHistoryAdd(ref arrLogHistory, "#" + Globals.intInstanceId + " > TCP error - connection closed or port in use > " + e.Message);
bTCPConnectionOnline = false;
//}
} }
if (!(ns is null)) // Clean up and prepare for next connection
if (!(nsReadStream is null))
{ {
ns.Flush(); nsReadStream.Flush();
ns.Close(); nsReadStream.Close();
} }
if (!(tcpClient is null)) if (!(tcpClient is null))
{ {
@@ -167,7 +164,6 @@ public class TCPController
{ {
tcpServer.Stop(); tcpServer.Stop();
} }
bStatus = false;
Console.WriteLine("TCP listen stop"); Console.WriteLine("TCP listen stop");
} }
} }