Good day.

To wait for incoming connections I use the TcpListener class. What should I do if I have a timeout to wait for a new connection = 30 seconds, and the installation of Server.ReceiveTimeout does not work?

Code:

  SMTP_Listener = new TcpListener(IPAddress.Any, 8888); SMTP_Listener.Server.ReceiveTimeout = timeout; // не срабатывает SMTP_Listener.Start(); SMTP_Listener.Server.ReceiveTimeout = 5; while (true) { Socket clientSocket = SMTP_Listener.AcceptSocket(); // висим на этой строчке и все, никуда дальше. Как таймаут сделать? if (clientSocket.Connected) { } Console.WriteLine("***"); } 

thank

  • What for? this is a workflow. The cycle is organized like this. - nick_n_a
  • On AcceptSocket (), the process hangs, and I want to stop it after the time expires, to issue a message, for example. How to do it here? - Leonard Bertone
  • Usually create a separate thread that can be stopped. Create Thread - Make Sleep then Abort. But for one example, one of the habrahabr.ru/post/120157 articles, for example, did sockets for them. - nick_n_a
  • ReceiveTimeout is not that timeout, it is a timeout for Receive not on Accept. - nick_n_a
  • one
    @nick_n_a: Abort? Uh ... Abort function can not be used . This is a direct path to shattered memory and deadlock. Do not teach the vehicle bad. - VladD

1 answer 1

Try this:

 SMTP_Listener.Server.Poll(timeout, SelectMode.SelectRead); 

This method should return true if there is an incoming connection (in this case, you can already call AcceptSocket / AcceptTcpClient , they will work without blocking). If the timeout is out, the method will return false .

  • Thank! It helped - Leonard Bertone