应用程序运行时C#TCP套接字性能下降

Mau*_*imo 4 .net c# sockets

我写了一个C#服务器应用程序.服务器使用异步TCP套接字.

数据包是80-180字节的数据.

对于性能测试,我有一个客户端连接并连续发送数据包.通过调试前100个数据包(0-100)在大约5秒内接收.当服务器收到数据包#300-400时,接收数据包大约需要30秒.随着更多接收发生,性能继续下降.

我环顾四周,一直无法找到解决方案.我已经尝试设置Socket.NoDelay标志,以防Nagle算法禁止服务器.

我已经禁用了服务器中的所有功能; 所以它只是收到以确保我没有失去其他代码中的性能.

我还检查了我的CPU利用率,它是~13%.我有超过2 GB的可用内存.在运行应用程序时,ram不会不断增长,利用率也很低.

关于调试什么以及接下来的问题,我感到很茫然......

编辑:添加代码示例

public void StartListening()
    {

        try
        {
            IPAddress ipAddress = IPAddress.Parse("192.168.2.60");
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, m_Port);
            m_MainSocket = new Socket(localEndPoint.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            m_MainSocket.NoDelay = true;
            m_MainSocket.Bind(localEndPoint);
            m_MainSocket.Listen(10);
            m_MainSocket.BeginAccept(new AsyncCallback(clientConnected), null);

            System.Diagnostics.Debug.WriteLine("Listening on:Local IP Address: " + localEndPoint.Address.ToString() + " Port :" + localEndPoint.Port.ToString() + "\n");
        }
        catch (SocketException se)
        {
            System.Diagnostics.Debug.WriteLine("Listening Exception \n");
            System.Diagnostics.Debug.WriteLine(se.Message);
        }
    }

    void clientConnected(IAsyncResult ar)
    {
        try
        {
            SocketState state = new SocketState(m_MainSocket.EndAccept(ar));
            Client client = new Client(state);

            if (client.SocketState.clientSocket.Connected)
            {
                System.Diagnostics.Debug.WriteLine("Client #?????? Connected \n");
                AddLogText("Client #?????? Connected \r\n\r\n");
                waitForData(client);
                SetSendButton(true);
            }

            m_MainSocket.BeginAccept(new AsyncCallback(clientConnected), null);
        }
        catch (ObjectDisposedException)
        {
           System.Diagnostics.Debug.WriteLine("Client Connected: Socket has been closed\n");
        }
        catch (SocketException se)
        {
            System.Diagnostics.Debug.WriteLine("Client Connected Exception \n");
            System.Diagnostics.Debug.WriteLine(se.Message);
        }
    }

    void waitForData(Client client)
    {
        try
        {
            SocketState state = new SocketState(client.SocketState.clientSocket);
            client.SocketState.clientSocket = null; 
            client.SocketState = state;
            client.SocketState.clientSocket.BeginReceive(client.SocketState.DataBuffer, 0, client.SocketState.DataBuffer.Length, SocketFlags.None, new AsyncCallback(readDataCallback), client);
        }
        catch (SocketException se)
        {
            System.Diagnostics.Debug.WriteLine("Wait For Data Exception \n");
            System.Diagnostics.Debug.WriteLine(se.Message);
        }

    }

    public void readDataCallback(IAsyncResult ar)
    {
        Client client = (Client)ar.AsyncState;
        try
        {                
            // Read data from the client socket.
            int iRx = client.SocketState.clientSocket.EndReceive(ar);
            client.SocketState.SB.Append(Encoding.ASCII.GetString(client.SocketState.DataBuffer, 0, iRx));
            string sPacketString = client.SocketState.SB.ToString();

            Server formServer = this;
            Packet_Helper packet_helper = new Packet_Helper(sPacketString, formServer);

            Packet packet = new Packet(sPacketString);
            client.SerialNumber = packet.SerialNumber;
            client.FirmwareVersion = packet.FirmwareVersion;
            client.ProductID = packet.ProductID;
            client.HardwareVersion = packet.HardwareVersion;
            if (!m_Clients.ContainsKey(packet.SerialNumber))
            {
                m_Clients.Add(packet.SerialNumber, client);
                UpdateClientList();
                string[] packets = client.refreshAll();
                for (int i = 0; i < packets.Length; i++)
                {
                    byte[] byteData = Encoding.ASCII.GetBytes(packets[i]);
                    client.SocketState.clientSocket.BeginSend(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(SendCallback), client);
                    AddPacketsSentText(packets[i] + "--" + (iSent++).ToString() + "\r\n\r\n");
                }
            }

            System.Diagnostics.Debug.WriteLine("Read " + sPacketString.Length.ToString() + " bytes from " + client.SerialNumber + "\n" + sPacketString + "\n");
            AddLogText("Read " + sPacketString.Length.ToString() + " bytes from " + client.SerialNumber + " \r\n");
            AddLogText(sPacketString.ToString() + "\r\n\r\n");

            waitForData(client);
        }
        catch (ObjectDisposedException)
        {
            System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
        }
        catch (SocketException se)
        {
            if (se.ErrorCode == 10054) // Error code for Connection reset by peer
            {
                string sclientSerial = "??????";
                if (client.SerialNumber != null || client.SerialNumber != "")
                    sclientSerial = client.SerialNumber;
                AddLogText("Client " + sclientSerial + " Disconnected" + "\r\n\r\n");
                System.Diagnostics.Debug.WriteLine("Client " + sclientSerial + " Disconnected" + "\n");

                m_Clients.Remove(sclientSerial);
                UpdateClientList();
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("Read Data Exception \n");
                System.Diagnostics.Debug.WriteLine(se.Message);
            }
        }
    }


