PTP通讯

时间:2015-08-04 20:35:19

标签: c# sockets visual-studio-2013

我正在尝试与精确时间协议(PTP)服务器通信,并使用Windows窗体和C#构建PTP时钟。我理解Sync消息的整个过程,然后有时是后续消息,然后是延迟请求消息,最后是延迟响应消息。现在我需要与服务器通信。 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()是一个在收到同步消息时返回布尔值的方法,并最终以字节为单位存储消息。我试图使用套接字连接服务器,但我的计时器总是超时,并返回false。我的PTP服务器设置为每秒发送一条同步消息,所以我知道我的超时(3秒后)应该能够接收它。

请帮忙!

1 个答案:

答案 0 :(得分:0)

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

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

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;
}