< VB .NET Asynchronous Server Program Example | Main | VB .NET Asynchronous Client Program Example >

 


 

Chapter 9 Part 6:

Server or Listening Sockets Programming

 

 

What do we have in this chapter 9 Part 6?

  1. C# Asynchronous Client Program Example

 

 

C# Asynchronous Client Program Example

 

Create a new console application project and you might want to use the solution name, AsyncTcpClientCS and project name, AsyncTcpClient as shown in the following Figure.

 

C# Asynchronous Client Program Example - creating a new console application project using VS 2008 IDE

 

Rename the source file to AsyncClient to reflect the application that we are going to develop.

 

C# Asynchronous Client Program Example - renaming the source file to reflect the application to be developed

 

Add the following using directive. Take note that the AsyncPacketClass also included, and then we need to add a reference to the class later.

 

using System;

using System.Net;

using System.Net.Sockets;

using System.Collections;

using System.Threading;

using AsyncPacketClass;

 

C# Asynchronous Client Program Example - adding the using directive that include the custom made class

 

Add a reference to the AsyncPacketClass class library. Select project folder > Right click mouse > Select Add Reference context menu.

 

C# Asynchronous Client Program Example - invoking the Add Reference page

 

Browse and find the AsyncPacketClass DLL file. It should be under the project’s Debug (Release) folder.

 

C# Asynchronous Client Program Example - browsing and finding the DLL file

 

Select the DLL file and click OK.

 

C# Asynchronous Client Program Example - selecting the DLL file to be included into the existing project

 

You should see the reference under the References folder in the Solution Explorer as shown below.

 

C# Asynchronous Client Program Example - the reference to the class can be seen under the References folder in the Solution Explorer

 

You can see the details of the class by double clicking the class node. All available objects in the class can be seen in the Object Browser.

 

C# Asynchronous Client Program Example - browsing the class objects through the Object Browser

 

Next, add the usage() method.

 

        /// <summary>

        /// Displays simple usage information

        /// </summary>

        static public void usage()

        {

            Console.WriteLine("Executable_file_name [-c count] [-n address] [-p port]");

            Console.WriteLine("Available options:");

            Console.WriteLine("     -c count        Number of simultaneous asynch connects (BeginAccept) to create");

            Console.WriteLine("     -n address      Server address to connect to");

            Console.WriteLine("     -p port         Port number to connect to server on");

            Console.WriteLine();

        }

 

Then, add th Main() code.

 

 

 

 

        /// <summary>

        /// This is the main program that parses the command line parameters and sets up each TCP

        /// listening socket by creating a TcpServer object to handle client connections to each

        /// listening endpoint. The TcpServer object creates a ClientConnection object for each

        /// established connection which handles IO operations from each client.

        /// </summary>

        /// <param name="args"></param>

        static void Main(string[ ] args)

        {

        ArrayList           clientList = new ArrayList();

        ManualResetEvent    clientListEmpty = new ManualResetEvent( false );

        string              serverName = "localhost";

        int                 connectCount = 10, serverPort = 5150;

 

        if (args.Length != 0)

        {

            // Parse the command line

            for (int i = 0; i < args.Length; i++)

            {

                try

                {

                    if ((args[i][0] == '-') || (args[i][0] == '/'))

                    {

                        switch (Char.ToLower(args[i][1]))

                        {

                            case 'c':

                                // How many client connections to establish to server

                                connectCount = System.Convert.ToInt32(args[++i]);

                                break;

                            case 'n':

                                // Server address/name to connect to

                                serverName = args[++i];

                                break;

                            case 'p':

                                // Port on which server is listening on

                                serverPort = System.Convert.ToInt32(args[++i]);

                                break;

                            default:

                                usage();

                                return;

                        }

                    }

                }

                catch

                {

                    usage();

                    return;

                }

            }

        }

        else

        {

            usage();

            return;

        }

 

        try

        {

            // Resolve the host name and create 'connectCount' number of

            //    ClientConnection objects for each address returned from name resolution.

            Console.WriteLine("Resolving the hostname & creating connection count...");

            IPHostEntry resolvedHost = Dns.GetHostEntry( serverName );

            foreach (IPAddress addr in resolvedHost.AddressList)

            {

                IPEndPoint       serverEndPoint = new IPEndPoint( addr, serverPort );

                ClientConnection clientConn;

 

                for(int i=0; i < connectCount ;i++)

                {

                    clientConn = new ClientConnection( serverEndPoint, clientList, clientListEmpty );

 

                    Monitor.Enter( clientList );

                    clientList.Add( clientConn );

                    Monitor.Exit( clientList );

                }

            }

        }

        catch ( Exception err )

        {

            Console.WriteLine("Error occurred: {0}", err.Message);

        }

 

        // Wait until all the TCP server sockets are done

        Console.WriteLine("Waiting until all the TCP server sockets are done...");

        while ( true )

        {

            clientListEmpty.WaitOne( );

            clientListEmpty.Reset();

            Console.WriteLine("Connected clients: {0}", clientList.Count );   

       

            if ( clientList.Count == 0 )

                break;

        }

    }

 

 

Build and run the project.

 

C# Asynchronous Client Program Example - building the project

 

Under the project’s Debug folder, you can see the executable and the DLL file that we refer in the project. In order to run the executable, we need to have the DLL together.

 

C# Asynchronous Client Program Example - the DLL has been imported into the existing project when we add a reference

 

The following is the sample output.

 

C# Asynchronous Client Program Example - a sample output without any arguments

 

Let test this client program with the server program. We will use the previously created server program. In this case, you may want to test several client programs against the server.

Firstly, run the server program and then run several client programs (from different paths in the same host or from different hosts). You may want to test this asynchronous client-server program in the real network either private or public.

The following snapshots show the server and the client program when run from the command prompt.

 

C# Asynchronous Client Program Example - the asynchronous tcp server sample output

 

C# Asynchronous Client Program Example - the asynchronous tcp client sample output

 

Firstly, run the server program.

 

C# Asynchronous Client Program Example - running the asynchronous tcp server with options

 

Then, run several client programs against the server program.

 

C# Asynchronous Client Program Example - the asynchronous tcp client in action try to connect to the async server

 

C# Asynchronous Client Program Example - another asynchronous tcp client in action, connecting to the async server

 

The following snapshot shows the server output with two completed connections from clients.

 

C# Asynchronous Client Program Example - the asynchronous tcp server sample output with connections from the clients

 

 

 


 

< VB .NET Asynchronous Server Program Example | Main | VB .NET Asynchronous Client Program Example >