我正在尝试与精确时间协议( 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;
}
其中接收()是一个方法,如果您收到同步消息,该方法将返回一个布尔值,并且最终将以字节存储该消息。我尝试使用套接字与服务器连接,但我的计时器总是超时,并返回false。我将我的PTP服务器设置为每秒发送一条同步消息,因此我知道我的超时(3秒后)应该能够获得它。
请帮帮我!
发布于 2015-08-06 03:26:03
只是粗略地看一下,但也许不要压制异常(空的catch块),而是让它被抛出或打印出来,看看发生了什么类型的问题。
另外,我认为你需要使用ReceiveFrom方法,而不是接收。
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;
}
https://stackoverflow.com/questions/31818827
复制相似问题