TcpListener Timeout / o / something? Without ASync?

I am creating a thread that uses TcpListener, and when my application closes, I want thead to end. I can cause an interrupt, but the thread is still alive, because TcpListener is blocking AcceptTcpClient.

Is it possible to set or set a timeout or to do SOMETHING with AcceptTcpClient? I can not imagine how it would be useful if it were not for stopping them 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?

+3
source share
3 answers

A simple solution. CHECK pending.

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

You can replace the AcceptTcpClient call with one for Socket.Select (), which may expire.

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

AcceptTcpClient() while(!Disposing) .
I, Stop() TcpListener Disposing true; :

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();
    }
}

, ...

, AcceptTcpClient() .
Thread (Start() function).

+3

Source: https://habr.com/ru/post/1756069/


All Articles