423,850 Members | 1,555 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 423,850 IT Pros & Developers. It's quick & easy.

C# How To Increase the TCP SocKet Clients ( Current 60 Clients) on Socket

P: 10
I have designed a socket Server and developed asynchronous server . It is working fine with 60 Clients which are connecting to ths Server running at Machine (2 GB RAM and OS is Windows 2003 Server)having IP which is Mapped with static IP and Port in firewall .

The Programme is working fine with 60 clients and rate if incoing data on the server is 5 -6 string of 1024 byte size are being saved in DataBase.

When i try to connect 61th client to the same server then it stops functioning. does not recieve Data and do accept new clients. And existing clients start gettting disconnected.

Pls note i am using BeginConnect and EndConnect function of C#. and using GPRS Connection at the Client Side. and LEased Line of 2 MEG on server Side.

For rceieving the Data Once the Client is Connected i use WaitforData function and OnRecieveData function in Asynchronous manner to recieved the Data on Socket Server.

Kindly suggest me how i can increase the number more than 60 Clients on Socket Server
Dec 14 '07 #1
Share this Question
Share on Google+
4 Replies


P: 38
http://www.csharphelp.com/archives3/archive486.html
I have designed a socket Server and developed asynchronous server . It is working fine with 60 Clients which are connecting to ths Server running at Machine (2 GB RAM and OS is Windows 2003 Server)having IP which is Mapped with static IP and Port in firewall .

The Programme is working fine with 60 clients and rate if incoing data on the server is 5 -6 string of 1024 byte size are being saved in DataBase.

When i try to connect 61th client to the same server then it stops functioning. does not recieve Data and do accept new clients. And existing clients start gettting disconnected.

Pls note i am using BeginConnect and EndConnect function of C#. and using GPRS Connection at the Client Side. and LEased Line of 2 MEG on server Side.

For rceieving the Data Once the Client is Connected i use WaitforData function and OnRecieveData function in Asynchronous manner to recieved the Data on Socket Server.

Kindly suggest me how i can increase the number more than 60 Clients on Socket Server

I found this researching your question not sure if it will help but this seems to set the sockets I found it at http://www.csharphelp.com/archives3/archive486.html

Expand|Select|Wrap|Line Numbers
  1. public Server(int port, string title, string attr)
  2.   {
  3.     this.portNumber = port;
  4.     this.title = title;
  5.     this.maxSockets =10000;
  6.     connectedSocks = new ArrayList(this.maxSockets);
  7.   }
  8.  
  9.  
  10. /// 
  11. /// Description: Start the threads to listen to the port and process
  12. /// messages.
  13. /// 
  14.  
a lot of other code was included maybe you can get an idea from there
hope it helps
Dec 14 '07 #2

P: 10
[HTML]I have already done this and initialized an array of 20000 for the clients.
Below written is the Code fort his which i am using
Expand|Select|Wrap|Line Numbers
  1.  private Socket[] m_workerSocket = new Socket[20000];
  2.  
  3. //Start Listen Here On Button click
  4. void ButtonStartListenClick(object sender, System.EventArgs e)
  5.         {
  6.  
  7.             OPenDataBaseConnectionIfClosed();
  8.  
  9.             try
  10.             {
  11.                 // Check the port value
  12.                 if (textBoxPort.Text == "")
  13.                 {
  14.                     MessageBox.Show("Please enter a Port Number");
  15.                     return;
  16.                 }
  17.                 string portStr = textBoxPort.Text;
  18.                 int port = System.Convert.ToInt32(portStr);
  19.                 // Create the listening socket...
  20.               /*  m_mainSocket = new Socket(AddressFamily.InterNetwork,
  21.                                           SocketType.Stream,
  22.                                           ProtocolType.Tcp);
  23.                */
  24.                 IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);
  25.                 // Bind to local IP Address...
  26.                 //MessageBox.Show("iplocal00" + ipLocal);
  27.                // m_mainSocket.Bind(ipLocal);
  28.  
  29.                 // Start listening...
  30.                 m_mainSocket.Listen(100000);
  31.                 //MessageBox.Show("iplocal 01" );
  32.                 // Create the call back for any client connections...
  33.                 m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
  34.                 //MessageBox.Show("iplocal 02");
  35.  
  36.                 //UpdateControls(true);
  37.                 //MessageBox.Show("iplocal 03");
  38.                 //      lblIPAddress.Text = m_mainSocket.RemoteEndPoint.ToString();
  39.                 //                MessageBox.Show("IP Number : " + m_mainSocket.RemoteEndPoint);    
  40.                 //  lblIPAddress = m_mainSocket.RemoteEndPoint;
  41.  
  42.             }
  43.             catch (SocketException se)
  44.             {
  45.                 lblIPAddress.Text = "6 : Connection Closed";
  46.  
  47.                 WriteTOTextFile("1:" + se.NativeErrorCode + " : " + se.Message + System.DateTime.Now);
  48.             }
  49.  
  50.         }
  51.  
  52. // This is the call back function, which will be invoked when a client is connected
  53. public void OnClientConnect(IAsyncResult asyn)
  54.         {
  55.             try
  56.             {
  57.                 // Here we complete/end the BeginAccept() asynchronous call
  58.                 // by calling EndAccept() - which returns the reference to
  59.                 // a new Socket object
  60.                 //m_mainSocket.
  61.  
  62.                 m_workerSocket[m_clientCount] = m_mainSocket.EndAccept(asyn);
  63.  
  64.                 // Let the worker Socket do the further processing for the 
  65.                 // just connected client
  66.  
  67.  
  68.  
  69.                 WaitForData(m_workerSocket[m_clientCount]);
  70.  
  71.                 // Now increment the client count
  72.                 ++m_clientCount;
  73.                 ++SocketNo;
  74.                 // Display this client connection as a status message on the GUI    
  75.                 //String str = String.Format("Client # {0} connected", m_clientCount);
  76.                 String str = String.Format("Client # {0} connected", SocketNo);
  77.                 textBoxMsg.Text = str;
  78.                 SocketNo = m_clientCount;
  79.               //  m_workerSocket[m_clientCount].Ttl = 500;
  80.                 // lblIPAddress.Text;
  81.                 //  MessageBox.Show(" : " + m_clientCount +  " : ");
  82.                 String ipconnected = m_workerSocket[m_clientCount].RemoteEndPoint.ToString();
  83.                  hstIPDev.Add(ipconnected, "0");
  84.                  lblIPAddress.Text = ":: " + ipconnected;
  85.                  lbl_dev_count.Text = hstIPDev.Count.ToString();
  86.                 // Since the main Socket is now free, it can go back and wait for
  87.                 // other clients who are attempting to connect
  88.  
  89.                 m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
  90.  
  91.  
  92.             }
  93.  
  94.             catch (ObjectDisposedException e )
  95.             {
  96.                 //lblIPAddress.Text = "4 : Connection Closed";
  97.                 System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
  98.                 WriteTOTextFile("2 " +  e.Message + " : OnClientConnection: Socket has been closed : " + System.DateTime.Now);
  99.  
  100.                 textBoxMsg.Text = String.Format("Client # {0} connected",m_clientCount);
  101.  
  102.  
  103.  
  104.             }
  105.             catch (SocketException se)
  106.             {
  107.  
  108.                 //MessageBox.Show("22" + " ErrorCode " + se.ErrorCode + " : " +se.Message);
  109.                 WriteTOTextFile("3: " + se.NativeErrorCode + " : " + se.Message + System.DateTime.Now);
  110.                 StartListenClick();
  111.                 //m_mainSocket.Close();
  112.                 //StartListenClick();
  113.  
  114.             }
  115.             catch (Exception se)
  116.             {
  117.  
  118.                 //MessageBox.Show("22" + " ErrorCode " + se.ErrorCode + " : " + se.Message);
  119.                 WriteTOTextFile("33: "  + " : " + se.Message + System.DateTime.Now);
  120.                 StartListenClick();
  121.  
  122.             }
  123.  
  124.  
  125.  
  126.         }
  127.  
  128.  
  129. Actually i listen the client requst on one IP wth Port to listen . When Asychronous call END then i create new Socket Object nad put that socket object in waitstate  in the following function 
  130. // Start waiting for data from the client
  131.         public void WaitForData(System.Net.Sockets.Socket soc)
  132.         {
  133.  
  134.  
  135.             try
  136.             {
  137.                 if  ( pfnWorkerCallBack == null ){        
  138.                     // Specify the call back function which is to be 
  139.                     // invoked when there is any write activity by the 
  140.                     // connected client
  141.                     pfnWorkerCallBack = new AsyncCallback (OnDataReceived);
  142.                 }
  143.                 SocketPacket theSocPkt = new SocketPacket ();
  144.                 theSocPkt.m_currentSocket     = soc;
  145.  
  146.                 // Start receiving any data written by the connected client
  147.                 // asynchronously
  148.                 soc .BeginReceive (theSocPkt.dataBuffer, 0, 
  149.                                    theSocPkt.dataBuffer.Length,
  150.                                    SocketFlags.None,
  151.                                    pfnWorkerCallBack,
  152.                                    theSocPkt);
  153.               //  MessageBox.Show("inside Wait 02");
  154.  
  155.                 if (soc.RemoteEndPoint != null)
  156.                 {
  157.                     lblIPAddress.Text= " Recent ip connected : " + soc.RemoteEndPoint.ToString();
  158.                     CurrentIP = soc.RemoteEndPoint.ToString();
  159.                     //lstBoxClientList.Items.Add (soc.RemoteEndPoint.ToString());
  160.  
  161.  
  162.                 }
  163.                 //MessageBox.Show("inside Wait 03");
  164.             }
  165.             catch(SocketException se)
  166.             {
  167.                //MessageBox.Show ( "2:" + se.ErrorCode + " : " + se.Message );
  168.                 WriteTOTextFile("4: " + se.NativeErrorCode + " : " + se.Message + System.DateTime.Now);
  169.                 int ipIndexinListBox;
  170.                 ipIndexinListBox = FindAllOfMyString(CurrentIP);
  171.                 if (ipIndexinListBox >= 0)
  172.                 {
  173.  
  174.                  lstBoxClientList.Items.RemoveAt(ipIndexinListBox);
  175.                 }
  176.                 soc.Disconnect(true);
  177.                 ////.......
  178.                 //m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
  179.                  ////.....
  180.                 //textBoxMsg.Text = String.Format("Client # {0} connected", SocketNo);
  181.  
  182.             }
  183.  
  184.         }
  185. And when Data arrives on the main Socket from the Client the On recieve asynchrous function     to read the Data is being used in following function
  186.  
  187.   public  void OnDataReceived(IAsyncResult asyn)
  188.         {
  189.  
  190.  
  191.             try
  192.             {
  193.                 SocketPacket socketData = (SocketPacket)asyn.AsyncState;
  194.  
  195.                 int iRx = 0;
  196.                 // Complete the BeginReceive() asynchronous call by EndReceive() method
  197.                 // which will return the number of characters written to the stream 
  198.                 // by the client
  199.                 iRx = socketData.m_currentSocket.EndReceive(asyn);
  200.  
  201.                 char[] chars = new char[iRx + 1];
  202.                 System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
  203.                 String ipData=socketData.m_currentSocket.RemoteEndPoint.ToString();
  204.                 CurrentIP = ipData;
  205.                 int charLen = d.GetChars(socketData.dataBuffer,
  206.                                          0, iRx, chars, 0);
  207.  
  208.                 System.String szData = new System.String(chars);
  209.                 szData = szData.Trim();
  210.  
  211.  
  212.                 long intvalOfChar;//, minA,mina,maxZ,maxz,min0,max9; // Determine the Ascii Value
  213.                 char c;
  214.  
  215.  
  216.                 c = Convert.ToChar(szData.Substring(0, 1));
  217.                 intvalOfChar = (int)c;
  218.                // richTextBoxAllData.AppendText(szData);
  219.  
  220.  
  221.                 // IF $ Appears more than one than the following if block stops
  222.                 //the add Enter character in the  string comming from Client()Device ///
  223.                 if ((richTextBoxReceivedMsg.Text.LastIndexOf('$') == 0 && c == '$') || (richTextBoxReceivedMsg.Text.LastIndexOf('$') > 0 && c == '$'))
  224.                 {
  225.                     richTextBoxReceivedMsg.Text = "";
  226.                     //richTextBoxSendMsg.AppendText("\r");
  227.                     c = (char)('\r');
  228.                 }
  229.                 ////////////////////////////////////////////////////////////////
  230.  
  231.                 if (c != (char)1 && c != (char)('*') )
  232.                 {
  233.  
  234.                     try
  235.                     {
  236.                         if ((szData.LastIndexOf('$') == 0 || richTextBoxReceivedMsg.Text.Trim().LastIndexOf('$') == 0))
  237.                         {
  238.  
  239.                             richTextBoxReceivedMsg.AppendText(szData);
  240.                             //richTextBoxSendMsg.AppendText(szData);
  241.  
  242.                             str = richTextBoxReceivedMsg.Text;
  243.                             String[] values3 = str.Split(',');
  244.  
  245.                             if (richTextBoxReceivedMsg.Text.LastIndexOf('&') > 0 && str.IndexOf(',') != -1 )
  246.                             {
  247.  
  248.                                 // Get Cutrrent Pos
  249.                                 if (richTextBoxReceivedMsg.Text.IndexOf("CurrentPos") != -1 && values3.Length == 3)
  250.                                 {
  251.                                   //  richTextBoxSendMsg.AppendText("\r");
  252.                                     String[] CurrentPOSStr;
  253.                                     String IPofDevice, DeviceCode, DevName;
  254.                                     CurrentPOSStr = str.Split(',');
  255.  
  256.                                    // DeviceCode = CurrentPOSStr[1];
  257.                                    // DevName = FindDeviceNamefortheDeviceCode(DeviceCode);
  258.                                     DevName = CurrentPOSStr[1];
  259.                                     DevName1 = DevName; // Parameter for  concatng IP            
  260.  
  261.                                     //IPofDevice = FindIPoftheDevName(DevName);
  262.                                     IPofDevice = FindIPFromHashTable(DevName);
  263.  
  264.  
  265.                                     if (IPofDevice != "")
  266.                                     {
  267.                                         SendSingleMessage("$ActGetPos,1203,0000&", IPofDevice);
  268.                                         richTextBoxPollingList.AppendText(DevName + "," + IPofDevice + "," + System.DateTime.Now + "\n");
  269.                                         lblLastMessageSent.Text = DevName + "," + IPofDevice + " " + System.DateTime.Now;
  270.                                     }
  271.                                     else 
  272.                                     {
  273.                                         richTextBoxPollingList.AppendText("Message not sent for polling because No IP found for "+DevName + "," + IPofDevice + "," + System.DateTime.Now + "\n");
  274.                                     }
  275.                                     str = ""; // Clearing the String
  276.                                     szData = "";
  277.                                     richTextBoxReceivedMsg.Clear();
  278.  
  279.                                 }
  280.  
  281.  
  282.                                 //Get Unit ID
  283.  
  284.  
  285.                                 if (richTextBoxReceivedMsg.Text.IndexOf("GetUnit") != -1 && values3.Length==3 )
  286.                                 {
  287.                                     String[] Str;
  288.                                     String IPofDevice, DeviceCode, DevName;
  289.                                     //Str = str.Split(',');
  290.                                     //DeviceCode = Str[1];
  291.                                     //DevName = FindDeviceNamefortheDeviceCode(DeviceCode);
  292.                                     //DevName1 = DevName; // Parameter for  concatng IP            
  293.                                     //IPofDevice = FindIPoftheDevName(DevName);
  294.                                     //richTextBoxPollingList.AppendText(DevName + "," + IPofDevice + "," + System.DateTime.Now + "\n");
  295.                                     //lblLastMessageSent.Text = DevName + "," + IPofDevice + " " + System.DateTime.Now;
  296.  
  297.                                     richTextBoxCommandOK.AppendText(str+"\n");
  298.                                     str = ""; // Clearing the String
  299.                                     szData = "";
  300.                                     richTextBoxReceivedMsg.Clear();
  301.  
  302.                                 }
  303.  
  304.                                 //GetGPRs Config
  305.  
  306.                                 if (richTextBoxReceivedMsg.Text.IndexOf("GetGPRSConfig") != -1 && values3.Length==7)
  307.                                 {
  308.                                     String[] Str;
  309.                                     String IPofDevice, DeviceCode, DevName;
  310.                                     //Str = str.Split(',');
  311.                                     //DeviceCode = Str[1];
  312.                                     //DevName = FindDeviceNamefortheDeviceCode(DeviceCode);
  313.                                     //DevName1 = DevName; // Parameter for  concatng IP            
  314.                                     //IPofDevice = FindIPoftheDevName(DevName);
  315.                                     //richTextBoxPollingList.AppendText(DevName + "," + IPofDevice + "," + System.DateTime.Now + "\n");
  316.                                     //lblLastMessageSent.Text = DevName + "," + IPofDevice + " " + System.DateTime.Now;
  317.  
  318.                                     richTextBoxCommandOK.AppendText(str + "\n");
  319.                                     str = ""; // Clearing the String
  320.                                     szData = "";
  321.                                     richTextBoxReceivedMsg.Clear();
  322.  
  323.                                 }
  324.                                 // Get TimeStamp
  325.                                 if (richTextBoxReceivedMsg.Text.IndexOf("GetTimeStamp") != -1 && values3.Length==3)
  326.                                 {
  327.                                     String[] Str;
  328.                                     String IPofDevice, DeviceCode, DevName;
  329.                                     //Str = str.Split(',');
  330.                                     //DeviceCode = Str[1];
  331.                                     //DevName = FindDeviceNamefortheDeviceCode(DeviceCode);
  332.                                     //DevName1 = DevName; // Parameter for  concatng IP            
  333.                                     //IPofDevice = FindIPoftheDevName(DevName);
  334.                                     //richTextBoxPollingList.AppendText(DevName + "," + IPofDevice + "," + System.DateTime.Now + "\n");
  335.                                     //lblLastMessageSent.Text = DevName + "," + IPofDevice + " " + System.DateTime.Now;
  336.  
  337.                                     richTextBoxCommandOK.AppendText(str + "\n");
  338.                                     str = ""; // Clearing the String
  339.                                     szData = "";
  340.                                     richTextBoxReceivedMsg.Clear();
  341.  
  342.                                 }
  343.  
  344.  
  345.                                 if (richTextBoxReceivedMsg.Text.IndexOf("logGetPos") != -1 && str.IndexOf(',') != -1 && values3.Length<=18)
  346.                                 {
  347.                                     richTextBoxCommandOK.AppendText(str+"\n");
  348.                                    // richTextBoxSendMsg.AppendText(" from IP " + CurrentIP + "\r\n");
  349.                                     String[] LogGetPOSStringArray;
  350.                                     LogGetPOSStringArray = str.Split(',');
  351.  
  352.                                     if (LogGetPOSStringArray.Length == 18)
  353.                                     {
  354.                                         SaveNewDataToDataBase(str);
  355.                                         UpdatePollingDetail(LogGetPOSStringArray[1]);
  356.                                     }
  357.                                     else
  358.                                     {
  359.                                         WriteTOTextFile("logGetPos String Less than 17 words: " + str + " "+ System.DateTime.Now);
  360.                                     }
  361.  
  362.  
  363.                                     str = ""; // Clearing the String
  364.                                     szData = "";
  365.                                     richTextBoxReceivedMsg.Clear();
  366.  
  367.                                     //SavetoDataBase.....
  368.                                 }
  369.  
  370.  
  371.                             }
  372.  
  373.                         }
  374.                     }
  375.                     catch (Exception e)
  376.                     {
  377.                         int ipIndex;
  378.                         //m_workerSocket[m_clientCount].Disconnect(true);
  379.  
  380.                         WriteTOTextFile("5: " + e.Message + System.DateTime.Now);
  381.                        //--SocketNo;
  382.                        // textBoxMsg.Text = "Client # " + SocketNo +" connected";
  383.                         ////////ipIndex = FindAllOfMyString(CurrentIP);
  384.                         ////////if (ipIndex >= 0)
  385.                         ////////{
  386.                         ////////    lstBoxClientList.Items.RemoveAt(ipIndex);
  387.                         ////////}
  388.                     }
  389.                  }
  390.  
  391.                  if (str.IndexOf('&') != -1 && str.IndexOf(',') != -1)
  392.                 {
  393.                     String[] values2 = str.Split(',');
  394.  
  395.  
  396.                     /////////////// Display  the IP in rich text box  from which the command Ok received
  397.                     if ((str.IndexOf("OK", 0) > 0 || str.IndexOf("Pwd", 0) > 0 || str.IndexOf("Cmd", 0)>0 || str.IndexOf("Param", 0)>0) && values2.Length >=3)
  398.                     {
  399.  
  400.                         richTextBoxCommandOK.AppendText("Recieved : " + str + " from " + CurrentIP + "\n");
  401.                         //richTextBoxSendMsg.AppendText("Recieved : " + str + " from  " + CurrentIP + "\n");
  402.  
  403.                         str = "";
  404.                         szData = "";
  405.                         richTextBoxReceivedMsg.Clear();
  406.  
  407.  
  408.                     }
  409.                     ////////////
  410.  
  411.                     if(  (str.IndexOf('$') != -1) && ((values2.Length == 15) || (values2.Length == 17) || (values2.Length == 18)) && (str.IndexOf(',') != -1))
  412.                      {
  413.                         String existingIPAndDevName;
  414.                         int indexofExistingIPAndDevName;
  415.                         lock (hstIPDev)
  416.                         {
  417.                            // hstIPDev.Remove(values2[1]);
  418.                            // hstIPDev.Add(values2[1],ipData);
  419.                             hstIPDev.Remove(ipData);
  420.                             hstIPDev.Add(ipData,values2[1]);
  421.                         }
  422.                        // MessageBox.Show(str);
  423.                       //  existingIPAndDevName = CurrentIP + "," + values2[1];
  424.                         existingIPAndDevName = "," + values2[1];
  425.  
  426.                         //////////////indexofExistingIPAndDevName = FindAllOfMyString(existingIPAndDevName);
  427.  
  428.  
  429.                         //////////////if (indexofExistingIPAndDevName < 0)
  430.                         //////////////{
  431.                         //////////////    lstBoxClientList.Items.Add(CurrentIP + "," + values2[1]); // Adding the IP with Device Code in the ListClient
  432.                         //////////////    // lstBoxClientList.Items.Add(CurrentIP + "," + values2[1]); // Adding the IP with Device Code in the ListClient
  433.                         //////////////}
  434.                         //////////////else
  435.                         //////////////{
  436.                         //////////////    lstBoxClientList.Items.RemoveAt(indexofExistingIPAndDevName);//,CurrentIP + "," + values2[1]); // Adding the IP with Device Code in the ListClient
  437.                         //////////////    lstBoxClientList.Items.Add(CurrentIP + "," + values2[1]); // Adding the IP with Device Code in the ListClient
  438.                         //////////////}
  439.                         richTextBoxReceivedMsg.Clear();
  440.  
  441.  
  442.                         if (((values2[1].Equals("0705280114")) || values2[3].Equals("0705280114") && str.IndexOf(',') != -1) && (values2.Length == 15 || values2.Length == 17))  //  Device code 8
  443.                         {
  444.  
  445.                             str = str.Trim();
  446.  
  447.                             SaveDataToDataBase(str);
  448.  
  449.                             szData = null;
  450.  
  451.                             richTextBoxReceivedMsg.Clear();
  452.                         }
  453.  
  454.                         //else
  455.  
  456.                         if (((!values2[1].Equals("0705280114")) || !values2[3].Equals("0705280114") && str.IndexOf(',') != -1) && values2.Length == 18)  //  Devices Other Than Device code 8
  457.                         {
  458.  
  459.                             if (str.IndexOf(',') != -1)
  460.                             {
  461.                                 SaveNewDataToDataBase(str);
  462.                                 szData = null;
  463.                             }
  464.                         }
  465.  
  466.  
  467.                         txtLastMessageSaved.Text = str;
  468.                         str = "";
  469.  
  470.  
  471.  
  472.                         richTextBoxReceivedMsg.Clear();
  473.  
  474.                         values2 = null;
  475.                     }
  476.  
  477.                 }
  478.                 // Continue the waiting for data on the Socket
  479.  
  480.                 WaitForData(socketData.m_currentSocket);
  481.                 //////lbl_dev_count.Text = lstBoxClientList.Items.Count.ToString();
  482.                 lbl_dev_count.Text = hstIPDev.Count.ToString();
  483.                 //UpdateListofIP(CurrentIP,DevName1);
  484.             }
  485.             catch (ObjectDisposedException )
  486.             {
  487.                 SocketPacket socketData02 = (SocketPacket)asyn.AsyncState;
  488.                 String ipData = socketData02.m_currentSocket.RemoteEndPoint.ToString();
  489.                 hstIPDev.Remove(ipData);
  490.  
  491.                 System.Diagnostics.Debugger.Log(0,"1","\nOnDataReceived: Socket has been closed\n");
  492.                 WriteTOTextFile("5: OnDataReceived: Socket has been closed "+ System.DateTime.Now);
  493.  
  494.                 int indexofIP;
  495.                 ////////indexofIP = FindAllOfMyString(CurrentIP);
  496.                 ////////if (indexofIP != -1)
  497.                 ////////{
  498.                 ////////    lstBoxClientList.Items.RemoveAt(indexofIP);
  499.                 ////////}
  500.                 // m_workerSocket[m_clientCount].Disconnect(true);
  501.                // --SocketNo;
  502.                // textBoxMsg.Text = "Client # " + SocketNo + " connected";
  503.                 //WaitForData(socketData02.m_currentSocket);
  504.                 ////////////lbl_dev_count.Text = lstBoxClientList.Items.Count.ToString();
  505.                 lbl_dev_count.Text = hstIPDev.Count.ToString();
  506.             }
  507.             catch(SocketException se)
  508.             {
  509.  
  510.                 //Code To Close the Worker  Socket
  511.                 SocketPacket socketData01 = (SocketPacket)asyn.AsyncState;
  512.                 String ipData01;
  513.                 if (socketData01.m_currentSocket != null)
  514.                 {
  515.  
  516.                     ipData01 = socketData01.m_currentSocket.RemoteEndPoint.ToString();
  517.                     //RemoveIPFromHashTable(ip); 
  518.                     hstIPDev.Remove(ipData01);
  519.  
  520.                     WriteTOTextFile("8. Closing Worker Socket OrionIP:" + ipData01 + " Worker IP : " + socketData01.m_currentSocket.LocalEndPoint.ToString());
  521.                     socketData01.m_currentSocket.Close();
  522.                     socketData01.m_currentSocket = null;
  523.  
  524.  
  525.  
  526.                 }
  527.  
  528.                 if( se.ErrorCode ==10054)
  529.                 {
  530.                     //CurrentIP= m_workerSocket[m_clientCount].RemoteEndPoint.ToString();
  531.                    // m_workerSocket[m_clientCount].Disconnect(true);
  532.                     lblIPAddress.Text = lblIPAddress.Text + " Remotely Closed" +CurrentIP;
  533.                    // --SocketNo;
  534.                     //textBoxMsg.Text = "Client # " + SocketNo + " connected";
  535.                     richTextBoxAllData.AppendText("Here disconnected :"+  CurrentIP);
  536.                     WriteTOTextFile("6:" + " " + se.NativeErrorCode + " : " + se.Message + System.DateTime.Now);
  537.                     StartListenClick();
  538.                     ////int indexofIP;
  539.                     ////indexofIP = FindAllOfMyString(CurrentIP);
  540.                     ////if( indexofIP != -1)
  541.                     ////{
  542.                     ////    lstBoxClientList.Items.RemoveAt(indexofIP);
  543.                     ////}
  544.  
  545.  
  546.                     //int i;
  547.                     //i=lstBoxClientList.FindString("," + CurrentIP);
  548.                     //lstBoxClientList.Items.RemoveAt(i);
  549.                 }
  550.                 else
  551.                 {
  552.                     //MessageBox.Show ("4 : " + se.ErrorCode + ": " + se.Message );
  553.                     WriteTOTextFile("7: a" + se.ErrorCode + " : " + se.Message + System.DateTime.Now);
  554.                 }
  555.  
  556.                   //  WaitForData(socketData01.m_currentSocket);
  557.                 //lbl_dev_count.Text = lstBoxClientList.Items.Count.ToString();
  558.                 lbl_dev_count.Text = hstIPDev.Count.ToString();
  559.             }
  560. }
  561. And in this read function when socket Client gets disconnected  the byte length of data i recieve is zero and then i check for null ocket and then close the child socket which is not the main socket but one of the socket fin the array list.
  562.  
  563. Still waiting for solution 
  564. setiarakeshgps@hotmail.com
