I'm developing a c# program just to get some knowledge about TcpClient. So, this program receives a message from another and sends back a OK packet to it, confirming the established connection.
On the first request, it works pretty well, sending back the OK packet without any issues. But on second request, it simply does not reply. Looks like it never received the packet from the client. I can see using a packet sniffer that the packet is being sent from client, but my server has no action.
It's actually printing all requests on console, so I can see if something "went" to the readstream or not. If I close the server or the client, and reopen to stablish a new connection, I receive again the first packet, but not the second.
I've been searching for a solution, at least a week. Many functions simply did not worked for me and I don't want the application to disconnect and reconnect a lot of times.
My server code:
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());
}
}
}
}
The reason why you don't receive the second packet is this line:
clientSocket = serverSocket.AcceptTcpClient();
This call waits for a new client to connect to your server's listener socket.
Move this line outside your outer loop to accept only one client and use only that single clientSocket
in your loops.
(I'd like to add details but am on the road and it's hard to type all that on a phone...)