我看了一些C#聊天源代碼&我看到:在聊天服務器上連接了很多客戶端,服務器監聽器會運行在一個單獨的線程中&每個連接的客戶端也會運行在一個分離的線。 代碼示例:與很多客戶端的聊天服務器
啓動服務器&開始在一個獨立的線程監聽:
public void StartListening()
{
// Get the IP of the first network device, however this can prove unreliable on certain configurations
IPAddress ipaLocal = ipAddress;
// Create the TCP listener object using the IP of the server and the specified port
tlsClient = new TcpListener(1986);
// Start the TCP listener and listen for connections
tlsClient.Start();
// The while loop will check for true in this before checking for connections
ServRunning = true;
// Start the new tread that hosts the listener
thrListener = new Thread(KeepListening);
thrListener.Start();
}
private void KeepListening()
{
// While the server is running
while (ServRunning == true)
{
// Accept a pending connection
tcpClient = tlsClient.AcceptTcpClient();
// Create a new instance of Connection
Connection newConnection = new Connection(tcpClient);
}
}
和連接也將在一個獨立的線程運行:
public Connection(TcpClient tcpCon)
{
tcpClient = tcpCon;
// The thread that accepts the client and awaits messages
thrSender = new Thread(AcceptClient);
// The thread calls the AcceptClient() method
thrSender.Start();
}
所以,如果有一個聊天服務器10000個連接的客戶端,聊天服務器應用程序將有10002個線程(一個主線程,一個服務器線程& 10000個客戶端線程)。我認爲聊天服務器會佔用大量的線程。請幫我解決。謝謝。
UPDATE: 我相信聊天的例子只是爲了學習網絡&它們不適合於現實世界的模型。請給我一個真實世界的解決方案。謝謝。
如果你期待10,000個客戶端,你會有其他問題(帶寬,爲一) – SLaks 2010-02-23 03:37:17
請參閱http://stackoverflow.com/questions/869744/how-to-write-a-scalable-tcp-ip-based-server – Jimmy 2010-02-23 03:38:21