class SocketState
{
    private Socket m_ClientSocket;                   //Socket connection to the client
    private byte[] m_DataBuffer = new byte[256];        //Buffer to store the data sent by the client
    private StringBuilder m_SB = new StringBuilder();  //for building recieved data into a string 

    /// <summary>
    /// Gets or Sets the client Socket
    /// </summary>
    public Socket clientSocket
    {
        get { return m_ClientSocket; }
        set { m_ClientSocket = value; }
    }

    /// <summary>
    /// Gets the DataBuffer
    /// </summary>
    public byte[] DataBuffer
    {
        get { return m_DataBuffer; }
        set { DataBuffer = value; }
    }

    /// <summary>
    /// Gets or Sets the SB
    /// </summary>
    public StringBuilder SB
    {
        get { return m_SB; }
        set { m_SB = value; }
    }

    public SocketState(Socket socket)
    {
        m_ClientSocket = socket;
        m_ClientSocket.ReceiveBufferSize = 256;
        m_ClientSocket.NoDelay = true;
        //m_DataBuffer = Enumerable.Repeat((byte)0, 256).ToArray();
    }
}      
Run Code Online (Sandbox Code Playgroud)

编辑:添加AddLogText()函数.此函数用于将文本添加到UI中的文本框.

// Delegate - 启用异步调用以设置tb_ListeningLog的text属性

delegate void AddLogTextCallback(string text);

private void AddLogText(string text)
    {
        // InvokeRequired required compares the thread ID of the
        // calling thread to the thread ID of the creating thread.
        // If these threads are different, it returns true.
        if (this.tb_ListeningLog.InvokeRequired)
        {
            AddLogTextCallback d = new AddLogTextCallback(AddLogText);
            this.Invoke(d, new object[] { text });
        }
        else
        {
            this.tb_ListeningLog.Text += text;
            tb_ListeningLog.SelectionStart = tb_ListeningLog.Text.Length;
            tb_ListeningLog.ScrollToCaret();
        }
    }
Run Code Online (Sandbox Code Playgroud)

Tim*_*z0r 5

我用这个答案在黑暗中拍了一下,但你发布的代码肯定有帮助.

随着时间的推移你可能会看到性能下降的原因是因为你的readDataCallback方法中的代码.您设置的方式,数据处理在您再次接收之前完成.这意味着随着处理长度的增加,接收数据之间的持续时间也会增加.

我不知道你的很多方法中有什么代码,但是你应该看看可能需要一段时间才能完成的任何循环.如果您在查找代码时遇到问题,请尝试查找哪些方法花费的时间最长,然后继续缩小代码范围.

例如(我猜测瓶颈在这个代码区域):

if (!m_Clients.ContainsKey(packet.SerialNumber))
{
    m_Clients.Add(packet.SerialNumber, client);

    AddLogText("Running UpdateClientList\r\n");

    UpdateClientList();

    AddLogText("Doing client.refreshAll\r\n");

    string[] packets = client.refreshAll();

    AddLogText("Doing for loop\r\n");

    for (int i = 0; i < packets.Length; i++)
    {
        byte[] byteData = Encoding.ASCII.GetBytes(packets[i]);
        client.SocketState.clientSocket.BeginSend(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(SendCallback), client);
        AddPacketsSentText(packets[i] + "--" + (iSent++).ToString() + "\r\n\r\n");
    }
}
Run Code Online (Sandbox Code Playgroud)

只需观察每种方法与眼睛之间的时间量,或使其更容易并使用StopwatchDateTime显示确切的时间.

此外,如果您发现代码的行为无法提高效率,您可以想到在单独的线程中处理数据.我假设不希望这种行为,因为手头的问题.


对于您的AddLogText方法,请尝试使用tb_ListeningLog.Text.AppendText而不是+ =.

  • + =使用字符串连接,这在较大的字符串上很昂贵; 随着文本框中文本的数量增加,操作变得更加昂贵.`AppendText`使用不涉及连接的方法,您可以通过反编译器观察. (2认同)