I'm developing a hobby program to understand how TcpClient
works. Well, I'm doing a program that from time to time gets a package from a secondary program and sends an OK back, confirming that the connection is still established.
On the first request, my program sends OK normally. However, on the second request, it no longer works. It's as if it has not received any package from client , but I can see in this second that the package has been sent.
Below is my server:
static void Main(string[] args)
{
int InternalLoop = 0;
bool Finished = false;
TcpListener serverSocket = new TcpListener(System.Net.IPAddress.Any, 10000);
int requestCount = 0;
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
while (true)
{
bool LoopReceive = true;
bool LoopSend = false;
Console.WriteLine(" :::: SERVER STARTED OK");
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(" :::: CONNECTED TO CLIENT");
requestCount = 0;
NetworkStream networkStream = clientSocket.GetStream();
string Packettosend = "";
while (LoopReceive == true)
{
try
{
//Gets the Client Packet
requestCount = requestCount + 1;
byte[] bytesFrom = new byte[128];
networkStream.Read(bytesFrom, 0, bytesFrom.Length);
string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
Packettosend = "ALIVE";
Console.WriteLine(" ::: SENDING ALIVE PACKET");
LoopReceive = false;
LoopSend = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
while (LoopSend == true || InternalLoop < 2)
{
try
{
InternalLoop += 1;
if (Packettosend == "ALIVE")
{
Byte[] sendBytes1 = { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 };
networkStream.Write(sendBytes1, 0, sendBytes1.Length);
networkStream.Flush();
LoopReceive = true;
LoopSend = false;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
}
If I close the client and server and reopen it, the server again receives the expected package and sends OK again, but only on the first request. / p>
I've looked for something similar before creating this topic, but nothing worked.