65.9K
CodeProject is changing. Read more.
Home

Windows Phone NTP Client

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (1 vote)

Aug 7, 2011

CPOL
viewsIcon

23041

Windows Phone NTP Client

I've got plans for an application in which I need to know with certainty the current time. So I don't want to trust the time as reported by the user's device. Instead, I need to retrieve the time from a server. I made a NTP (Network Time Protocol) client for retrieving this information. This is something that couldn't be done on Windows Phone 7 prior to Mango. But with the fall update (Mango), access to sockets is granted.

The use of the client is pretty simple. At a minimum, one can create the client with the default constructor, subscribe to the ReceivedTime event, and call the RequestTime method to initiate a request. The ReceivedTime event may be called on a thread other than the UI thread so remember to use a dispatcher when making UI updates.

NTP Client

This is an example of a client using the code to display both the system time and the network time.

public partial class MainPage : PhoneApplicationPage
{
    private NtpClient _ntpClient;
    public MainPage()
    {
        InitializeComponent();
        _ntpClient = new NtpClient();
        _ntpClient.TimeReceived += new EventHandler<NtpClient.TimeReceivedEventArgs>
				(_ntpClient_TimeReceived);
    }

    void _ntpClient_TimeReceived(object sender, NtpClient.TimeReceivedEventArgs e)
    {
        this.Dispatcher.BeginInvoke(() =>
                                        {
                                            txtCurrentTime.Text = 
						e.CurrentTime.ToLongTimeString();
                                            txtSystemTime.Text = 
						DateTime.Now.ToUniversalTime().
						ToLongTimeString();
                                        });
    }

    private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
    {
            
    }

    private void UpdateTimeButton_Click(object sender, RoutedEventArgs e)
    {
        _ntpClient.RequestTime();
    }
}