Click here to Skip to main content
15,903,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I have created a TCP server which listens to client(s) executes some commands and returns the data. I am new to both socket & multi thread programming and I think i have written in multi thread , but an exception is happening when multi client are run. What i am trying now is that I am trying to run both server and multi clients from my local machine, will that be the issue?
Here is the code .

C#
public class TCPServer
 {

     /// <summary>
     /// Local Variables Declaration.
     /// </summary>
     private TcpListener m_server = null;
     private bool m_stopServer = false;
     private Thread m_serverThread = null;
     private ArrayList m_socketListenersList = null;

     /// <summary>
     /// Constructors.
     /// </summary>
     public TCPServer()
     {
         //Change this to get the machines IP and  port as per appsettings
         IPAddress ipAddress = IPAddress.Parse(ConfigurationManager.AppSettings["IPAddress"]);
         int portNumber = Convert.ToInt32(ConfigurationManager.AppSettings["PortNumber"]);
         if (ipAddress != null && portNumber > 0)
         {
             Init(new IPEndPoint(IPAddress.Any, portNumber));
         }
         else
         {
             Console.WriteLine("IP address / Port number not found!!!");
         }
     }


     /// <summary>
     /// Init method that create a server (TCP Listener) Object based on the
     /// IP Address and Port information that is passed in.
     /// </summary>
     /// <param name="ipNport"></param>
     private void Init(IPEndPoint ipNport)
     {
         try
         {
             m_server = new TcpListener(ipNport);
             string filePath = ConfigurationManager.AppSettings["ExecutablePath"];
             if (!Directory.Exists(filePath))
             {
                 throw new Exception("Path not found");
             }

         }
         catch (Exception e)
         {
             m_server = null;
         }
     }

     /// <summary>
     /// Method that starts TCP/IP Server.
     /// </summary>
     public void StartServer()
     {

         if (m_server != null)
         {
             // Create a ArrayList for storing SocketListeners before
             // starting the server.
             m_socketListenersList = new ArrayList();


             // Start the Server and start the thread to listen client
             // requests.
             m_server.Start();
             Console.WriteLine("The server is running at port " + ConfigurationManager.AppSettings["PortNumber"] + "...");
             Console.WriteLine("The local End point is  :" +
                               m_server.LocalEndpoint);
             Console.WriteLine("Waiting for a connection.....");
             m_serverThread = new Thread(new ThreadStart(ServerThreadStart));
             m_serverThread.Start();
         }


     }

     /// <summary>
     /// Method that stops the TCP/IP Server.
     /// </summary>
     public void StopServer()
     {
         if (m_server != null)
         {
             // It is important to Stop the server first before doing
             // any cleanup. If not so, clients might being added as
             // server is running, but supporting data structures
             // (such as m_socketListenersList) are cleared. This might
             // cause exceptions.

             // Stop the TCP/IP Server.
             m_stopServer = true;
             m_server.Stop();

             // Wait for one second for the the thread to stop.
             m_serverThread.Join(1000);

             // If still alive; Get rid of the thread.
             if (m_serverThread.IsAlive)
             {
                 m_serverThread.Abort();
             }
             m_serverThread = null;

             // Free Server Object.
             m_server = null;

             // Stop All clients.
             StopAllSocketListers();
         }
     }

     /// <summary>
     /// Method that stops all clients and clears the list.
     /// </summary>
     private void StopAllSocketListers()
     {
         foreach (TCPSocketListener socketListener
                      in m_socketListenersList)
         {
             socketListener.StopSocketListener();
         }
         // Remove all elements from the list.
         m_socketListenersList.Clear();
         m_socketListenersList = null;
     }

     /// <summary>
     /// TCP/IP Server Thread that is listening for clients.
     /// </summary>
     private void ServerThreadStart()
     {
         // Client Socket variable;
         Socket clientSocket = null;
         TCPSocketListener socketListener = null;
         while (!m_stopServer)
         {
             try
             {
                 // Wait for any client requests and if there is any
                 // request from any client accept it (Wait indefinitely).
                 clientSocket = m_server.AcceptSocket();

                 Console.WriteLine("Connection accepted from " + clientSocket.RemoteEndPoint);

                 // Create a SocketListener object for the client.
                 socketListener = new TCPSocketListener(clientSocket);


                 // Add the socket listener to an array list in a thread.safe fashion.
                 lock (m_socketListenersList)
                 {
                     m_socketListenersList.Add(socketListener);
                 }

                 // Start a communicating with the client in a different
                 // thread.
                 socketListener.StartSocketListener();
             }
             catch (SocketException)
             {
                 m_stopServer = true;
             }
             catch (Exception ex)
             {

             }
         }
     }


 }


The code I am using , I got it from a post in Code Project itself

When i try to run the second client instance I get error at the accpet socket area.

Please help me out

Thanks & Regards
Arjun Menon
Posted

1 solution

Instead creating your own threads you can make use of the asynchronous programming model.

MSDN has some pretty good examples for both client and server side.

Asynchronous Server Socket Example[^]

Using an Asynchronous Server Socket[^]

I think you will find this way of programming more robust and easier to trouble shoot.
 
Share this answer
 

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