简体   繁体   中英

Many TcpListener incoming connections

I need to make a server that accepts and keeps for a long time many connections (perspectively over 100k).

My code is below:

public delegate Task ClientConnectedEventHandler(Stream stream);

public class Listener
{
    public event ClientConnectedEventHandler OnClientConnected;

    private readonly TcpListener _tcpListener;

    public Listener()
    {
        _tcpListener = new TcpListener(new IPEndPoint(IPAddress.Any, 8082));
    }

    public void Start()
    {
        _tcpListener.Start();
        _tcpListener.BeginAcceptTcpClient(Accept, null);
    }

    private void Accept(IAsyncResult asyncResult)
    {
        _tcpListener.BeginAcceptTcpClient(Accept, null);
        var client = _tcpListener.EndAcceptTcpClient(asyncResult);
        var stream = client.GetStream();
        OnClientConnected?.Invoke(stream).ContinueWith(_ => client.Close());
    }
}

class Program
{
    static void Main(string[] args)
    {
        var listener = new Listener();
        var count = 0;
        var infoLock = new object();

        listener.OnClientConnected += async stream =>
        {
            lock (infoLock)
            {
                count++;
                Console.Title = count.ToString();
            }
            while (true)
            {
                // Some logic
                await Task.Delay(100);
            }
        };

        listener.Start();
        while (true)
        {
            Thread.Sleep(100);
        }
    }
}

There is no problem when the logic takes up to 300-400 ms. But if I want to keep incoming connections for a long time, count variable increments very slow after accepting 8 clients, moreover appears a trouble with huge memory usage. What I'm doing wrong and how to resolve this?

Your memory issue may be caused by not disposing unmanaged resources. Both TcpClient and NetworkStream implement IDisposable and should be wrapped in Using blocks or manually Closed/Disposed. See How to properly and completely close/reset a TcpClient connection? for starters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM