Click here to Skip to main content
15,880,392 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a client which connects to server with 3 connections and server is receiving all the data from these connections but after some processing in the client side server detects that these 3 connections are disconnected. I tried executing the code line by line and found out that after running around 13 iterations of while(true) the client disconnects itself. The code in the while loop has nothing to do with the sockets.

What I have tried:

Function to connect to server

C#
public static void ConnectToServer()
        {
            byte[] request = Encoding.ASCII.GetBytes("Add Connection|requestSplit" + Environment.MachineName + "|requestSplit|requestSplitLive Screen");
            Socket s = clientSocket.socketConnect();
            sendToServer.SendFullData(request, s);

            Console.WriteLine("Connected: " + s.RemoteEndPoint);
            logFileWrite(DateTime.Now.ToString("hh:mm:ss") + ": " + Encoding.ASCII.GetString(request));

            Thread.Sleep(1000);

            request = Encoding.ASCII.GetBytes("Add Connection|requestSplit" + Environment.MachineName + "|requestSplit|requestSplitAudio");
            s = clientSocket.socketConnect();
            sendToServer.SendFullData(request, s);

            Console.WriteLine("Connected: " + s.RemoteEndPoint);
            logFileWrite(DateTime.Now.ToString("hh:mm:ss") + ": " + Encoding.ASCII.GetString(request));

            Thread.Sleep(1000);

            request = Encoding.ASCII.GetBytes("Add Connection|requestSplit" + Environment.MachineName + "|requestSplit|requestSplitPath");
            s = clientSocket.socketConnect();
            sendToServer.SendFullData(request, s);

            Console.WriteLine("Connected: " + s.RemoteEndPoint);
            logFileWrite(DateTime.Now.ToString("hh:mm:ss") + ": " + Encoding.ASCII.GetString(request));

            Thread.Sleep(1000);

            Console.WriteLine("Connected");
        }



while loop:

C#
Thread restrictedAreaThread = new Thread(restrictedAreasAccess);
restrictedAreaThread.IsBackground = true;
restrictedAreaThread.Start();

private void restrictedAreasAccess()
{
      int count = 1;
      while(true)
      {
          SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows();
          foreach (SHDocVw.InternetExplorer ie in shellWindows)
          {
               filename = Path.GetFileNameWithoutExtension(ie.FullName).ToLower();
               if (lastPathAccessed != ie.LocationURL)
               {
                  if (filename.Equals("explorer"))
                  {
                      // Save the location off to your application
                      filenameArray.Add(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "-" + ie.LocationURL);

                      if (ie.LocationURL != null || ie.LocationURL != string.Empty)
                      {
                         // Setup a trigger for when the user navigates
                         try
                         {
                            string unread = "Unread";
                            string pathAccessedDB = cpuInfo + " - pathAccessed";
                            string query = string.Empty;

                            string urlString = ie.LocationURL.ToString();
                            if (urlString.Contains("\\"))
                            {
                                urlString = urlString.Replace("\\", "/");
                            }
                            if (urlString.Contains("%20"))
                            {
                                urlString = urlString.Replace("%20", " ");
                            }
                            if (urlString.Contains("file:///"))
                            {
                                urlString = urlString.Replace("file:///", string.Empty);
                            }
                            Console.WriteLine("Filter: " + urlString);

                            try
                            {
                                string ConnectionString = @"Server=" + Program.server + ";Database=monitoringsystem;port=3306;uid=" + Program.userid + ";pwd=" + Program.password + "";
                                MySqlConnection connection = new MySqlConnection(ConnectionString);
                                connection.Open();
                                MySqlCommand command = new MySqlCommand();
                                command.Connection = connection;
                                command.CommandText = "insert into `" + pathAccessedDB + "`(TimeStamp, Path, Status) values('" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss").Replace("'", "''") + "','" + urlString.ToString() + "','" + unread + "')";
                                query = command.CommandText;
                                command.ExecuteNonQuery();
                                connection.Close();

                                lastPathAccessed = ie.LocationURL;
                             }
                             catch (Exception ex)
                             {
                                MessageBox.Show(ex.ToString() + "\nFor query: " + query);
                             }
                       }
                       catch (Exception ex)
                       {
                          MessageBox.Show(ex.ToString());
                       }
                   }
                   else
                   {
                     Console.WriteLine("Location is null!");
                   }
              }
           }
        }
    }
}


In the restrictedAreasAccess() after 13 iterations the server detects client disconnection. If I comment the call function then the program works correctly. I don't know what is wrong with this.
Posted
Updated 30-Jan-23 17:07pm
v2
Comments
Member 15627495 31-Jan-23 2:18am    
few comments :
- use a !!'DB class' instead of that bunch of codelines for the connection to DB.
a db class :
- connect to DB
- execute a query
- return the result from a query
- disconnect from DB

// all the Url checking like
"if (urlString.Contains("\\"))"
are useless, go straight to it with
"urlString = urlString.Replace("\\", "/");"
. because Replace(,) check the string too, and if patterns are found, it will be 'replace', the condition 'in string' is provided by replace(,) ( you'll earn by less lines of code ).

//
while(true) need a 'return false/break', or it is an 'infinite loop', it's risky and attempting a crash of your thread.


//
"if (lastPathAccessed != ie.LocationURL){ if (filename.Equals("explorer")){"
can be merge to make :
if (lastPathAccessed != ie.LocationURL && filename.Equals("explorer")) {...
// since there are no instructions in the first scope.
Member 14623639 31-Jan-23 2:38am    
Are these some mistakes that are causing the socket to disconnect?
Member 15627495 31-Jan-23 2:43am    
the DBs codes lines are too much, be aware that you're a connecting the DB !!! at each loop !!! ... it's not relevant, lots of resources for nothing.
because it involve lots of "connect to db" and "close the db" every loop, it's close to an overload of 'call to db'.
just keep inside your process : the "query string built", and "the execution of the query".
Member 14623639 31-Jan-23 3:38am    
Yes you are right. After commenting out some code the sockets weren't disconnecting but I still don't get it as I understood that too many processes in the application are causing this but how do they lead sockets(async) to disconnect? Because this has never happened before and I'm curious to know what is it exactly happening causing this issue.
Member 15627495 31-Jan-23 4:38am    
use Task( return T) or more Thread(return T) if you wanna escape from 'crash'.
prefers Thread in MTA at launch ( because of unrestricted memory space ).

as a Trick, you can store too all the coming new sql query -> in a array of string... before executing them just once.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900