2015-08-22 144 views
0

我试着通过StreamReader的NTP阅读,我发现很难从ph.pool.ntp.org获取时,它给了我一个outofboundsexception当我试图在定时器运行NTP阅读VB.NET

继承人我的代码

Public Function GetNISTTime(ByVal host As String) As DateTime 

    Dim timeStr As String = "" 

    Try 
     Dim reader As New StreamReader(New TcpClient(host, 13).GetStream) 
     timeStr = reader.ReadToEnd() 
     Console.WriteLine(timeStr.ToString) 
     reader.Close() 
    Catch ex As SocketException 
     Label1.Text = ex.Message 
    Catch ex As Exception 
     Label1.Text = ex.Message 
    End Try 

    Dim jd As Integer = Integer.Parse(timeStr.Substring(1, 5)) 
    Dim yr As Integer = Integer.Parse(timeStr.Substring(7, 2)) 
    Dim mo As Integer = Integer.Parse(timeStr.Substring(10, 2)) 
    Dim dy As Integer = Integer.Parse(timeStr.Substring(13, 2)) 
    Dim hr As Integer = Integer.Parse(timeStr.Substring(16, 2)) 
    Dim mm As Integer = Integer.Parse(timeStr.Substring(19, 2)) 
    Dim sc As Integer = Integer.Parse(timeStr.Substring(22, 2)) 
    Dim Temp As Integer = CInt(AscW(timeStr(7))) 

    Return New DateTime(yr + 2000, mo, dy, hr, mm, sc) 

End Function 

和主机名被装载在定时器

Label1.Text = GetNISTTime("ph.pool.ntp.org ").ToString 

,它是通过在形式负载的timer.start()开始。

+0

向我们展示字符串返回的是什么。 – OneFineDay

+0

@onefineday它不会返回一个字符串,因为它引发了一个抛出的异常:'System.ArgumentOutOfRangeException –

+0

WHere?什么线? – OneFineDay

回答

0
Public Function GetNISTTime(ByVal host As String) As DateTime 
    Using sck = New TcpClient(host, 13) 
     System.Threading.Thread.Sleep(100) 'give the server time to answer 
     Using strm = sck.GetStream 
      strm.ReadTimeout = 1000 '1s timeout 
      Dim buf(1023) As Byte 
      Dim read As Integer = 0 
      While read < 50 'loop until enough data is read 
       read += strm.Read(buf, read, 1024) 
       If read = 0 Then 'connection lost 
        Return Nothing 'or throw exception 
       End If 
      End While 
      Dim rawstring As String = System.Text.Encoding.ASCII.GetString(buf).Trim() 
      Dim rawdata As String() = rawstring.Split(" ") 
      Dim strdate As String() = rawdata(1).Split("-") 
      Dim strtime As String() = rawdata(2).Split(":") 
      Return New DateTime(2000 + strdate(0), strdate(1), strdate(2), strtime(0), strtime(1), strtime(2)) 
     End Using 
    End Using 
End Function 

而不是使用Substring的,我用另一种方法:Split

此外,我已经改变了如何从服务器读取数据,因为您没有让服务器有足够的时间来提供答案。

请注意,有时服务器会丢弃连接而不是发送时间,因此请检查函数是否返回Nothing

最后,您最好使用NTP库,或者至少向服务器发送预期的输入。

有趣的相关问题:How to Query an NTP Server using C#?