I have the following code in my server side:
// Bind to a specific local port number (SERVER_PORT) and any local IP address.
m_tlServer = new TcpListener(IPAddress.Any, SERVER_PORT);
// Start listening for connection attempts.
m_tlServer.Start();
// Start accepting new clients.
// Sleep until a new client(s) will try to connect to the server.
while (!m_bStopThread)
{
if (!m_tlServer.Pending())
{
// Sleep and try again.
Thread.Sleep(LISTENING_SLEEP_TIME);
continue;
}
else
{
// Accept a new client in a new thread.
Thread newthread = new Thread(new ThreadStart(HandleNewConnection));
newthread.Start();
}
}
My problem is that when a client tries to connect to the server, the method Pending returns true several times (usually 4 times) and several thread are created.
I tried to replace that while loop by a loop that uses the AcceptTcpClient method (without knowing if there are any connection attempts) and it’s works fine. So, I think the problem is caused by Pending method.
Can anyone help me? Thanks, Ofer.
Use
AcceptTcpClientnotPendingand it will work.Why what you’re doing is producing theses steps :
In a nutshell that’s not because you start a thread that some random instruction inside is executed immediately. The point of the thread is exactly that : It will execute later.
If you want to have a way to stop the listening process use
WaitHandles:Your method that want to stop the thread will just need to
stopEvent.Set()