C# TcpListener.AcceptTcpClient generates System.IO.IOException

50 views Asked by At

My TcpListner code is very simple and works flawlessly. But after AcceptTcpClient() the FIRST time I see 'Exception thrown: 'System.IO.IOException' in mscorlib.dll' in the debug/output window. I have been ignoring it since it is not captured by try/catch, has no effect on this server, and never happens after the first pass through the loop. No client has yet requested a connection and when subsequent clients do they are received correctly. Can anyone explain?

listener = new TcpListener(IP, port);
listener.Start();

while (true)
{
    try
    {
        client = listener.AcceptTcpClient();
        // output/debug window shows exception

I played with the TcpListener timeout value but results were inconclusive.

1

There are 1 answers

0
Yusuf Karaman On

The exception you are seeing, System.IO.IOException, is a normal behavior when working with TcpListener and AcceptTcpClient() method. It is thrown when there is no pending connection request from a client at the time AcceptTcpClient() is called. This is expected behavior and is used to provide a non-blocking operation.

When you start your TcpListener and call AcceptTcpClient() for the first time, it waits for a client to connect. Since no client has connected yet, it waits for a certain period of time (controlled by the underlying operating system) before throwing the IOException. After the first time, subsequent calls to AcceptTcpClient() will work correctly because there will be a pending connection request from a client.