2 Replies - 588 Views - Last Post: 11 February 2016 - 05:22 PM Rate Topic: -----

#1 jphoc13  Icon User is offline

  • D.I.C Addict

Reputation: 0
  • View blog
  • Posts: 584
  • Joined: 08-July 13

Need to be able to instantiate a server and client multiple times.

Posted 11 February 2016 - 09:20 AM

Besides hard coding in multiple instances, I would like to set up some kind of condition for my server to know it is time to create another instance. I am hitting a logical stumbling block on how to do this properly.

Here is my server class:

namespace Server
{
    public class RunServer
    {

    
        // State object for reading client data asynchronously
        public class StateObject
        {
            // Client  socket.
            public Socket workSocket = null;
            // Size of receive buffer.
            public const int BufferSize = 1024;
            // Receive buffer.
            public byte[] buffer = new byte[BufferSize];
            // Received data string.
            public StringBuilder sb = new StringBuilder();
        }

        public class AsynchronousSocketListener
        {
            // Thread signal.
            public static ManualResetEvent allDone = new ManualResetEvent(false);

            public AsynchronousSocketListener(int port)
            {
            }

      

            public void StartListening()
            {
                // Data buffer for incoming data.
                byte[] bytes = new Byte[1024];
                int port = 0;

                // Establish the local endpoint for the socket.
                // The DNS name of the computer
                // running the listener is "host.contoso.com".
                IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
                IPAddress ipAddress = ipHostInfo.AddressList[0];
                IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);

                // Create a TCP/IP socket.
                Socket listener = new Socket(AddressFamily.InterNetwork,
                    SocketType.Stream, ProtocolType.Tcp);

                // Bind the socket to the local endpoint and listen for incoming connections.
                try
                {
                    listener.Bind(localEndPoint);
                    //backlog of how many clients to take in
                    listener.Listen(100);

                    while (true)
                    {
                        // Set the event to nonsignaled state.
                        allDone.Reset();

                        // Start an asynchronous socket to listen for connections.
                        Console.WriteLine("Waiting for a connection...");
                        listener.BeginAccept(
                            new AsyncCallback(AcceptCallback),
                            listener);

                        // Wait until a connection is made before continuing.
                        allDone.WaitOne();
                    }

                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }

                Console.WriteLine("\nPress ENTER to continue...");
                Console.Read();

            }

            public static void AcceptCallback(IAsyncResult ar)
            {
                // Signal the main thread to continue.
                allDone.Set();

                // Get the socket that handles the client request.
                Socket listener = (Socket)ar.AsyncState;
                Socket handler = listener.EndAccept(ar);

                // Create the state object.
                StateObject state = new StateObject();
                state.workSocket = handler;
                handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(ReadCallback), state);
            }

            public static void ReadCallback(IAsyncResult ar)
            {
                String content = String.Empty;

                // Retrieve the state object and the handler socket
                // from the asynchronous state object.
                StateObject state = (StateObject)ar.AsyncState;
                Socket handler = state.workSocket;

                // Read data from the client socket. 
                int bytesRead = handler.EndReceive(ar);

                if (bytesRead > 0)
                {
                    // There  might be more data, so store the data received so far.
                    state.sb.Append(Encoding.ASCII.GetString(
                        state.buffer, 0, bytesRead));

                    // Check for end-of-file tag. If it is not there, read 
                    // more data.
                    content = state.sb.ToString();
                    if (content.IndexOf("<EOF>") > -1)
                    {
                        // All the data has been read from the 
                        // client. Display it on the console.
                        Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
                            content.Length, content);
                        Random rand = new Random();
                        content = rand.ToString();
                        // Echo the data back to the client.
                        Send(handler, content);
                    }
                    else {
                        // Not all data received. Get more.
                        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                        new AsyncCallback(ReadCallback), state);
                    }
                }
            }

            private static void Send(Socket handler, String data)
            {
                // Convert the string data to byte data using ASCII encoding.
                byte[] byteData = Encoding.ASCII.GetBytes(data);

                // Begin sending the data to the remote device.
                handler.BeginSend(byteData, 0, byteData.Length, 0,
                    new AsyncCallback(SendCallback), handler);
            }

            private static void SendCallback(IAsyncResult ar)
            {
                try
                {
                    // Retrieve the socket from the state object.
                    Socket handler = (Socket)ar.AsyncState;

                    // Complete sending the data to the remote device.
                    int bytesSent = handler.EndSend(ar);
                    Console.WriteLine("Sent {0} bytes to client.", bytesSent);

                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();

                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }


            public static int Main(String[] args)
            {
                AsynchronousSocketListener a = new AsynchronousSocketListener(0);
                a.StartListening();
                return 0;
            }

        }
    }


}



Here is what I have so far for the program to create multiple instances of a server class:

namespace AppStart
{
    class ServerStart 
    {
        static void Main(string[] args)
        {
            //Need to set up while loop to allow for multiple connections and pass in port number
            while ()
            {
                Server.RunServer.AsynchronousSocketListener a = new RunServer.AsynchronousSocketListener(0);
                a.StartListening();
            }
            //Need to set up while loop to allow for multiple connections and pass in port number
           
            Server.RunServer.AsynchronousSocketListener b = new RunServer.AsynchronousSocketListener(0);
            b.StartListening();








        }
    }
}



Is This A Good Question/Topic? 0
  • +

Replies To: Need to be able to instantiate a server and client multiple times.

#2 jphoc13  Icon User is offline

  • D.I.C Addict

Reputation: 0
  • View blog
  • Posts: 584
  • Joined: 08-July 13

Re: Need to be able to instantiate a server and client multiple times.

Posted 11 February 2016 - 09:47 AM

This seems to be a similar solution to what I am looking for:

http://stackoverflow...ient-one-server
Was This Post Helpful? 0
  • +
  • -

#3 tlhIn`toq  Icon User is online

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6530
  • View blog
  • Posts: 14,446
  • Joined: 02-June 10

Re: Need to be able to instantiate a server and client multiple times.

Posted 11 February 2016 - 05:22 PM

See FAQ 10: I'm trying to make a client/server and....

Wanting to know how and where to distribute software, what to charge, how to secure it, how to provide updates and so on is fairly common. For that reason, if you look toward the end of my FAQ below questions 48 and higher cover a lot and provide several links to existing in-dept discussions. Of course distribution channels change rapidly. Some are platform specific such as Apple's app store if you are making iOS software. If you have any new suggestions specifically on where, please let me know and I'll update this FAQ.




tlhIn`toq's FAQ list - Updated Oct 2015


Learning to debug one's own code is an essential skill. Sadly, one that apparently few college courses teach. Silly if you ask me.
Placing breakpoints and walking through the code line by line allows you to actually WATCH it execute, check the condition of each of variable's run-time value, and watch the logic unfold right before your eyes.
Visualizing what your code does will let you see why it behaves the way it does.
It would be well worth your time to do the tutorials on FAQ 2. A couple hours learning this skill will save you hundreds of hours of confusion in one project alone.

In addition to FAQ 2 in the list below, also check my signature block for a link on how to look at your variables' values at run-time.

TOP most asked:
What does this error message mean?
FAQ 2: How do I debug
FAQ 3: How do I make Class1/Form1 talk to Class2/Form2

Why are you still building in WinForms?

Quote

"old 1990's WinForms"? i just use visual studio 2015 and started up with a windows form. didn't know there was an option for a newer winform?


WinForms is OLD. Virtually 'legacy' and to many of us nearly considered end-of-life. There are still placing building new projects in it, but I wouldn't work for anyplace that wanted to hold me back by two decades. There are probably tens of thousands of legacy WinForms applications in use in countless companies. "If it ain't broke, don't fix it." in other words: If there isn't a financial gain to be made in re-writing them right now why invest the time and money?

But with decades of WinForms comes developers with decades more experience than you'll have and you have no way to compete with them. Let the legacy developer maintain the legacy applications. Many of them are too stuck in their ways to move forward to WPF. Which is why if you look at job boards, what companies are hiring for and have been looking for, for the last several years its: WPF/MVVM.

So if I were you I would just jump right to WPF. Don't worry about WinForms unless you have a deliberate need for it down the line. Otherwise you spend 10,000 hours getting good at WinForms only to find you need to spend another 7,500 hours bringing your skillset forward several years into WPF - And at the same time break all the bad habits you learned in WinForms.

If some company hires you for WPF development, but would also like it if you could maintain some legacy applications THEN learn WinForms; and take your good habits from WPF with you.


FAQ (Frequently Asked Questions - Updated Nov 2015
Spoiler



Was This Post Helpful? 0
  • +
  • -

Page 1 of 1