【问题标题】:PTP Communication点对点通信
【发布时间】:2015-08-11 05:27:47
【问题描述】:

我正在尝试与精确时间协议 (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 秒后)应该能够接收到它。

请帮忙!

【问题讨论】:

    标签: c# sockets visual-studio-2013


    【解决方案1】:

    只是粗略的一瞥,但也许不要压制异常(空的 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;
    }
    

    【讨论】:

    • 我也试过了,但没有成功。问题不在于它无法接收(我之前做过 UDP 和 NTP 通信),而是它无法找到/得到我想要的。
    猜你喜欢
    • 2021-09-09
    • 2019-09-15
    • 2019-06-11
    • 2021-05-08
    • 2016-07-13
    • 1970-01-01
    • 1970-01-01
    • 2013-03-08
    • 2019-05-29
    相关资源
    最近更新 更多