首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场

PTP通信
EN

Stack Overflow用户
提问于 2015-08-05 04:35:19
回答 1查看 1.1K关注 0票数 2

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

我知道组播是通过PTP端口319上的IP地址224.0.1.129完成的。我的粗略轮廓是这样的:

代码语言:javascript
运行
复制
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;
}

其中接收()是一个方法,如果您收到同步消息,该方法将返回一个布尔值,并且最终将以字节存储该消息。我尝试使用套接字与服务器连接,但我的计时器总是超时,并返回false。我将我的PTP服务器设置为每秒发送一条同步消息,因此我知道我的超时(3秒后)应该能够获得它。

请帮帮我!

EN

回答 1

Stack Overflow用户

发布于 2015-08-06 03:26:03

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

另外,我认为你需要使用ReceiveFrom方法,而不是接收。

another question about some basic UDP stuff

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

代码语言:javascript
运行
复制
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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31818827

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档