473,378 Members | 1,544 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

Async Socket Server exe memory increases by 10 percent per day

1
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

Expand|Select|Wrap|Line Numbers
  1.             void StartListen()
  2.             {
  3.  
  4.                                try
  5.                 {
  6.                     // Check the port value
  7.  
  8.                     string portStr = 9999;
  9.  
  10.                     try
  11.                     {
  12.                         // NOTE: DNS lookups are nice and all but quite time consuming.
  13.                         strHostName = Dns.GetHostName();
  14.                         IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
  15.                         aryLocalAddr = ipEntry.AddressList;
  16.                     }
  17.                     catch (Exception ex)
  18.                     {
  19.                         Console.WriteLine("Error trying to get local address {0} ", ex.Message);
  20.                     }
  21.  
  22.                     // Verify we got an IP address. Tell the user if we did
  23.                     if (aryLocalAddr == null || aryLocalAddr.Length < 1)
  24.                     {
  25.                         Console.WriteLine("Unable to get local address");
  26.                         return;
  27.                     }
  28.                     // Create the listening socket...
  29.                     m_mainSocket = new Socket(AddressFamily.InterNetwork,
  30.                         SocketType.Stream,
  31.                         ProtocolType.Tcp);
  32.                     IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);
  33.                     // Bind to local IP Address...
  34.                     m_mainSocket.Bind(ipLocal);
  35.                     // Start listening...
  36.                     m_mainSocket.Listen(500);
  37.                     // Create the call back for any client connections...
  38.                  m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
  39.  
  40.                 }
  41.                 catch (SocketException se)
  42.                 {
  43.                     writer.WriteToLog(se.Message);
  44.                 }
  45.  
  46.             }
  47.  
  48.             public bool isAlive()
  49.             {
  50.                 return m_mainSocket != null;
  51.             }
  52.  
  53.  
  54.  
  55.  
  56.             // This is the call back function, which will be invoked when a client is connected
  57.             public void OnClientConnect(IAsyncResult asyn)
  58.             {
  59.                 if (!isAlive()) 
  60.                 {
  61.                     return;
  62.                 }
  63.  
  64.                 try
  65.                 {
  66.                    Socket workerSocket = m_mainSocket.EndAccept(asyn);
  67.  
  68.                     WaitForData(workerSocket, m_clientCount);
  69.  
  70.                 m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
  71.                 }
  72.                 catch (ObjectDisposedException)
  73.                 {
  74.                     System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
  75.                 }
  76.                 catch (SocketException se)
  77.                 {
  78.                     writer.WriteToLog(se.Message);
  79.                 }
  80.  
  81.             }
  82.             public class SocketPacket
  83.             {
  84.                 // Constructor which takes a Socket and a client number
  85.                 public SocketPacket(System.Net.Sockets.Socket socket, int clientNumber)
  86.                 {
  87.                     m_currentSocket = socket;
  88.                     m_clientNumber = clientNumber;
  89.                 }
  90.                 public System.Net.Sockets.Socket m_currentSocket;
  91.                 public int m_clientNumber;
  92.                 // Buffer to store the data sent by the client
  93.                 public byte[] dataBuffer = new byte[2048];
  94.             }
  95.             // Start waiting for data from the client
  96.             public void WaitForData(System.Net.Sockets.Socket soc, int clientNumber)
  97.             {
  98.                 try
  99.                 {
  100.                     if (pfnWorkerCallBack == null)
  101.                     {
  102.                         // Specify the call back function which is to be 
  103.                         // invoked when there is any write activity by the 
  104.                         // connected client
  105.                         pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
  106.                     }
  107.                     SocketPacket theSocPkt = new SocketPacket(soc, clientNumber);
  108.  
  109.                     soc.BeginReceive(theSocPkt.dataBuffer, 0,
  110.                         theSocPkt.dataBuffer.Length,
  111.                         SocketFlags.None,
  112.                         pfnWorkerCallBack,
  113.                         theSocPkt);
  114.  
  115.  
  116.                 }
  117.                 catch (SocketException se)
  118.                 {
  119.                    writer.WriteToLog(se.Message);
  120.                 }
  121.            }
  122.  
  123.             // This the call back function which will be invoked when the socket
  124.             // detects any client writing of data on the stream
  125.             public void OnDataReceived(IAsyncResult asyn)
  126.             {
  127.                 SocketPacket socketData = (SocketPacket)asyn.AsyncState;
  128.                 int iRx = 0;
  129.                 try
  130.                 {
  131.                     try
  132.                     {
  133.                         SocketError errorCode;
  134.                         // int nBytesRec = socket.EndReceive(ar, out errorCode);
  135.                          iRx = socketData.m_currentSocket.EndReceive(asyn, out errorCode);
  136.                          if (errorCode != SocketError.Success)
  137.                          {
  138.                              iRx = 0;
  139.                              socketData.m_currentSocket.Shutdown(SocketShutdown.Both);
  140.                              socketData.m_currentSocket.Close();
  141.                              socketData.m_currentSocket.Disconnect(false);
  142.  
  143.                              socketData = null;
  144.                              socketData.m_currentSocket = null;
  145.                              socketData.dataBuffer = null;
  146.                              m_mainSocket.Shutdown(SocketShutdown.Both);
  147.                              m_mainSocket.Close();
  148.                              m_mainSocket.Disconnect(false);
  149.                              this.Dispose();
  150. m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
  151.  
  152.                          } 
  153.  
  154.                     }
  155.                     catch (SocketException se)
  156.                     {
  157.                         writer.WriteToLog("data received");
  158.  
  159.                         writer.WriteToLog(se.ErrorCode.ToString());
  160.                         writer.WriteToLog(se.Message);
  161.  
  162.                         socketData.m_currentSocket.Shutdown(SocketShutdown.Both);
  163.                         socketData.m_currentSocket.Close();
  164.  
  165.                         this.Dispose();
  166.  
  167.                     }
  168.  
  169.                    if (iRx < 0) {
  170.                        string Mesg = socketData.m_currentSocket.RemoteEndPoint + "  Disconnected" + "\n";
  171.                        this.textBoxMsg.Text = Mesg.ToString();
  172.  
  173.                        socketData.m_currentSocket.Shutdown(SocketShutdown.Both);
  174.                        socketData.m_currentSocket.Close();
  175.                        socketData.m_currentSocket.Disconnect(false);
  176.  
  177.  
  178.                        socketData = null;
  179.                        socketData.m_currentSocket = null;
  180.                        socketData.dataBuffer = null;
  181.  
  182.                      GC.Collect();
  183.  
  184.                         return;
  185.                    }
  186.  
  187.                    else
  188.                     {
  189.  
  190.                         char[] chars = new char[iRx + 1];
  191.                         // Extract the characters as a buffer
  192.                         System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
  193.                         int charLen = d.GetChars(socketData.dataBuffer,
  194.                         0, iRx, chars, 0);
  195.  
  196.                         System.String szData = new System.String(chars);
  197.  
  198.                         szData = szData.TrimEnd('\0');
  199.                         if (szData != null && szData != " " && szData != "" && szData != "\n\r\n" && szData != "\r\n")
  200.                         {
  201.  
  202.                             Console.WriteLine(szData);
  203.  
  204.                             try
  205.                             {
  206.                                 MSMQ msmq = new MSMQ();
  207.                                 msmq.InitializeQueue(GetQ());
  208.                                 msmq.AddData(szData); // s
  209.                                 msmq = null;
  210.                             }
  211.                             catch (Exception ex1)
  212.                             {
  213.                                 // Logger.Log("Send failure: " + ex1.Message);
  214.                                 writer.WriteToLog("Send failure: " + ex1.Message);
  215.                             }
  216.                               WaitForData(socketData.m_currentSocket, socketData.m_clientNumber);
  217.  
  218.                         }
  219.                     }
  220.                 }
  221.  
  222.                 catch (ObjectDisposedException)
  223.                 {
  224.                     System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
  225.                 }
  226.                 catch (SocketException se)
  227.                 {
  228.                     if (se.ErrorCode == 10054) 
  229.                     {
  230.                         string msg = "Client " + socketData.m_clientNumber + " Disconnected" + "\n";
  231.                         AppendToRichEditControl(msg);
  232.  
  233.                        collected
  234.                         m_workerSocketList[socketData.m_clientNumber - 1] = null;
  235.                     }
  236.                     else
  237.                     {
  238.                         writer.WriteToLog(se.Message);
  239.                     }
  240.                 }
  241.             }
  242.  
  243.             void CloseSockets()
  244.             {
  245.                 if (m_mainSocket != null)
  246.                 {
  247.  
  248.                     m_mainSocket.Close();
  249.                     m_mainSocket = null;
  250.  
  251.                    return;
  252.                }
  253.  
  254.                    public void Dispose() { }
  255.             }
  256.     }
  257.  
