1

I am experimenting with client-server applications using the System.Net namespace in C#. I am currently using the following TcpListener code to listen for incoming connections:

TcpListener listener = new TcpListener(IPAddress.Any, 62126);
List<Connection> ClientConnections = new List<Connection>();
while (true)
{
    listener.Start();
    while (true)
    {
        if (listener.Pending())
        {
            ClientConnections.Add(new Connection(listener.AcceptTcpClient()));
            break;
        }
    }
}

(Where Connection is a class that takes the accepted TcpClient via public Connection(TcpClient client) { ... } and maintains the connection on a separate thread.)

Do I need to invoke listener.Start() every time an incoming connection is accepted or is that unnecessary?

StackUnderflow
  • 431
  • 1
  • 3
  • 15
  • 2
    Take a look at using [BeginAcceptTcpClient](http://msdn.microsoft.com/en-us/library/vstudio/system.net.sockets.tcplistener.beginaccepttcpclient%28v=vs.110%29.aspx). It is a good idea to avoid while(true) loops. – bytedreamer May 10 '14 at 13:58

2 Answers2

0

You're busy waiting if no pending connection requests exist. This is not necessary. Just delete that if. Make sure you understand why it is not necessary.

I do not understand why there are two nested loops. You only need one. Call Start only once.

I can tell that you have not read the documentation. Quite dangerous. You are capable of answering these questions yourself.

usr
  • 168,620
  • 35
  • 240
  • 369
0

No. Start needs to be called only once. Remove the outer while loop

Krzysztof Wende
  • 3,208
  • 25
  • 38