有很多客户端的聊天服务器 [英] Chat server with a lot of clients

查看:30
本文介绍了有很多客户端的聊天服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了一些 C# 聊天源代码 &我看到:在具有大量连接客户端的聊天服务器上,服务器侦听器将在单独的线程中运行 &每个连接的客户端也将在一个单独的线程中运行.代码示例:

I read some C# chat source code & I see that: on chat server with a lot of connected clients, server listener will run in a separated thread & each connected client will also run in a separated thread. Code examples:

启动服务器 &在单独的线程中开始收听:

Start server & begin listening in a separated thread:

    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);
            }
        }

并且一个连接也会在一个单独的线程中运行:

And a connection will also run in a separated thread:

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 个客户端线程).我认为聊天服务器会有大量线程的开销.请帮我一个解决方案.谢谢.

So, if a chat server with 10000 connected clients, the chat server application will have 10002 threads (one main thread, one server thread & 10000 client threads). I think the chat server will be overhead with a big number of threads. Please help me a solution. Thanks.

更新:我相信聊天示例仅用于学习网络和它们不适合现实世界的模型.请给我一个现实世界的解决方案.谢谢.

UPDATE: I believe chat examples are only for learning networking & they are not suitable in real-world model. Please give me a real-world solution. Thanks.

推荐答案

如果您使用 .Net framework 2.0 SP2 或更高版本,那么您可以使用基于 IO 完成端口.在这种情况下,您不应创建自己的线程,因为 IO 完成端口会为您完成所有工作.

If you use .Net framework 2.0 SP2 or higher, than you may use new asyncrhronous sockets model based on IO Completion ports. In this case you shouldn't create your own threads, because IO Completion ports do all job for you.

这里有一些例子:

tcpServer = new System.Net.Sockets.TcpListener(IPAddress.Any, port);
tcpServer.Start();
tcpServer.BeginAcceptSocket(EndAcceptSocket, tcpServer);


private void EndAcceptSocket(IAsyncResult asyncResult)
{
    TcpListener lister = (TcpListener)asyncResult.AsyncState;
    Socket sock = lister.EndAcceptSocket(asyncResult);
    //handle socket connection (you may add socket to you internal storage or something)

    //start accepting another sockets
    lister.BeginAcceptSocket(EndAcceptSocket, lister);


    SocketAsyncEventArgs e = new SocketAsyncEventArgs();
    e.Completed += ReceiveCompleted;
    e.SetBuffer(new byte[socketBufferSize], 0, socketBufferSize);
    sock.ReceiveAsync(e);
}


void ReceiveCompleted(object sender, SocketAsyncEventArgs e)
{
    var sock = (Socket)sender;
    if (!sock.Connected)
    {
      //handle socket disconnection
    }
    var buf = new byte[size];
    Array.Copy(e.Buffer, buf, size);
    //handle received data

    //start reading new data
    sock.ReceiveAsync(e);
}

这篇关于有很多客户端的聊天服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