0
我需要製作一個服務器,接受並保持很長時間許多連接(透視超過100k)。許多TcpListener傳入連接
我的代碼如下:
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);
}
}
}
當邏輯需要多達300-400毫秒是沒有問題的。但是如果我想長時間保持傳入連接,count接受8個客戶端後變量遞增很慢,而且出現內存使用量巨大的問題。我做錯了什麼,以及如何解決這個問題?
很多閱讀:http://smallvoid.com/article/winnt-tcpip-max-limit.html –