我正在尝试与精确时间协议(protocol)(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;
}

其中,Receive()是一种方法,如果您收到同步消息,它将返回一个 bool 值,并最终将消息存储为字节。我试图使用套接字与服务器连接,但是我的计时器始终超时,并返回false。我将我的PTP服务器设置为每秒发送一次同步消息,因此我知道我的超时(3秒后)应该可以接收它。

请帮忙!

最佳答案

粗略浏览一下,但也许不要抑制异常(空的catch块),而是将其抛出或打印出来以查看发生了什么类型的问题。

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

another question about some basic UDP stuff

因此,调用ReceiveFrom和Bind到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;
}

关于c# - PTP通讯,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31818827/

10-13 06:05