简体   繁体   English

异步tcp伺服器内存不断增长,并且有时在接收时收到10054错误

[英]Async tcp sever memory keeps on growing and also getting 10054 error on endreceive sometime

In addition to memory usage increase at an alarming rate, I am also getting "An existing connection was closed by remote host 10054" at end receive and pgm stops. 除了以惊人的速度增加内存使用量之外,在接收结束时我还收到“远程主机10054关闭了现有连接”,并且pgm停止了。 Please help 请帮忙
Thanks 谢谢

I have a TCP socket server and it works fine . 我有一个TCP套接字服务器,它工作正常。 But the working memory grows from 10 MB to 250 MB. 但是工作内存从10 MB增长到250 MB。

I monitored nestat for any closed_wait sockets, but did not find any? 我监视了nestat是否有任何closed_wait套接字,但是没有找到任何套接字?

Can anybody please help me. 有人可以帮我吗? It must handle many connections with no memory leak. 它必须处理许多连接而不会发生内存泄漏。

Code for StartListen 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; }
    }
}

There's no problem with the memory footprint of a .NET app growing to a certain size, as long as it doesn't keep on growing. .NET应用程序的内存占用量增长到一定大小没有任何问题,只要它不会持续增长即可。 Depending on the work load, your TCP server allocates many objects everytime it accepts new clients, and sends/receives data. 根据工作负载,TCP服务器每次接受新客户端并发送/接收数据时都会分配许多对象。 Even after they are no longer used, these objects stay in memory for a while until GC releases them. 即使不再使用它们,这些对象也会在内存中保留一段时间,直到GC释放它们。 This doesn't mean there is a memory-leak. 这并不意味着存在内存泄漏。

If the memory usage is growing so much that you're running into system memory problems, make sure you're not somehow keeping around some objects created while handling client requests. 如果内存使用量增长太多,导致您遇到系统内存问题,请确保在处理客户端请求时不要以某种方式保留创建的某些对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法停止异步TCP服务器Windows服务 - Can not stop async TCP sever Windows service C#TCP异步EndReceive()仅在Windows XP 32位上引发InvalidOperationException - C# TCP Async EndReceive() throws InvalidOperationException ONLY on Windows XP 32-bit 没有字符串的异步套接字中的 EndReceive - EndReceive in Async Socket without strings C# Parallel.ForEach() 内存使用量不断增长 - C# Parallel.ForEach() memory usage keeps growing Websphere MQ 7.0.1 C#XMS连接导致10054(X'2746')tcp错误 - Websphere MQ 7.0.1 C# XMS connection causing 10054 (X'2746') tcp Error 数据上下文注册为瞬态,但 memory 的使用量不断增长。 我的 DI 配置有问题吗? - Data context registered as transient, but memory usage keeps growing. Is there something wrong with my DI configuration? 浏览器上的内存使用量不断增长的IIS 7.5 Asp.net应用程序 - Memory Usage on Browsers Keeps Growing IIS 7.5 Asp.net Apps Azure Functions-Node.js和Dot Net Core 2.2内存消耗在回收之前一直在增长 - Azure Functions - nodejs and dot net core 2.2 memory consumption keeps growing until recycled C# .NET 套接字 tcp begin/endreceive 客户端:endreceive 读取所有字节,但在 beginreceive 中,缓冲区大小自行更改 - C# .NET socket tcp begin/endreceive client : endreceive reads all bytes, but in beginreceive, the buffer size changes on its own 下载Excel输出文件时有时出错 - Sometime getting error while downloading the Excel output file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM