|
Build and Run
Build and run the project. Make sure there is no error else you have to resolve the error.
The following screenshot shows a sample console output when run from Visual Studio without debugging. This program needs to run at the command prompt.
|
Launch the command prompt. Run the program with some sample options. The following sample output uses:
%\FastGetCS\bin\Debug>fastgetcs -a -c 10 -n 10 -u http://www.reactos.org/en/dev.html
As the arguments and the following screenshot shows the console output.
Use different arguments mainly the –n and –c options combination for 'performance comparison'. A complete output for the previous sample run is given below.
C:\networkdotnetproject\FastGetCS\FastGetCS\bin\Debug>fastgetcs -a -c 10 -n 10 -u http://www.reactos.org/en/dev.html
In FastAsyncGetCS.Main()
Counting start in ms: 6726437
In FastAsyncGetCS.GetPages()
In FastAsyncGetCS.ResponseCallback()
In FastAsyncGetCS.ResponseCallback()
In FastAsyncGetCS.ResponseCallback()
In FastAsyncGetCS.ReadCallBack()
In FastAsyncGetCS.ReadCallBack()
In FastAsyncGetCS.ReadCallBack()
[trimmed]
In FastAsyncGetCS.ReadCallBack()
In FastAsyncGetCS.ResponseCallback()
In FastAsyncGetCS.ResponseCallback()
In FastAsyncGetCS.ReadCallBack()
In FastAsyncGetCS.ReadCallBack()
[trimmed]
In FastAsyncGetCS.ReadCallBack()
In FastAsyncGetCS.ReadCallBack()
In FastAsyncGetCS.ResponseCallback()
In FastAsyncGetCS.ReadCallBack()
In FastAsyncGetCS.ReadCallBack()
[trimmed]
In FastAsyncGetCS.ReadCallBack()
In FastAsyncGetCS.ReadCallBack()
In FastAsyncGetCS.ResponseCallback()
In FastAsyncGetCS.ReadCallBack()
In FastAsyncGetCS.ReadCallBack()
In FastAsyncGetCS.ReadCallBack()
In FastAsyncGetCS.ReadCallBack()
In FastAsyncGetCS.ResponseCallback()
In FastAsyncGetCS.ReadCallBack()
In FastAsyncGetCS.ReadCallBack()
In FastAsyncGetCS.ReadCallBack()
In FastAsyncGetCS.ResponseCallback()
In FastAsyncGetCS.ReadCallBack()
In FastAsyncGetCS.ReadCallBack()
In FastAsyncGetCS.ReadCallBack()
In FastAsyncGetCS.ResponseCallback()
In FastAsyncGetCS.ReadCallBack()
In FastAsyncGetCS.ReadCallBack()
In FastAsyncGetCS.ReadCallBack()
[trimmed]
In FastAsyncGetCS.ReadCallBack()
In FastAsyncGetCS.ReadCallBack()
In FastAsyncGetCS.ReadCallBack()
In FastAsyncGetCS.ReadCallBack()
In FastAsyncGetCS.ReadCallBack()
Counting end in ms: 6803375
Total count in ms: 76938
Calculating the total KB/s...
Then total count in seconds 76.938 seconds.
Number of request: 0.1299748 requests per second.
It is 1 KB per second.
C:\networkdotnetproject\FastGetCS\FastGetCS\bin\Debug>
Create a new VB .NET console application project. You may want to use the solution and project names as shown in the following screenshot.
Add/edit the code as given below.
' This sample measures HTTP GET performance through the HttpWebRequest class. Various ' options can be configured such as the connectionlimit, the total number of requests, ' Nagling, unsafe connection sharing, etc. The sample posts the requested number of ' asynchronous requests. When one completes, the response is retrieved, and an ' asynchronous stream receive is posted. The stream receive is reposted until the entire ' data stream has been read. ' ' Usage: ' fastgetvb -c [int] -n [int] -u [URI] -p ' -a Allow unsafe authenticated connections ' -c int Number of concurrent requests allowed ' -d Disable Nagle algorithm ' -n int Total number of connections to make ' -u URI URI resource to download ' -p Enable pipelining ' -un string User name ' -up string Password ' -ud domain Domain ' ' Sample usage: ' fastgetvb -c 10 -n 10000 -u http://foo.com/default.html ' ' fastgetvb -c 10 -n 10000 -u http://foo.com/default.html '
Imports System Imports System.IO Imports System.Net Imports System.Text Imports System.Threading Imports System.Globalization
Module Module1
' <summary> ' Simple client designed to max out the network ' using HttpWebRequest. ' </summary> Class FastAsyncGet
Public Shared uriName As Uri = Nothing Public Shared allDone As ManualResetEvent = Nothing Public Shared numRequests As Integer = 10 Public Shared Test As Integer = 1 Public Shared numConnections As Integer = 2 Public Shared numRequestsCompleted As Integer = 0 Public Shared readBuffer() As Byte = Nothing Public Shared totalBytesReceived As Long = 0 Public Shared pipeliningEnabled As Boolean = False Public Shared useNagle As Boolean = True Public Shared unsafeAuthentication As Boolean = False Public Shared userInfo As NetworkCredential = Nothing
' <summary> ' Displays usage information. ' </summary> Shared Sub usage() Console.WriteLine("usage: fastgetvb -c [int] -n [int] -u [URI] -p") Console.WriteLine(" -a Allow unsafe authenticated connections") Console.WriteLine(" -c int Number of concurrent requests allowed") Console.WriteLine(" -d Disable Nagle algorithm") Console.WriteLine(" -n int Total number of connections to make") Console.WriteLine(" -u URI URI resource to download") Console.WriteLine(" -p Enable pipelining") Console.WriteLine(" -un string User name") Console.WriteLine(" -up string Password") Console.WriteLine(" -ud domain Domain") Console.WriteLine("") Console.WriteLine("Sample: fastgetvb -a -c 10 -n 10000 -u http://foo.com/default.html") End Sub
' <summary> ' This is the main method which parses the command line and initiates the GET requests. ' It then waits for the 'allDone' method to be set at which point it calculates the performance ' statistics and displays them to the console. ' </summary> ' <param name="args">Command line parameters</param> Shared Sub Main() Dim userName As String = Nothing Dim passWord As String = Nothing Dim domain As String = Nothing
Dim appArguments As String() = Environment.GetCommandLineArgs() Dim i As Integer
For i = 1 To appArguments.GetUpperBound(0) - 1 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), Globalization.CultureInfo.CurrentCulture)
Case "a" ' Allow unsafe authentication unsafeAuthentication = True Case "c" ' How many concurrent requests to allow ' i + 1 to fetch the argument else we just fetch the options/switches ' numConnections = Convert.ToInt32(appArguments(i + 1)) -- IS OK! ' http://www.codeproject.com/KB/cs/AgileWare_Convert_Int32.aspx ' numConnections = Integer.Parse(appArguments(i)) ' -- FAIL! Test = Int32.TryParse(appArguments(i + 1), i + 1) Console.WriteLine("appArguments(i+1) is: " + appArguments(i + 1)) ' Test = Integer.TryParse(appArguments(i), i) -- FAIL!
If Test = True Then numConnections = i + 1 Else Console.WriteLine("Cannot convert the bastard lor!") usage() Exit Sub End If i = i + 1
Case "d" ' Disable Nagle algorithm useNagle = False Case "n" ' How many client connections to establish to server numRequests = Convert.ToInt32(appArguments(i + 1)) i = i + 1 Case "p" ' Enable pipelining pipeliningEnabled = True Case "u" If (appArguments(i).Length = 2) Then ' URI to retrieve uriName = New Uri(appArguments(i + 1)) i = i + 1 Else Select Case Char.ToLower(CurArg(2)) Case "n" ' User name i = i + 1 userName = appArguments(i + 1) Case "p" ' Password i = i + 1 passWord = appArguments(i + 1) Case "d" ' Domain i = i + 1 domain = appArguments(i + 1) Case Else usage() Exit Sub End Select End If Case Else usage() End Select End If Catch err As Exception Console.WriteLine("Error lol! " + err.ToString()) usage() Exit Sub End Try Next
If (uriName Is Nothing) Then usage() Exit Sub End If
If ((Not userName Is Nothing) Or (Not passWord Is Nothing) Or (Not domain Is Nothing)) Then userInfo = New NetworkCredential(userName, passWord, domain) End If
Try Dim startTime As Double = 0.0 Dim endTime As Double = 0.0 Dim totalTime As Double = 0.0
ReDim readBuffer(1200) allDone = New ManualResetEvent(False) startTime = Environment.TickCount ' Console.WriteLine("The start counting in ms is: " + startTime) --- FAIL! Console.WriteLine("The start counting in ms is: {0}.", startTime) Console.WriteLine("Start getting the page...")
GetPages() allDone.WaitOne() endTime = Environment.TickCount Console.WriteLine("The end counting in ms is: {0}.", endTime) totalTime = endTime - startTime Console.WriteLine("The total time elapsed in ms is: {0}.", totalTime) Dim totalKBytes As Long = CLng((totalBytesReceived / 1000) / (totalTime / 1000)) Console.WriteLine("The total KB in the elapsed time (second) is: {0}.", totalKBytes) Console.WriteLine("The elapsed time in seconds is: {0} seconds.", totalTime / 1000) Console.WriteLine("The number of request in elapsed time is: {0} requests per second.", numRequests / (totalTime / 1000)) ' Gets a NumberFormatInfo associated with the en-US culture. Dim nfi As NumberFormatInfo = New CultureInfo("en-US", False).NumberFormat nfi.NumberDecimalDigits = 0 Console.WriteLine("It is " + totalKBytes.ToString("N", nfi) + " KB per second lor!") Catch ex As Exception Console.WriteLine(ex.ToString()) allDone.Set() End Try End Sub
'/ <summary> '/ Retrieve the given URI the requested number of times. This method initiates an asynchronous '/ HTTP GET request for the URI. '/ </summary> Shared Sub GetPages() Dim i As Integer
Console.WriteLine("In GetPages()") For i = 0 To numRequests - 1 Dim request As HttpWebRequest = WebRequest.Create(uriName)
request.ServicePoint.ConnectionLimit = numConnections request.ServicePoint.UseNagleAlgorithm = useNagle request.UnsafeAuthenticatedConnectionSharing = unsafeAuthentication request.Pipelined = pipeliningEnabled request.Credentials = userInfo If (Not userInfo Is Nothing) Then request.ConnectionGroupName = userInfo.UserName End If request.BeginGetResponse(AddressOf ResponseCallback, request) Next End Sub
' <summary> ' This is the asynchronous callback invoked when the HTTP GET request completes. It retrieves ' the HTTP response object, obtains the data stream, and posts an asynchronous stream read ' to retrieve the data. Note that all receives for all requests use the same data buffer since ' we don't care about the data -- we just want to measure performance. ' </summary> ' <param name="result">Asynchronous context result for the operation</param> Shared Sub ResponseCallback(ByVal result As IAsyncResult) Dim req As HttpWebRequest = result.AsyncState
Console.WriteLine("ResponseCallback()")
Try ' Retrieve the response and post a stream receive Dim response As WebResponse = req.EndGetResponse(result) Dim responseStream As Stream = response.GetResponseStream() responseStream.BeginRead(readBuffer, 0, readBuffer.Length, AddressOf ReadCallBack, responseStream) Catch ex As Exception Console.WriteLine("Exception thrown in ResponseCallback... " + ex.ToString()) req.Abort() Interlocked.Increment(numRequestsCompleted) End Try End Sub
'/ <summary> '/ This is the asynchronous callback for the asynchronous stream receive operation posted after the '/ HTTP response is obtained from a request. This method checks the number of bytes returned. If it is '/ non-zero, another receive is posted as there could be more data pending. If zero is returned, we have '/ read the entire data stream so we can close it. '/ </summary> '/ <param name="asyncResult">Asynchronous context result for the operation</param> Shared Sub ReadCallBack(ByVal asyncResult As IAsyncResult) Dim responseStream As Stream = asyncResult.AsyncState Dim read As Integer = responseStream.EndRead(asyncResult)
Console.WriteLine("ReadCallBack()")
If (read > 0) Then ' Possibly more data pending...post another receive totalBytesReceived = totalBytesReceived + read responseStream.BeginRead(readBuffer, 0, readBuffer.Length, AddressOf ReadCallBack, responseStream) Else ' Reached the end of the stream so close it up responseStream.Close() Interlocked.Increment(numRequestsCompleted)
If (numRequestsCompleted >= numRequests) Then allDone.Set() End If End If End Sub End Class End Module |