Async Socket Server exe memory increases by 10 percent per day

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • abk123
    New Member
    • Oct 2012
    • 1

    Async Socket Server exe memory increases by 10 percent per day

    I have an async tcp socket server sending data to MSMQ. The exe memory increases and I am suspecting a memory leak. This server should run 24/7 and must not have any memory leak. I am new to sockets . Please help. Code attached Thanks

    Code:
                void StartListen()
                {
    
                                   try
                    {
                        // Check the port value
                      
                        string portStr = 9999;
                        
                        try
                        {
                            // NOTE: DNS lookups are nice and all but quite time consuming.
                            strHostName = Dns.GetHostName();
                            IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
                            aryLocalAddr = ipEntry.AddressList;
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error trying to get local address {0} ", ex.Message);
                        }
    
                        // Verify we got an IP address. Tell the user if we did
                        if (aryLocalAddr == null || aryLocalAddr.Length < 1)
                        {
                            Console.WriteLine("Unable to get local address");
                            return;
                        }
                        // Create the listening socket...
                        m_mainSocket = new Socket(AddressFamily.InterNetwork,
                            SocketType.Stream,
                            ProtocolType.Tcp);
                        IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);
                        // Bind to local IP Address...
                        m_mainSocket.Bind(ipLocal);
                        // Start listening...
                        m_mainSocket.Listen(500);
                        // Create the call back for any client connections...
                     m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
                                           
                    }
                    catch (SocketException se)
                    {
                        writer.WriteToLog(se.Message);
                    }
    
                }
    
                public bool isAlive()
                {
                    return m_mainSocket != null;
                }
    
    
    
          
                // This is the call back function, which will be invoked when a client is connected
                public void OnClientConnect(IAsyncResult asyn)
                {
                    if (!isAlive()) 
                    {
                        return;
                    }
    
                    try
                    {
                       Socket workerSocket = m_mainSocket.EndAccept(asyn);
                        
                        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 (SocketException se)
                    {
                        writer.WriteToLog(se.Message);
                    }
    
                }
                public class SocketPacket
                {
                    // Constructor which takes a Socket and a client number
                    public SocketPacket(System.Net.Sockets.Socket socket, int clientNumber)
                    {
                        m_currentSocket = socket;
                        m_clientNumber = clientNumber;
                    }
                    public System.Net.Sockets.Socket m_currentSocket;
                    public int m_clientNumber;
                    // Buffer to store the data sent by the client
                    public byte[] dataBuffer = new byte[2048];
                }
                // Start waiting for data from the client
                public void WaitForData(System.Net.Sockets.Socket soc, int clientNumber)
                {
                    try
                    {
                        if (pfnWorkerCallBack == null)
                        {
                            // Specify the call back function which is to be 
                            // invoked when there is any write activity by the 
                            // connected client
                            pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
                        }
                        SocketPacket theSocPkt = new SocketPacket(soc, clientNumber);
                       
                        soc.BeginReceive(theSocPkt.dataBuffer, 0,
                            theSocPkt.dataBuffer.Length,
                            SocketFlags.None,
                            pfnWorkerCallBack,
                            theSocPkt);
               
                        
                    }
                    catch (SocketException se)
                    {
                       writer.WriteToLog(se.Message);
                    }
               }
              
                // This the call back function which will be invoked when the socket
                // detects any client writing of data on the stream
                public void OnDataReceived(IAsyncResult asyn)
                {
                    SocketPacket socketData = (SocketPacket)asyn.AsyncState;
                    int iRx = 0;
                    try
                    {
                        try
                        {
                            SocketError errorCode;
                            // int nBytesRec = socket.EndReceive(ar, out errorCode);
                             iRx = socketData.m_currentSocket.EndReceive(asyn, out errorCode);
                             if (errorCode != SocketError.Success)
                             {
                                 iRx = 0;
                                 socketData.m_currentSocket.Shutdown(SocketShutdown.Both);
                                 socketData.m_currentSocket.Close();
                                 socketData.m_currentSocket.Disconnect(false);
    
                                 socketData = null;
                                 socketData.m_currentSocket = null;
                                 socketData.dataBuffer = null;
                                 m_mainSocket.Shutdown(SocketShutdown.Both);
                                 m_mainSocket.Close();
                                 m_mainSocket.Disconnect(false);
                                 this.Dispose();
    m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
    
                             } 
    
                        }
                        catch (SocketException se)
                        {
                            writer.WriteToLog("data received");
                          
                            writer.WriteToLog(se.ErrorCode.ToString());
                            writer.WriteToLog(se.Message);
    
                            socketData.m_currentSocket.Shutdown(SocketShutdown.Both);
                            socketData.m_currentSocket.Close();
                         
                            this.Dispose();
                       
                        }
                      
                       if (iRx < 0) {
                           string Mesg = socketData.m_currentSocket.RemoteEndPoint + "  Disconnected" + "\n";
                           this.textBoxMsg.Text = Mesg.ToString();
                         
                           socketData.m_currentSocket.Shutdown(SocketShutdown.Both);
                           socketData.m_currentSocket.Close();
                           socketData.m_currentSocket.Disconnect(false);
                     
    
                           socketData = null;
                           socketData.m_currentSocket = null;
                           socketData.dataBuffer = null;
                        
                         GC.Collect();
        
                            return;
                       }
               
                       else
                        {
                          
                            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 (szData != null && szData != " " && szData != "" && szData != "\n\r\n" && szData != "\r\n")
                            {
    
                                Console.WriteLine(szData);
                             
                                try
                                {
                                    MSMQ msmq = new MSMQ();
                                    msmq.InitializeQueue(GetQ());
                                    msmq.AddData(szData); // s
                                    msmq = null;
                                }
                                catch (Exception ex1)
                                {
                                    // Logger.Log("Send failure: " + ex1.Message);
                                    writer.WriteToLog("Send failure: " + ex1.Message);
                                }
                                  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) 
                        {
                            string msg = "Client " + socketData.m_clientNumber + " Disconnected" + "\n";
                            AppendToRichEditControl(msg);
    
                           collected
                            m_workerSocketList[socketData.m_clientNumber - 1] = null;
                        }
                        else
                        {
                            writer.WriteToLog(se.Message);
                        }
                    }
                }
               
                void CloseSockets()
                {
                    if (m_mainSocket != null)
                    {
                       
                        m_mainSocket.Close();
                        m_mainSocket = null;
                      
                       return;
                   }
                    
                       public void Dispose() { }
                }
        }
    Last edited by Meetee; Oct 3 '12, 10:02 AM. Reason: code tags added
Working...