Oct 3 '12 #1
0 1770

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: Pete Davis | last post by:
I've written an async socket server app and I'm having an issue with the EndReceive() call. My begin receive call is: sockState.RemoteSocket.BeginReceive(sockState.ReceiveBuffer, 0,...
0
by: Pete Davis | last post by:
I'm trying to do async socket IO in a socket server in C# and I'm having trouble on the receive side of things. I've tried variations of the code below and I just can't seem to get it to work. I...
4
by: zbcong | last post by:
Hello: I write a multithread c# socket server,it is a winform application,there is a richtextbox control and button,when the button is click,the server begin to listen the socket port,waiting for a...
2
by: zhebincong | last post by:
Hello: I write a multithread c# socket server,it is a winform application,there is a richtextbox control and button,when the button is click,the server begin to listen the socket port,waiting...
7
by: Colin | last post by:
I'm writing a little console socket server but I'm having some difficulty. Can I ask your advice - where is the best place to get some help on that topic? It would be nice if some people who knew...
4
by: Macca | last post by:
I am writing an application that uses asynchronous sockets to get data over ethernet from embedded devices, up to 30 concurrent devices.(These devices are written in C). My application...
0
by: Macca | last post by:
Hi, My app has an asynchronous socket server to receive and transmit data over ethernet connections coming in through a switch. My App will handle concurrent data for possibly 20+ embedded C...
0
by: Macca | last post by:
Hi, I am writing an asychronous socket server to handle 20+ simulataneous connections. I have used the example in MSDN as a base. The code is shown at end of question. Each connection has a...
4
by: Engineerik | last post by:
I am trying to create a socket server which will listen for connections from multiple clients and call subroutines in a Fortran DLL and pass the results back to the client. The asynchronous socket...
0
by: Ikado | last post by:
I have an async. tcp server, I want to restart it in some periods. but there is a problem I am closing all sockets, Initializing new IPEndPoint and binding it, I am creating a new listening...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.