1

除了内存使用量以惊人的速度增加之外,我还在最终接收和 pgm 停止时收到“现有连接已被远程主机 10054 关闭”。请帮忙
谢谢

我有一个 TCP 套接字服务器,它工作正常。但是工作内存从 10 MB 增长到 250 MB。

我监视了任何 closed_wait 套接字的嵌套,但没有找到任何?

任何人都可以帮助我。它必须处理许多没有内存泄漏的连接。

StartListen 的代码

void StartListen(object sender, System.EventArgs e)
{
    try
    {
        string portStr = textBoxPort.Text;
        int port = System.Convert.ToInt32(portStr);
        // Create the listening socket...
        m_mainSocket = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream,
            ProtocolType.Tcp);
        IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);

        m_mainSocket.Bind(ipLocal);

        m_mainSocket.Listen(100);

        m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect),null);

        UpdateControls(true);
    }
    catch (SocketException se)
    {
        writer.WriteToLog("In StartListen " + se.Message);
    }
}

public void OnClientConnect(IAsyncResult asyn)
{
    try
    {
        Socket m_mainSocket = (Socket)asyn.AsyncState;

        Socket workerSocket = m_mainSocket.EndAccept(asyn);
        Interlocked.Increment(ref m_clientCount);

        m_workerSocketList.Add(workerSocket);

        WaitForData(workerSocket, m_clientCount);

        m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
    }
    catch (ObjectDisposedException)
    {
        System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
    }
    catch (Exception se)
    {
        writer.WriteToLog(DateTime.Now.ToString() + " OnClientConnect " + se.Message);
    }
}

public void OnDataReceived(IAsyncResult asyn)
{
    // Logger.Log("In OnDataReceived");
    SocketPacket socketData = (SocketPacket)asyn.AsyncState;
    bool socketClosed = false;


    try
    {
        // Complete the BeginReceive() asynchronous call by EndReceive() method
        // which will return the number of characters written to the stream 
        // by the client
        int iRx = socketData.m_currentSocket.EndReceive(asyn);
        char[] chars = new char[iRx + 1];
        // Extract the characters as a buffer
        System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
        int charLen = d.GetChars(socketData.dataBuffer,
            0, iRx, chars, 0);




        System.String szData = new System.String(chars);
            szData= szData.TrimEnd('\0');




             if (!SocketExtensions.IsConnected(socketData.m_currentSocket)) {

            socketData.m_currentSocket.Shutdown(SocketShutdown.Both);
            socketData.m_currentSocket.Close();
                              return;
               } 

        else
        {

            WaitForData(socketData.m_currentSocket, socketData.m_clientNumber);
        }
    }
    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 msg = "Client " + socketData.m_clientNumber + " Disconnected" + "\n";

            // Remove the reference to the worker socket of the closed client
            // so that this object will get garbage collected
            m_workerSocketList[socketData.m_clientNumber - 1] = null;
            UpdateClientListControl();
        }
        else
        {
            MessageBox.Show(se.Message);
           // Logger.Log(se.Message);
            writer.WriteToLog("OnDataReceived " + se.Message);

        }
    }
    catch (Exception ex)
    {
       // Logger.Log(ex.Message);
        writer.WriteToLog("OnDataReceived " + ex.Message);
    }
}
static class SocketExtensions
{
    public static bool IsConnected(this Socket socket)
    {
        try
        { 
            return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0);
        }
        catch (SocketException) { return false; }
    }
}
4

1 回答 1

0

.NET 应用程序的内存占用增长到一定大小是没有问题的,只要它不继续增长。根据工作负载,您的 TCP 服务器每次接受新客户端并发送/接收数据时都会分配许多对象。即使不再使用它们,这些对象也会在内存中停留一段时间,直到 GC 释放它们。这并不意味着存在内存泄漏。

如果内存使用量增长得如此之快以至于您遇到了系统内存问题,请确保您在处理客户端请求时不会以某种方式保留一些创建的对象。

于 2012-09-13T07:37:02.060 回答