元经理沟通

本文关键字: | 更新日期: 2023-09-27 18:06:26

我正在尝试与精确时间协议(PTP)服务器通信,并使用windows窗体和c#构建PTP时钟。我了解同步消息的整个过程,然后有时是后续消息,然后是延迟请求消息,最后是延迟响应消息。现在我需要与服务器通信。WireShark可以获取我需要的所有数据包,但是我如何使用c#获取这些数据包呢?

我知道多播是在PTP端口319上用IP地址224.0.1.129完成的。我的大致轮廓是这样的:

while (true) //Continuously getting the accurate time
{
    if (Receive())
    {
        //create timestamp of received time
        //extract timestamp of sent time
        //send delay request
        //Receive timestamp
        //create receive timestamp
        //calculate round trip time
        //adjust clock to new time
    }
}
private bool Receive()
{
    bool bReturn = false;
    int port = 319;
    string m_serverIP = "224.0.1.129";
    byte[] packetData = new byte[86];
    IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(m_serverIP), port);
    Socket newSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    try
    {
        newSocket.Connect(ipEndPoint);
        newSocket.ReceiveTimeout = 3000;
        newSocket.Receive(packetData, SocketFlags.None);
        newSocket.Close();
        bReturn = true;
    }
    catch
    { }
    return bReturn;
}

Where Receive()是一个方法,如果你接收到同步消息,它将返回一个布尔值,并最终以字节存储消息。我试图使用套接字与服务器连接,但我的计时器总是超时,并返回false。我把我的PTP服务器设置为每秒发送一个同步消息,所以我知道我的超时(3秒后)应该能够拾取它。

请帮忙!

元经理沟通

只是粗略地看了一下,但也许不要抑制异常(空catch块),而是让它被抛出或打印出来,看看发生了什么类型的问题。

另外,我认为你需要使用ReceiveFrom方法而不是Receive,因为你正在使用UDP。

另一个关于UDP的基本问题

因此调用ReceiveFrom并将套接字绑定到ipEndPoint。以下是您需要的大致内容:

private static bool Receive()
{
    bool bReturn = false;
    int port = 319;
    string m_serverIP = "127.0.0.1";
    byte[] packetData = new byte[86];
    EndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(m_serverIP), port);
    using(Socket newSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
    {
        try
        {
            //newSocket.Connect(ipEndPoint);
            newSocket.Bind(ipEndPoint);
            newSocket.ReceiveTimeout = 3000;
            //newSocket.Receive(packetData, SocketFlags.None);
            int receivedAmount = newSocket.ReceiveFrom(packetData, ref ipEndPoint);
            newSocket.Close();
            bReturn = true;
        }
        catch(Exception e)
        {
            Console.WriteLine("Dear me! An exception: " + e);
        }
    }
    return bReturn;
}
相关文章:
  • 没有找到相关文章