A Simple Speedtest Application for Xamarin

In my previous post I described how to check your connection in a C# project. I should have the same function in a PCL project for Xamarin. Based on my project, I created this function:
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace PSC.Xamarin.Connection
{
	/// 
	/// Speed test.
	/// 
	public class SpeedTest
	{
		public double SecondsForOneMb { get; set; } = 0;
		public double KbSeconds { get; set; } = 0;

		/// 
		/// Starts the test to download a file from an url.
		/// Read SecondsForOneMb and KbSeconds for the result
		/// 
		public async Task StartTest()
		{
			string url = 
            "http://puresourcecode.com/file.axd?file=/SpeedTest/1024kb.txt";
			HttpClient client = new HttpClient();

			// get current tickcount 
			double starttime = Environment.TickCount;

			// download file from the specified URL, 
			// and save it to C:\speedtest.txt
			// in your project change the path of the following line
			var httpResponse = await client.GetAsync(url);
			byte[] dataBuffer = 
                   await httpResponse.Content.ReadAsByteArrayAsync();

			// get current tickcount
			double endtime = Environment.TickCount;

			// how many seconds did it take?
			// we are calculating this by subtracting starttime from
			// endtime and dividing by 1000 (since the tickcount is in 
			// miliseconds 1000 ms = 1 sec)
			SecondsForOneMb = Math.Floor(endtime - starttime) / 1000;

			// calculate download rate in kb per sec.
			// this is done by dividing 1024 by the number of seconds it
			// took to download the file (1024 bytes = 1 kilobyte)
			KbSeconds = Math.Round(1024 / SecondsForOneMb);
		}
	}
}

Happy coding!

Add comment

Advertsing

125X125_06

Calendar

<<  July 2017  >>
MonTueWedThuFriSatSun
262728293012
3456789
10111213141516
17181920212223
24252627282930
31123456

View posts in large calendar

Tag cloud

Month List