NTP阅读VB.NET

问题描述 投票:0回答:2

我试图通过streamreader读取ntp,我发现从ph.pool.ntp.org获取时间很困难,当我尝试在计时器上运行它时,它给了我一个outofboundsexception

继承我的代码

 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()开始。

vb.net date datetime time ntp
2个回答
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#?


0
投票

我想你必须改变一下

read += strm.Read(buf, read, 1024)

进入

read += strm.Read(buf, read, 1024-read)
© www.soinside.com 2019 - 2024. All rights reserved.