[/HTML][/PHP]
Dec 15 '07 #3

P: 10
[HTML]I have already done this and initialized an array of 20000 for the clients.Below written is the Code fort his which i am using
Expand|Select|Wrap|Line Numbers
  1.  private Socket[] m_workerSocket = new Socket[20000];
  2.  
  3. //Start Listen Here On Button click
  4. void ButtonStartListenClick(object sender, System.EventArgs e)
  5.         {
  6.  
  7.             OPenDataBaseConnectionIfClosed();
  8.  
  9.             try
  10.             {
  11.                 // Check the port value
  12.                 if (textBoxPort.Text == "")
  13.                 {
  14.                     MessageBox.Show("Please enter a Port Number");
  15.                     return;
  16.                 }
  17.                 string portStr = textBoxPort.Text;
  18.                 int port = System.Convert.ToInt32(portStr);
  19.                 // Create the listening socket...
  20.               /*  m_mainSocket = new Socket(AddressFamily.InterNetwork,
  21.                                           SocketType.Stream,
  22.                                           ProtocolType.Tcp);
  23.                */
  24.                 IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);
  25.                 // Bind to local IP Address...
  26.                 //MessageBox.Show("iplocal00" + ipLocal);
  27.                // m_mainSocket.Bind(ipLocal);
  28.  
  29.                 // Start listening...
  30.                 m_mainSocket.Listen(100000);
  31.                 //MessageBox.Show("iplocal 01" );
  32.                 // Create the call back for any client connections...
  33.                 m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
  34.                 //MessageBox.Show("iplocal 02");
  35.  
  36.                 //UpdateControls(true);
  37.                 //MessageBox.Show("iplocal 03");
  38.                 //      lblIPAddress.Text = m_mainSocket.RemoteEndPoint.ToString();
  39.                 //                MessageBox.Show("IP Number : " + m_mainSocket.RemoteEndPoint);    
  40.                 //  lblIPAddress = m_mainSocket.RemoteEndPoint;
  41.  
  42.             }
  43.             catch (SocketException se)
  44.             {
  45.                 lblIPAddress.Text = "6 : Connection Closed";
  46.  
  47.                 WriteTOTextFile("1:" + se.NativeErrorCode + " : " + se.Message + System.DateTime.Now);
  48.             }
  49.  
  50.         }
  51.  
  52. // This is the call back function, which will be invoked when a client is connected
  53. public void OnClientConnect(IAsyncResult asyn)
  54.         {
  55.             try
  56.             {
  57.                 // Here we complete/end the BeginAccept() asynchronous call
  58.                 // by calling EndAccept() - which returns the reference to
  59.                 // a new Socket object
  60.                 //m_mainSocket.
  61.  
  62.                 m_workerSocket[m_clientCount] = m_mainSocket.EndAccept(asyn);
  63.  
  64.                 // Let the worker Socket do the further processing for the 
  65.                 // just connected client
  66.  
  67.  
  68.  
  69.                 WaitForData(m_workerSocket[m_clientCount]);
  70.  
  71.                 // Now increment the client count
  72.                 ++m_clientCount;
  73.                 ++SocketNo;
  74.                 // Display this client connection as a status message on the GUI    
  75.                 //String str = String.Format("Client # {0} connected", m_clientCount);
  76.                 String str = String.Format("Client # {0} connected", SocketNo);
  77.                 textBoxMsg.Text = str;
  78.                 SocketNo = m_clientCount;
  79.               //  m_workerSocket[m_clientCount].Ttl = 500;
  80.                 // lblIPAddress.Text;
  81.                 //  MessageBox.Show(" : " + m_clientCount +  " : ");
  82.                 String ipconnected = m_workerSocket[m_clientCount].RemoteEndPoint.ToString();
  83.                  hstIPDev.Add(ipconnected, "0");
  84.                  lblIPAddress.Text = ":: " + ipconnected;
  85.                  lbl_dev_count.Text = hstIPDev.Count.ToString();
  86.                 // Since the main Socket is now free, it can go back and wait for
  87.                 // other clients who are attempting to connect
  88.  
  89.                 m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
  90.  
  91.  
  92.             }
  93.  
  94.             catch (ObjectDisposedException e )
  95.             {
  96.                 //lblIPAddress.Text = "4 : Connection Closed";
  97.                 System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
  98.                 WriteTOTextFile("2 " +  e.Message + " : OnClientConnection: Socket has been closed : " + System.DateTime.Now);
  99.  
  100.                 textBoxMsg.Text = String.Format("Client # {0} connected",m_clientCount);
  101.  
  102.  
  103.  
  104.             }
  105.             catch (SocketException se)
  106.             {
  107.  
  108.                 //MessageBox.Show("22" + " ErrorCode " + se.ErrorCode + " : " +se.Message);
  109.                 WriteTOTextFile("3: " + se.NativeErrorCode + " : " + se.Message + System.DateTime.Now);
  110.                 StartListenClick();
  111.                 //m_mainSocket.Close();
  112.                 //StartListenClick();
  113.  
  114.             }
  115.             catch (Exception se)
  116.             {
  117.  
  118.                 //MessageBox.Show("22" + " ErrorCode " + se.ErrorCode + " : " + se.Message);
  119.                 WriteTOTextFile("33: "  + " : " + se.Message + System.DateTime.Now);
  120.                 StartListenClick();
  121.  
  122.             }
  123.  
  124.  
  125.  
  126.         }
  127.  
  128.  
  129. Actually i listen the client requst on one IP wth Port to listen . When Asychronous call END then i create new Socket Object nad put that socket object in waitstate  in the following function 
  130. // Start waiting for data from the client
  131.         public void WaitForData(System.Net.Sockets.Socket soc)
  132.         {
  133.  
  134.  
  135.             try
  136.             {
  137.                 if  ( pfnWorkerCallBack == null ){        
  138.                     // Specify the call back function which is to be 
  139.                     // invoked when there is any write activity by the 
  140.                     // connected client
  141.                     pfnWorkerCallBack = new AsyncCallback (OnDataReceived);
  142.                 }
  143.                 SocketPacket theSocPkt = new SocketPacket ();
  144.                 theSocPkt.m_currentSocket     = soc;
  145.  
  146.                 // Start receiving any data written by the connected client
  147.                 // asynchronously
  148.                 soc .BeginReceive (theSocPkt.dataBuffer, 0, 
  149.                                    theSocPkt.dataBuffer.Length,
  150.                                    SocketFlags.None,
  151.                                    pfnWorkerCallBack,
  152.                                    theSocPkt);
  153.               //  MessageBox.Show("inside Wait 02");
  154.  
  155.                 if (soc.RemoteEndPoint != null)
  156.                 {
  157.                     lblIPAddress.Text= " Recent ip connected : " + soc.RemoteEndPoint.ToString();
  158.                     CurrentIP = soc.RemoteEndPoint.ToString();
  159.                     //lstBoxClientList.Items.Add (soc.RemoteEndPoint.ToString());
  160.  
  161.  
  162.                 }
  163.                 //MessageBox.Show("inside Wait 03");
  164.             }
  165.             catch(SocketException se)
  166.             {
  167.                //MessageBox.Show ( "2:" + se.ErrorCode + " : " + se.Message );
  168.                 WriteTOTextFile("4: " + se.NativeErrorCode + " : " + se.Message + System.DateTime.Now);
  169.                 int ipIndexinListBox;
  170.                 ipIndexinListBox = FindAllOfMyString(CurrentIP);
  171.                 if (ipIndexinListBox >= 0)
  172.                 {
  173.  
  174.                  lstBoxClientList.Items.RemoveAt(ipIndexinListBox);
  175.                 }
  176.                 soc.Disconnect(true);
  177.                 ////.......
  178.                 //m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
  179.                  ////.....
  180.                 //textBoxMsg.Text = String.Format("Client # {0} connected", SocketNo);
  181.  
  182.             }
  183.  
  184.         }
  185. And when Data arrives on the main Socket from the Client the On recieve asynchrous function     to read the Data is being used in following function
  186.  
  187.   public  void OnDataReceived(IAsyncResult asyn)
  188.         {
  189.  
  190.  
  191.             try
  192.             {
  193.                 SocketPacket socketData = (SocketPacket)asyn.AsyncState;
  194.  
  195.                 int iRx = 0;
  196.                 // Complete the BeginReceive() asynchronous call by EndReceive() method
  197.                 // which will return the number of characters written to the stream 
  198.                 // by the client
  199.                 iRx = socketData.m_currentSocket.EndReceive(asyn);
  200.  
  201.                 char[] chars = new char[iRx + 1];
  202.                 System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
  203.                 String ipData=socketData.m_currentSocket.RemoteEndPoint.ToString();
  204.                 CurrentIP = ipData;
  205.                 int charLen = d.GetChars(socketData.dataBuffer,
  206.                                          0, iRx, chars, 0);
  207.  
  208.                 System.String szData = new System.String(chars);
  209.                 szData = szData.Trim();
  210.  
  211.  
  212.                 long intvalOfChar;//, minA,mina,maxZ,maxz,min0,max9; // Determine the Ascii Value
  213.                 char c;
  214.  
  215.  
  216.                 c = Convert.ToChar(szData.Substring(0, 1));
  217.                 intvalOfChar = (int)c;
  218.                // richTextBoxAllData.AppendText(szData);
  219.  
  220.  
  221.                 // IF $ Appears more than one than the following if block stops
  222.                 //the add Enter character in the  string comming from Client()Device ///
  223.                 if ((richTextBoxReceivedMsg.Text.LastIndexOf('$') == 0 && c == '$') || (richTextBoxReceivedMsg.Text.LastIndexOf('$') > 0 && c == '$'))
  224.                 {
  225.                     richTextBoxReceivedMsg.Text = "";
  226.                     //richTextBoxSendMsg.AppendText("\r");
  227.                     c = (char)('\r');
  228.                 }
  229.                 ////////////////////////////////////////////////////////////////
  230.  
  231.                 if (c != (char)1 && c != (char)('*') )
  232.                 {
  233.  
  234.                     try
  235.                     {
  236.                         if ((szData.LastIndexOf('$') == 0 || richTextBoxReceivedMsg.Text.Trim().LastIndexOf('$') == 0))
  237.                         {
  238.  
  239.                             richTextBoxReceivedMsg.AppendText(szData);
  240.                             //richTextBoxSendMsg.AppendText(szData);
  241.  
  242.                             str = richTextBoxReceivedMsg.Text;
  243.                             String[] values3 = str.Split(',');
  244.  
  245.                             if (richTextBoxReceivedMsg.Text.LastIndexOf('&') > 0 && str.IndexOf(',') != -1 )
  246.                             {
  247.  
  248.                                 // Get Cutrrent Pos
  249.                                 if (richTextBoxReceivedMsg.Text.IndexOf("CurrentPos") != -1 && values3.Length == 3)
  250.                                 {
  251.                                   //  richTextBoxSendMsg.AppendText("\r");
  252.                                     String[] CurrentPOSStr;
  253.                                     String IPofDevice, DeviceCode, DevName;
  254.                                     CurrentPOSStr = str.Split(',');
  255.  
  256.                                    // DeviceCode = CurrentPOSStr[1];
  257.                                    // DevName = FindDeviceNamefortheDeviceCode(DeviceCode);
  258.                                     DevName = CurrentPOSStr[1];
  259.                                     DevName1 = DevName; // Parameter for  concatng IP            
  260.  
  261.                                     //IPofDevice = FindIPoftheDevName(DevName);
  262.                                     IPofDevice = FindIPFromHashTable(DevName);
  263.  
  264.  
  265.                                     if (IPofDevice != "")
  266.                                     {
  267.                                         SendSingleMessage("$ActGetPos,1203,0000&", IPofDevice);
  268.                                         richTextBoxPollingList.AppendText(DevName + "," + IPofDevice + "," + System.DateTime.Now + "\n");
  269.                                         lblLastMessageSent.Text = DevName + "," + IPofDevice + " " + System.DateTime.Now;
  270.                                     }
  271.                                     else 
  272.                                     {
  273.                                         richTextBoxPollingList.AppendText("Message not sent for polling because No IP found for "+DevName + "," + IPofDevice + "," + System.DateTime.Now + "\n");
  274.                                     }
  275.                                     str = ""; // Clearing the String
  276.                                     szData = "";
  277.                                     richTextBoxReceivedMsg.Clear();
  278.  
  279.                                 }
  280.  
  281.  
  282.                                 //Get Unit ID
  283.  
  284.  
  285.                                 if (richTextBoxReceivedMsg.Text.IndexOf("GetUnit") != -1 && values3.Length==3 )
  286.                                 {
  287.                                     String[] Str;
  288.                                     String IPofDevice, DeviceCode, DevName;
  289.                                     //Str = str.Split(',');
  290.                                     //DeviceCode = Str[1];
  291.                                     //DevName = FindDeviceNamefortheDeviceCode(DeviceCode);
  292.                                     //DevName1 = DevName; // Parameter for  concatng IP            
  293.                                     //IPofDevice = FindIPoftheDevName(DevName);
  294.                                     //richTextBoxPollingList.AppendText(DevName + "," + IPofDevice + "," + System.DateTime.Now + "\n");
  295.                                     //lblLastMessageSent.Text = DevName + "," + IPofDevice + " " + System.DateTime.Now;
  296.  
  297.                                     richTextBoxCommandOK.AppendText(str+"\n");
  298.                                     str = ""; // Clearing the String
  299.                                     szData = "";
  300.                                     richTextBoxReceivedMsg.Clear();
  301.  
  302.                                 }
  303.  
  304.                                 //GetGPRs Config
  305.  
  306.                                 if (richTextBoxReceivedMsg.Text.IndexOf("GetGPRSConfig") != -1 && values3.Length==7)
  307.                                 {
  308.                                     String[] Str;
  309.                                     String IPofDevice, DeviceCode, DevName;
  310.                                     //Str = str.Split(',');
  311.                                     //DeviceCode = Str[1];
  312.                                     //DevName = FindDeviceNamefortheDeviceCode(DeviceCode);
  313.                                     //DevName1 = DevName; // Parameter for  concatng IP            
  314.                                     //IPofDevice = FindIPoftheDevName(DevName);
  315.                                     //richTextBoxPollingList.AppendText(DevName + "," + IPofDevice + "," + System.DateTime.Now + "\n");
  316.                                     //lblLastMessageSent.Text = DevName + "," + IPofDevice + " " + System.DateTime.Now;
  317.  
  318.                                     richTextBoxCommandOK.AppendText(str + "\n");
  319.                                     str = ""; // Clearing the String
  320.                                     szData = "";
  321.                                     richTextBoxReceivedMsg.Clear();
  322.  
  323.                                 }
  324.                                 // Get TimeStamp
  325.                                 if (richTextBoxReceivedMsg.Text.IndexOf("GetTimeStamp") != -1 && values3.Length==3)
  326.                                 {
  327.                                     String[] Str;
  328.                                     String IPofDevice, DeviceCode, DevName;
  329.                                     //Str = str.Split(',');
  330.                                     //DeviceCode = Str[1];
  331.                                     //DevName = FindDeviceNamefortheDeviceCode(DeviceCode);
  332.                                     //DevName1 = DevName; // Parameter for  concatng IP            
  333.                                     //IPofDevice = FindIPoftheDevName(DevName);
  334.                                     //richTextBoxPollingList.AppendText(DevName + "," + IPofDevice + "," + System.DateTime.Now + "\n");
  335.                                     //lblLastMessageSent.Text = DevName + "," + IPofDevice + " " + System.DateTime.Now;
  336.  
  337.                                     richTextBoxCommandOK.AppendText(str + "\n");
  338.                                     str = ""; // Clearing the String
  339.                                     szData = "";
  340.                                     richTextBoxReceivedMsg.Clear();
  341.  
  342.                                 }
  343.  
  344.  
  345.                                 if (richTextBoxReceivedMsg.Text.IndexOf("logGetPos") != -1 && str.IndexOf(',') != -1 && values3.Length<=18)
  346.                                 {
  347.                                     richTextBoxCommandOK.AppendText(str+"\n");
  348.                                    // richTextBoxSendMsg.AppendText(" from IP " + CurrentIP + "\r\n");
  349.                                     String[] LogGetPOSStringArray;
  350.                                     LogGetPOSStringArray = str.Split(',');
  351.  
  352.                                     if (LogGetPOSStringArray.Length == 18)
  353.                                     {
  354.                                         SaveNewDataToDataBase(str);
  355.                                         UpdatePollingDetail(LogGetPOSStringArray[1]);
  356.                                     }
  357.                                     else
  358.                                     {
  359.                                         WriteTOTextFile("logGetPos String Less than 17 words: " + str + " "+ System.DateTime.Now);
  360.                                     }
  361.  
  362.  
  363.                                     str = ""; // Clearing the String
  364.                                     szData = "";
  365.                                     richTextBoxReceivedMsg.Clear();
  366.  
  367.                                     //SavetoDataBase.....
  368.                                 }
  369.  
  370.  
  371.                             }
  372.  
  373.                         }
  374.                     }
  375.                     catch (Exception e)
  376.                     {
  377.                         int ipIndex;
  378.                         //m_workerSocket[m_clientCount].Disconnect(true);
  379.  
  380.                         WriteTOTextFile("5: " + e.Message + System.DateTime.Now);
  381.                        //--SocketNo;
  382.                        // textBoxMsg.Text = "Client # " + SocketNo +" connected";
  383.                         ////////ipIndex = FindAllOfMyString(CurrentIP);
  384.                         ////////if (ipIndex >= 0)
  385.                         ////////{
  386.                         ////////    lstBoxClientList.Items.RemoveAt(ipIndex);
  387.                         ////////}
  388.                     }
  389.                  }
  390.  
  391.                  if (str.IndexOf('&') != -1 && str.IndexOf(',') != -1)
  392.                 {
  393.                     String[] values2 = str.Split(',');
  394.  
  395.  
  396.                     /////////////// Display  the IP in rich text box  from which the command Ok received
  397.                     if ((str.IndexOf("OK", 0) > 0 || str.IndexOf("Pwd", 0) > 0 || str.IndexOf("Cmd", 0)>0 || str.IndexOf("Param", 0)>0) && values2.Length >=3)
  398.                     {
  399.  
  400.                         richTextBoxCommandOK.AppendText("Recieved : " + str + " from " + CurrentIP + "\n");
  401.                         //richTextBoxSendMsg.AppendText("Recieved : " + str + " from  " + CurrentIP + "\n");
  402.  
  403.                         str = "";
  404.                         szData = "";
  405.                         richTextBoxReceivedMsg.Clear();
  406.  
  407.  
  408.                     }
  409.                     ////////////
  410.  
  411.                     if(  (str.IndexOf('$') != -1) && ((values2.Length == 15) || (values2.Length == 17) || (values2.Length == 18)) && (str.IndexOf(',') != -1))
  412.                      {
  413.                         String existingIPAndDevName;
  414.                         int indexofExistingIPAndDevName;
  415.                         lock (hstIPDev)
  416.                         {
  417.                            // hstIPDev.Remove(values2[1]);
  418.                            // hstIPDev.Add(values2[1],ipData);
  419.                             hstIPDev.Remove(ipData);
  420.                             hstIPDev.Add(ipData,values2[1]);
  421.                         }
  422.                        // MessageBox.Show(str);
  423.                       //  existingIPAndDevName = CurrentIP + "," + values2[1];
  424.                         existingIPAndDevName = "," + values2[1];
  425.  
  426.                         //////////////indexofExistingIPAndDevName = FindAllOfMyString(existingIPAndDevName);
  427.  
  428.  
  429.                         //////////////if (indexofExistingIPAndDevName < 0)
  430.                         //////////////{
  431.                         //////////////    lstBoxClientList.Items.Add(CurrentIP + "," + values2[1]); // Adding the IP with Device Code in the ListClient
  432.                         //////////////    // lstBoxClientList.Items.Add(CurrentIP + "," + values2[1]); // Adding the IP with Device Code in the ListClient
  433.                         //////////////}
  434.                         //////////////else
  435.                         //////////////{
  436.                         //////////////    lstBoxClientList.Items.RemoveAt(indexofExistingIPAndDevName);//,CurrentIP + "," + values2[1]); // Adding the IP with Device Code in the ListClient
  437.                         //////////////    lstBoxClientList.Items.Add(CurrentIP + "," + values2[1]); // Adding the IP with Device Code in the ListClient
  438.                         //////////////}
  439.                         richTextBoxReceivedMsg.Clear();
  440.  
  441.  
  442.                         if (((values2[1].Equals("0705280114")) || values2[3].Equals("0705280114") && str.IndexOf(',') != -1) && (values2.Length == 15 || values2.Length == 17))  //  Device code 8
  443.                         {
  444.  
  445.                             str = str.Trim();
  446.  
  447.                             SaveDataToDataBase(str);
  448.  
  449.                             szData = null;
  450.  
  451.                             richTextBoxReceivedMsg.Clear();
  452.                         }
  453.  
  454.                         //else
  455.  
  456.                         if (((!values2[1].Equals("0705280114")) || !values2[3].Equals("0705280114") && str.IndexOf(',') != -1) && values2.Length == 18)  //  Devices Other Than Device code 8
  457.                         {
  458.  
  459.                             if (str.IndexOf(',') != -1)
  460.                             {
  461.                                 SaveNewDataToDataBase(str);
  462.                                 szData = null;
  463.                             }
  464.                         }
  465.  
  466.  
  467.                         txtLastMessageSaved.Text = str;
  468.                         str = "";
  469.  
  470.  
  471.  
  472.                         richTextBoxReceivedMsg.Clear();
  473.  
  474.                         values2 = null;
  475.                     }
  476.  
  477.                 }
  478.                 // Continue the waiting for data on the Socket
  479.  
  480.                 WaitForData(socketData.m_currentSocket);
  481.                 //////lbl_dev_count.Text = lstBoxClientList.Items.Count.ToString();
  482.                 lbl_dev_count.Text = hstIPDev.Count.ToString();
  483.                 //UpdateListofIP(CurrentIP,DevName1);
  484.             }
  485.             catch (ObjectDisposedException )
  486.             {
  487.                 SocketPacket socketData02 = (SocketPacket)asyn.AsyncState;
  488.                 String ipData = socketData02.m_currentSocket.RemoteEndPoint.ToString();
  489.                 hstIPDev.Remove(ipData);
  490.  
  491.                 System.Diagnostics.Debugger.Log(0,"1","\nOnDataReceived: Socket has been closed\n");
  492.                 WriteTOTextFile("5: OnDataReceived: Socket has been closed "+ System.DateTime.Now);
  493.  
  494.                 int indexofIP;
  495.                 ////////indexofIP = FindAllOfMyString(CurrentIP);
  496.                 ////////if (indexofIP != -1)
  497.                 ////////{
  498.                 ////////    lstBoxClientList.Items.RemoveAt(indexofIP);
  499.                 ////////}
  500.                 // m_workerSocket[m_clientCount].Disconnect(true);
  501.                // --SocketNo;
  502.                // textBoxMsg.Text = "Client # " + SocketNo + " connected";
  503.                 //WaitForData(socketData02.m_currentSocket);
  504.                 ////////////lbl_dev_count.Text = lstBoxClientList.Items.Count.ToString();
  505.                 lbl_dev_count.Text = hstIPDev.Count.ToString();
  506.             }
  507.             catch(SocketException se)
  508.             {
  509.  
  510.                 //Code To Close the Worker  Socket
  511.                 SocketPacket socketData01 = (SocketPacket)asyn.AsyncState;
  512.                 String ipData01;
  513.                 if (socketData01.m_currentSocket != null)
  514.                 {
  515.  
  516.                     ipData01 = socketData01.m_currentSocket.RemoteEndPoint.ToString();
  517.                     //RemoveIPFromHashTable(ip); 
  518.                     hstIPDev.Remove(ipData01);
  519.  
  520.                     WriteTOTextFile("8. Closing Worker Socket OrionIP:" + ipData01 + " Worker IP : " + socketData01.m_currentSocket.LocalEndPoint.ToString());
  521.                     socketData01.m_currentSocket.Close();
  522.                     socketData01.m_currentSocket = null;
  523.  
  524.  
  525.  
  526.                 }
  527.  
  528.                 if( se.ErrorCode ==10054)
  529.                 {
  530.                     //CurrentIP= m_workerSocket[m_clientCount].RemoteEndPoint.ToString();
  531.                    // m_workerSocket[m_clientCount].Disconnect(true);
  532.                     lblIPAddress.Text = lblIPAddress.Text + " Remotely Closed" +CurrentIP;
  533.                    // --SocketNo;
  534.                     //textBoxMsg.Text = "Client # " + SocketNo + " connected";
  535.                     richTextBoxAllData.AppendText("Here disconnected :"+  CurrentIP);
  536.                     WriteTOTextFile("6:" + " " + se.NativeErrorCode + " : " + se.Message + System.DateTime.Now);
  537.                     StartListenClick();
  538.                     ////int indexofIP;
  539.                     ////indexofIP = FindAllOfMyString(CurrentIP);
  540.                     ////if( indexofIP != -1)
  541.                     ////{
  542.                     ////    lstBoxClientList.Items.RemoveAt(indexofIP);
  543.                     ////}
  544.  
  545.  
  546.                     //int i;
  547.                     //i=lstBoxClientList.FindString("," + CurrentIP);
  548.                     //lstBoxClientList.Items.RemoveAt(i);
  549.                 }
  550.                 else
  551.                 {
  552.                     //MessageBox.Show ("4 : " + se.ErrorCode + ": " + se.Message );
  553.                     WriteTOTextFile("7: a" + se.ErrorCode + " : " + se.Message + System.DateTime.Now);
  554.                 }
  555.  
  556.                   //  WaitForData(socketData01.m_currentSocket);
  557.                 //lbl_dev_count.Text = lstBoxClientList.Items.Count.ToString();
  558.                 lbl_dev_count.Text = hstIPDev.Count.ToString();
  559.             }
  560. }
