我有一個C#程序有很多(比方說大約一千個)打開了TcpClient對象。我想進入一個狀態,等待任何這些連接發生。處理多個TcpClient連接而不使用線程
我寧願不爲每個連接啓動一個線程。
喜歡的東西...
while (keepRunning)
{
// Wait for any one connection to receive something.
TcpClient active = WaitAnyTcpClient(collectionOfOpenTcpClients);
// One selected connection has incomming traffic. Deal with it.
// (If other connections have traffic during this function, the OS
// will have to buffer the data until the loop goes round again.)
DealWithConnection(active);
}
附加信息:
的TcpClient的對象來自的TcpListener。
目標環境將是MS .NET或Mono-on-Linux。
該協議在連接打開時要求長時間閒置。
在Unix世界中,您將使用'select'系統調用來執行此操作。我確定Windows中有一些模擬。 – 2011-04-04 17:02:31
你對「每個連接的線程」的假設是有缺陷的。線程池與APM方法結合是解決這類問題的方法。只有幾個線程可以爲許多客戶提供服務。我給了這個答案應該證明內容豐富:http://stackoverflow.com/questions/3153959/how-does-a-full-featured-long-polling-server-work-abstractly/3154115#3154115 – spender 2011-04-04 17:11:42
@spender - 你建議我BeginRead all〜1000 TcpClients並處理回調中的任何流量?如果你想把它寫成答案,我會接受它。 – billpg 2011-04-04 17:24:09