|
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.
|
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.
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.
Browse and find the AsyncPacketClass DLL file. It should be under the project’s Debug (or Release) folder.
Select the DLL file and click OK.
In the project property page, you can see the referred class in the References link.
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.
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.
Change the Application type: to Console Application and Startup object: to Sub Main.
Build the project.
Run the project.
![]() |
|
The referred class also included in the project. In order to run the executable, you need to have the DLL file together.
The following is the output sample.
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.