예제 #1
0
 void sntpClient_QueryServerCompleted(object sender, QueryServerCompletedEventArgs e)
 {
     if (e.Succeeded)
     {
         listView.Items.Clear();
         listView.Items.AddRange(new ListViewItem[] {
             new ListViewItem(new string[]
                              { "Query Suceeded:", sntpClient.RemoteSNTPServer.ToString() }),
             new ListViewItem(new string[]
                              { "IP endpoint:", sntpClient.RemoteSNTPServer.GetIPEndPoint().ToString() }),
             new ListViewItem(new string[]
                              { "Leap indicator:", e.Data.LeapIndicatorText }),
             new ListViewItem(new string[]
                              { "Version number:", e.Data.VersionNumberText }),
             new ListViewItem(new string[]
                              { "Mode:", e.Data.ModeText }),
             new ListViewItem(new string[]
                              { "Stratum:", e.Data.StratumText }),
             new ListViewItem(new string[]
                              { "Poll interval (seconds):", e.Data.PollInterval.ToString() }),
             new ListViewItem(new string[]
                              { "Precision (seconds):", e.Data.Precision.ToString() }),
             new ListViewItem(new string[]
                              { "Root delay (seconds):", e.Data.RootDelay.ToString() }),
             new ListViewItem(new string[]
                              { "Root dispersion (seconds):", e.Data.RootDispersion.ToString() }),
             new ListViewItem(new string[]
                              { "Reference identifier:", e.Data.ReferenceIdentifier }),
             new ListViewItem(new string[]
                              { "Reference date & time:", string.Format("{0}.{1}",
                                                                        e.Data.ReferenceDateTime, e.Data.ReferenceDateTime.Millisecond) }),
             new ListViewItem(new string[]
                              { "Originate date & time:", string.Format("{0}.{1}",
                                                                        e.Data.OriginateDateTime, e.Data.OriginateDateTime.Millisecond) }),
             new ListViewItem(new string[]
                              { "Receive date & time:", string.Format("{0}.{1}",
                                                                      e.Data.ReceiveDateTime, e.Data.ReceiveDateTime.Millisecond) }),
             new ListViewItem(new string[]
                              { "Transmit date & time:", string.Format("{0}.{1}",
                                                                       e.Data.TransmitDateTime, e.Data.TransmitDateTime.Millisecond) }),
             new ListViewItem(new string[]
                              { "Destination date & time:", string.Format("{0}.{1}",
                                                                          e.Data.TransmitDateTime, e.Data.TransmitDateTime.Millisecond) }),
             new ListViewItem(new string[]
                              { "Round trip delay (seconds)", e.Data.RoundTripDelay.ToString() }),
             new ListViewItem(new string[]
                              { "Local clock offset (seconds)", e.Data.LocalClockOffset.ToString() }),
         });
     }
     if (e.LocalDateTimeUpdated)
     {
         listView.Items.Add(new ListViewItem(new string[]
                                             { "Local date & time updated. Now:", DateTime.Now.ToString() }));
     }
     if (e.ErrorData.Error)
     {
         listView.Items.Add(new ListViewItem(new string[] { "Error:", e.ErrorData.ErrorText }));
     }
 }
        // Protected Methods 

        /// <summary>
        /// Raises the QueryServerCompleted event.
        /// </summary>
        /// <param name="e">A QueryServerCompletedEventArgs instance.</param>
        protected virtual void OnQueryServerCompleted(QueryServerCompletedEventArgs e)
        {
            EventHandler <QueryServerCompletedEventArgs> eh = QueryServerCompleted;

            if (eh != null)
            {
                eh(this, e);
            }
        }
        /// <summary>
        /// This is the 'nuts and bolts' method that queries the server.
        /// </summary>
        /// <returns>A QueryServerResults instance that holds the results of the query.</returns>
        private QueryServerCompletedEventArgs QueryServer()
        {
            QueryServerCompletedEventArgs result = new QueryServerCompletedEventArgs();

            Initialize();
            UdpClient client = null;

            try
            {
                // Configure and connect the socket.
                client = new UdpClient();
                IPEndPoint ipEndPoint = RemoteSNTPServer.GetIPEndPoint();
                client.Client.SendTimeout    = Timeout;
                client.Client.ReceiveTimeout = Timeout;
                client.Connect(ipEndPoint);

                // Send and receive the data, and save the completion DateTime.
                SNTPData request = SNTPData.GetClientRequestPacket(VersionNumber);
                client.Send(request, request.Length);
                result.Data = client.Receive(ref ipEndPoint);
                result.Data.DestinationDateTime = DateTime.Now.ToUniversalTime();

                // Check the data
                if (result.Data.Mode == Mode.Server)
                {
                    result.Succeeded = true;

                    // Call other method(s) if needed
                    if (UpdateLocalDateTime)
                    {
                        UpdateTime(result.Data.LocalClockOffset);
                        result.LocalDateTimeUpdated = true;
                    }
                }
                else
                {
                    result.ErrorData = new ErrorData("The response from the server was invalid.");
                }
                return(result);
            }
            catch (Exception ex)
            {
                result.ErrorData = new ErrorData(ex);
                return(result);
            }
            finally
            {
                // Close the socket
                if (client != null)
                {
                    client.Close();
                }
            }
        }
 private void WorkerThreadStart()
 {
     lock (this)
     {
         QueryServerCompletedEventArgs e = null;
         try
         {
             e = QueryServer();
         }
         catch (Exception exception)
         {
             throw exception;
         }
         asyncOperation.PostOperationCompleted(operationCompleted, e);
     }
 }
        /// <summary>
        /// Gets the real local date and time using the default server and the specified timeout.
        /// If there is an error or exception, DateTime.MinValue is returned.
        /// </summary>
        /// <param name="remoteSNTPServer">The server to use.</param>
        /// <param name="timeout">The timeout in milliseconds used for sending and receiving.</param>
        /// <returns>The real local date and time.</returns>
        public static DateTime GetNow(RemoteSNTPServer remoteSNTPServer, int timeout)
        {
            SNTPClient sntpClient = new SNTPClient();

            sntpClient.UpdateLocalDateTime = false;
            sntpClient.RemoteSNTPServer    = remoteSNTPServer;
            sntpClient.Timeout             = timeout;
            QueryServerCompletedEventArgs args = sntpClient.QueryServer();

            if (args.Succeeded)
            {
                return(DateTime.Now.AddSeconds(args.Data.LocalClockOffset));
            }
            else
            {
                return(DateTime.MinValue);
            }
        }