【发布时间】:2011-01-19 22:20:51
【问题描述】:
我阅读了一些 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 个客户端线程)。我认为聊天服务器会有大量线程的开销。请帮我一个解决方案。谢谢。
更新: 我相信聊天示例仅用于学习网络,它们不适合现实世界的模型。请给我一个现实世界的解决方案。谢谢。
【问题讨论】:
-
如果您期望有 10,000 个客户端,您将遇到其他问题(带宽,一个)
标签: c# architecture networking