基准测试中的许多TCPClient都没有正确关闭

时间:2012-01-15 13:44:15

标签: c# sockets tcp tcpclient

我正在为我的TCP-Socket服务器编写基准程序。 基本概念如下:

  • 客户端创建10000个连接
  • 有2500个并发连接
  • 他们都向服务器发送10秒乒乓消息并接收pong
  • 10秒后他们全部断开连接

当我使用较少数量的连接(100个并发和1000个连接)时,一切正常,但是通过上面的设置,一些连接在服务器上保持连接。 这意味着关闭呼叫根本不会到达服务器。

以下是上述解释的代码:

    class Program {   
    static List<Thread> mConnectionThreads_ = new List<Thread>();                  //!< The list of the Threads for all textloaders
    static List<TCPConnection> mConnections_ = new List<TCPConnection>();         //!< The list of TextsXMLParser

    static void Main(string[] args) {
        int numConnections = 10000;
        int numConcurrentConnections = 2500;
        for( int k = 0; k < numConnections/numConcurrentConnections; ++k) {
            for( int i = 0; i < numConcurrentConnections; ++i ) {
                TCPConnection connection = new TCPConnection();
                connection.connect(((k+1)*numConcurrentConnections)+i);
                mConnections_.Add(connection);
                mConnectionThreads_.Add(new Thread(connection.pingLoop));
            }
            Console.WriteLine(((k+1)*numConcurrentConnections) + "/" + numConnections + " Threads connected");

            // start all threads
            foreach (Thread t in mConnectionThreads_)
                t.Start();

            foreach (Thread t in mConnectionThreads_)
                t.Join();
            foreach (TCPConnection c in mConnections_)
                c.disconnect();
            Console.WriteLine(((k+1)*numConcurrentConnections) + "/" + numConnections + " Threads disconnected " + cnt + " calls");
            mConnections_.Clear();
            mConnectionThreads_.Clear();
        }
    }
}

断开连接功能如下所示:

    public void disconnect() {
        if(  mClient_.Client != null ) {
            mClient_.Client.Disconnect(false);
            //mClient_.GetStream().Close();
            //mClient_.Close();
            Console.WriteLine("closed " + mConnectionId_);
        }
        else if( mClient_.Client == null )
            Console.WriteLine("closed invalid " + mConnectionId_);
    }

正如你所看到的,我已经尝试了很多不同的近距离方法,但更直接的方法。

在这种情况下我能做些什么吗?还有其他人有同样的问题吗?

1 个答案:

答案 0 :(得分:0)

也许我错过了什么类型,但mClient_.Client是什么类型的?

通常,如果使用TCP客户端(TCPClient类),则可以调用Close来关闭连接。以直接使用Socket或NetworkStream的方式相同,您也可以调用Close。

另一方面,您正在检测和调试服务器上的连接打开/关闭连接,对吧?服务器代码可能无法正确处理连接,从而导致统计信息不正确。

同样在高负载下,服务器可能没有足够的CPU时间来更新连接的状态,因此您可能会遇到一些延迟。您的服务器是否使用异步I / O或每线程连接原则?