How can I constantly monitor new TCP clients?

I have a TCP server that asynchronously monitors new incoming clients and adds them to the list of clients:

public class TcpServer
{
    public List<TcpClient> ClientsList = new List<TcpClient>();
    protected TcpListener Server = new TcpListener(IPAddress.Any, 3000);
    private _isMonitoring = false;

    public TcpServer()
    {
        Server.Start();
        Server.StartMonitoring();
    }

    public void StartMonitoring()
    {
        _isMonitoring = true;
        Server.BeginAcceptTcpClient(HandleNewClient, null);
    }

    public void StopMonitoring()
    {
        _isMonitoring = false;
    }

    protected void HandleNewClient(IAsyncResult result)
    {
        if (_isMonitoring)
        {
            var client = Server.EndAcceptTcpClient(result);
            ClientsList.Add(client);

            StartMonitoring(); // repeats the monitoring
        }
    }
}

However, I am having two problems with this code.

First call StartMonitoring()in HandleNewClient(). Without it, the server will accept only one incoming connection and ignore any additional connections. What I would like to do is constantly keep an eye on new customers, but something spoils me incorrectly as to how I do it now. Is there a better way to do this?

_isMonitoring. , . - , ? , , while (true).

+3
1

, StartMonitoring - , , . , , .

, / /, , , , StartMonitoring :

public void StartMonitoring()
{
    _isMonitoring = true;
    while (_isMonitoring)
        Server.BeginAcceptTcpClient(HandleNewClient, null);
}

, _isMonitoring , volatile , , .

+3

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


All Articles