Tutorial :TcpListener Timeout/about/something? Without ASync?



Question:

I create a thread which uses TcpListener and when my app closes i'd like the thead to terminate. I can call abort but the thread is still alive since TcpListener is blocking with AcceptTcpClient.

Is it possible to about or set a timeout or to do SOMETHING with AcceptTcpClient? i cant imagine how it would be useful if theres no way to stop it from blocking forever. My code is serial and i would like it to stay that way so is there a solution without using BeginAcceptTcpClient? and writing ASync code?


Solution:1

Simple solution. CHECK with pending.

while(!server.Pending())  {      Thread.Sleep(10);  }  TcpClient client = server.AcceptTcpClient();  


Solution:2

You could replace the call to AcceptTcpClient with one for Socket.Select(), which can timeout.

var sockl = new ArrayList { listener.Server };  Socket.Select(sockl, null, null, _timeout_);  if (sockl.Contains(listener.Server)) listener.AcceptTcpClient();  


Solution:3

I use AcceptTcpClient() in a while(!Disposing) loop to accept my clients.
When I dispose the Class I call the Stop() function of the TcpListener and set Disposing to true; like this:

public class Server : IDisposable  {      private TcpListener _tcpListener;      private bool _isDisposing;        public void Start()      {          (new Thread(new ThreadStart(ListenForClients))).Start();      }        private void ListenForClients()      {          this._tcpListener = new TcpListener(System.Net.IPAddress.Any, this.ListenPort);          this._tcpListener.Start();            while (!_isDisposing)          {              //blocks until a client has connected to the server              TcpClient client = this._tcpListener.AcceptTcpClient();                if (client == null) continue;                //create a thread to handle communication with connected client          }      }        public void Dispose()      {          this._isDisposing = true;          this._tcpListener.Stop();      }  }  

Note that this is just a small excerpt from a server class...

This way, the program can stay locked on the AcceptTcpClient() function and still be ended.
However, the listening itself must also happen on a separate Thread (Start() function).


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »