< C# Asynchronous Client Program Example | Main | The Asynchronous Socket Operations >


 

Chapter 9 Part 7:

Server or Listening Sockets Programming

 

 

What do we have in this chapter 9 Part 7?

  1. VB .NET Asynchronous Client Program Example

 

 

VB .NET Asynchronous Client Program Example

 

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

 

VB .NET Asynchronous Client Program Example - creating a new class library project in Visual Studio 2008 IDE

 

Rename the source file to AsyncClient to reflect the application that we are going to develop. Take note that the default class name also will be renamed automatically.

 

VB .NET Asynchronous Client Program Example - renaming the source file

 

Next, let add the reference to the AsyncPacketClass that we have created before. Select the project folder > Right click mouse > Select Add Reference context menu.

 

VB .NET Asynchronous Client Program Example - invoking the Add Reference page

 

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

 

VB .NET Asynchronous Client Program Example - browsing and finding the DLL file

 

Select the DLL file and click OK.

 

VB .NET Asynchronous Client Program Example - selecting the DLL file

 

In the project property page, you can see the referred class in the References link.

 

VB .NET Asynchronous Client Program Example - invoking the project's property page

 

VB .NET Asynchronous Client Program Example - the project's References

 

Next, add the following Imports directives

 

Imports System

Imports System.Net

Imports System.Net.Sockets

Imports System.Collections

Imports System.Threading

Imports AsyncPacketClass.AsyncPacket

 

At this stage, you may want to test the functionality of the referred class. You can see the intellisense as shown below for the AsyncPacketClass Imports directive or you can build the project, there should be no error.

 

VB .NET Asynchronous Client Program Example - testing the custom made class

 

Next, add the usage() subroutine.

 

' Displays simple usage information       

    Shared Sub 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()

    End Sub

 

Then, add the Main() subroutine and its code.

 

 

 

 

 

 

    ' 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.       

    Shared Sub Main()

        Dim clientList As ArrayList = New ArrayList

        Dim clientListEmpty As ManualResetEvent = New ManualResetEvent(False)

        Dim serverName As String = "localhost"

        Dim connectCount As Integer = 5

        Dim serverPort As Integer = 5150

 

        ' Parse the command line

        Dim appArguments As String() = Environment.GetCommandLineArgs()

        Dim i As Integer

 

        usage()

 

        For i = 1 To appArguments.GetUpperBound(0)

            Try

                Dim CurArg() As Char = appArguments(i).ToCharArray(0, appArguments(i).Length)

 

                If (CurArg(0) = "-") Or (CurArg(0) = "/") Then

                    Select Case Char.ToLower(CurArg(1), System.Globalization.CultureInfo.CurrentCulture)

                        Case "c"

                            ' How many client connections to establish to server

                            i += 1

                            connectCount = System.Convert.ToInt32(appArguments(i))

                        Case "n"

                            ' Server address/name to connect to

                            i += 1

                            serverName = appArguments(i)

                        Case "p"

                            ' Port on which server is listening on

                            i += 1

                            serverPort = System.Convert.ToInt32(appArguments(i))

                        Case Else

                            usage()

                    End Select

                End If

            Catch

                usage()

                Exit Sub

            End Try

        Next

 

        Try

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

            '    ClientConnection objects for each address returned from

            '    name resolution.

            Console.WriteLine("Resolving the host name & creating connection count...")

            Dim resolvedHost As IPHostEntry = Dns.GetHostEntry(serverName)

            Dim addr As IPAddress

 

            For Each addr In resolvedHost.AddressList

                Dim serverEndPoint As IPEndPoint = New IPEndPoint(addr, serverPort)

                Dim clientConn As ClientConnection

 

                For i = 0 To connectCount - 1

                    clientConn = New ClientConnection(serverEndPoint, clientList, clientListEmpty)

 

                    Monitor.Enter(clientList)

                    clientList.Add(clientConn)

                    Monitor.Exit(clientList)

                Next

            Next

        Catch err As Exception

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

        End Try

 

        Try

            ' 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) Then

                    Exit While

                End If

            End While

            Exit Try

        Catch err As Exception

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

        End Try

    End Sub

 

In order to test this program, change the project DLL type to application type (EXE). Select project folder > Right click mouse > select Properties context menu.

 

VB .NET Asynchronous Client Program Example - invoking the project's property page to change the project type

 

Change the Application type: to Console Application and Startup object: to Sub Main.

 

VB .NET Asynchronous Client Program Example - change the Application type: to Console Application and Startup object: to Main() subroutine

 

Build the project.

 

VB .NET Asynchronous Client Program Example - building the project

 

Run the project.

 

VB .NET Asynchronous Client Program Example - running the project  

 

The referred class also included in the project. In order to run the executable, you need to have the DLL file together.

 

VB .NET Asynchronous Client Program Example - the DLL was imported into the existing project when we add the reference. We need to have this DLL in order to run the executable

 

The following is the output sample.

 

VB .NET Asynchronous Client Program Example - a sample output using default argument values

 

The following screenshots show the server and the client programs run together. 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.

 

VB .NET Asynchronous Client Program Example - running the asynchronous tcp server to test the client. A few clients got connected.

 

 

VB .NET Asynchronous Client Program Example - the asynchrounous tcp client in action

 

 

 


 

< C# Asynchronous Client Program Example | Main | The Asynchronous Socket Operations >