我正在尝试与精确时间协议(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 block ),而是让它被抛出或打印出来以查看发生了什么类型的问题。
此外,鉴于您正在使用 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/