[HTML]And in this read function when socket Client gets disconnected the byte length of data i recieve is zero and then i check for null ocket and then close the child socket which is not the main socket but one of the socket fin the array list.

Still waiting for solution [/HTML] setiarakeshgps@hotmail.com[/HTML]
Dec 15 '07 #4

P: 10
http://www.csharphelp.com/archives3/archive486.html


I found this researching your question not sure if it will help but this seems to set the sockets I found it at http://www.csharphelp.com/archives3/archive486.html

Expand|Select|Wrap|Line Numbers
  1. public Server(int port, string title, string attr)
  2.   {
  3.     this.portNumber = port;
  4.     this.title = title;
  5.     this.maxSockets =10000;
  6.     connectedSocks = new ArrayList(this.maxSockets);
  7.   }
  8.  
  9.  
  10. /// 
  11. /// Description: Start the threads to listen to the port and process
  12. /// messages.
  13. /// 
  14.  
a lot of other code was included maybe you can get an idea from there
hope it helps
[HTML]Rakesh Says Thanks for Reply But alreday i have set 20000 for socket clients in array to handle the processing of data receving from the 60 Clients Below is the Code which i am using[/HTML]
Expand|Select|Wrap|Line Numbers
  1. //Start Listen Here On Button click
  2. void ButtonStartListenClick(object sender, System.EventArgs e)
  3.         {
  4.  
  5.             OPenDataBaseConnectionIfClosed();
  6.  
  7.             try
  8.             {
  9.                 // Check the port value
  10.                 if (textBoxPort.Text == "")
  11.                 {
  12.                     MessageBox.Show("Please enter a Port Number");
  13.                     return;
  14.                 }
  15.                 string portStr = textBoxPort.Text;
  16.                 int port = System.Convert.ToInt32(portStr);
  17.                 // Create the listening socket...
  18.               /*  m_mainSocket = new Socket(AddressFamily.InterNetwork,
  19.                                           SocketType.Stream,
  20.                                           ProtocolType.Tcp);
  21.                */
  22.                 IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);
  23.                 // Bind to local IP Address...
  24.                 //MessageBox.Show("iplocal00" + ipLocal);
  25.                // m_mainSocket.Bind(ipLocal);
  26.  
  27.                 // Start listening...
  28.                 m_mainSocket.Listen(100000);
  29.                 //MessageBox.Show("iplocal 01" );
  30.                 // Create the call back for any client connections...
  31.                 m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
  32.                 //MessageBox.Show("iplocal 02");
  33.  
  34.                 //UpdateControls(true);
  35.                 //MessageBox.Show("iplocal 03");
  36.                 //      lblIPAddress.Text = m_mainSocket.RemoteEndPoint.ToString();
  37.                 //                MessageBox.Show("IP Number : " + m_mainSocket.RemoteEndPoint);    
  38.                 //  lblIPAddress = m_mainSocket.RemoteEndPoint;
  39.  
  40.             }
  41.             catch (SocketException se)
  42.             {
  43.                 lblIPAddress.Text = "6 : Connection Closed";
  44.  
  45.                 WriteTOTextFile("1:" + se.NativeErrorCode + " : " + se.Message + System.DateTime.Now);
  46.             }
  47.  
  48.         }
  49.  
  50. // This is the call back function, which will be invoked when a client is connected
  51. public void OnClientConnect(IAsyncResult asyn)
  52.         {
  53.             try
  54.             {
  55.                 // Here we complete/end the BeginAccept() asynchronous call
  56.                 // by calling EndAccept() - which returns the reference to
  57.                 // a new Socket object
  58.                 //m_mainSocket.
  59.  
  60.                 m_workerSocket[m_clientCount] = m_mainSocket.EndAccept(asyn);
  61.  
  62.                 // Let the worker Socket do the further processing for the 
  63.                 // just connected client
  64.  
  65.  
  66.  
  67.                 WaitForData(m_workerSocket[m_clientCount]);
  68.  
  69.                 // Now increment the client count
  70.                 ++m_clientCount;
  71.                 ++SocketNo;
  72.                 // Display this client connection as a status message on the GUI    
  73.                 //String str = String.Format("Client # {0} connected", m_clientCount);
  74.                 String str = String.Format("Client # {0} connected", SocketNo);
  75.                 textBoxMsg.Text = str;
  76.                 SocketNo = m_clientCount;
  77.               //  m_workerSocket[m_clientCount].Ttl = 500;
  78.                 // lblIPAddress.Text;
  79.                 //  MessageBox.Show(" : " + m_clientCount +  " : ");
  80.                 String ipconnected = m_workerSocket[m_clientCount].RemoteEndPoint.ToString();
  81.                  hstIPDev.Add(ipconnected, "0");
  82.                  lblIPAddress.Text = ":: " + ipconnected;
  83.                  lbl_dev_count.Text = hstIPDev.Count.ToString();
  84.                 // Since the main Socket is now free, it can go back and wait for
  85.                 // other clients who are attempting to connect
  86.  
  87.                 m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
  88.  
  89.  
  90.             }
  91.  
  92.             catch (ObjectDisposedException e )
  93.             {
  94.                 //lblIPAddress.Text = "4 : Connection Closed";
  95.                 System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
  96.                 WriteTOTextFile("2 " +  e.Message + " : OnClientConnection: Socket has been closed : " + System.DateTime.Now);
  97.  
  98.                 textBoxMsg.Text = String.Format("Client # {0} connected",m_clientCount);
  99.  
  100.  
  101.  
  102.             }
  103.             catch (SocketException se)
  104.             {
  105.  
  106.                 //MessageBox.Show("22" + " ErrorCode " + se.ErrorCode + " : " +se.Message);
  107.                 WriteTOTextFile("3: " + se.NativeErrorCode + " : " + se.Message + System.DateTime.Now);
  108.                 StartListenClick();
  109.                 //m_mainSocket.Close();
  110.                 //StartListenClick();
  111.  
  112.             }
  113.             catch (Exception se)
  114.             {
  115.  
  116.                 //MessageBox.Show("22" + " ErrorCode " + se.ErrorCode + " : " + se.Message);
  117.                 WriteTOTextFile("33: "  + " : " + se.Message + System.DateTime.Now);
  118.                 StartListenClick();
  119.  
  120.             }
  121.  
  122.  
  123.  
  124.         }
Dec 15 '07 #5

Post your reply

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