A

A

  • NA
  • 1
  • 0

TcpListener stops accepting clients?

Oct 17 2005 3:15 PM

Hi,

I’m having a strange problem with a simple web server using TcpListener.

The problem is that the server sometimes hangs on the line "listener.AcceptTcpClient();" The server could work fine for hours with a couple of connections/second but suddenly it just stops accepting connections. I have to stop the listener and restart the listener from another thread in order to get it to work again.

A bad solution is to stop and start the listener for every connection. This means that incoming connections during the stop/restart sequence is lost, right?

The problem is very sporadic and the server could work for hours and some times just a few minutes. I really need a robust solution that is fail safe.

Please give me some hints on what the problem could be.

Code snippet:

TcpListener listener = new TcpListener(IPAddress.Any, 8080);
TcpClient tcpc;
NetworkStream stream;

int numberOfBytesRead;
String request;

listener.Start();

while(true)
{
  try
  {
    tcpc = listener.AcceptTcpClient(); 
    stream  = tcpc.GetStream();

    do
    {  
      if(stream.CanRead)
      {
        numberOfBytesRead = stream.Read (temp, 0, temp.Length);
        request = String.Concat(request, Encoding.ASCII.GetString(temp, 0, numberOfBytesRead));
      }
    }while(stream.DataAvailable && stream.CanRead);

    stream.Close();
    tcpc.Close();

 
    // do stuff with request


  }catch (Exception e)
  {
    try { stream.Close();} catch{}
    try { tcpc.Close();} catch{}
  }
}