使用 UDP 客户端监听特定端口并获取传输的数据包

Listen To Specific Port With UDPClient & Get Transmitted Packets

首先,对于术语的错误使用,我深表歉意。

我的本地网络上有一个传感器。它通过端口 35333 向网络上的每个人广播当前温度值。我想创建一个 C# 控制台程序,持续接收来自该传感器的数据包。

这是我当前的代码:

public static UdpClient Client = new UdpClient(35333); 

private static async void Start()
{
      Client.BeginReceive(new AsyncCallback(recv), null);
}

private static void recv(IAsyncResult res)
{
      IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
      byte[] received = Client.EndReceive(res, ref RemoteIpEndPoint);

       //Process codes

      Client.BeginReceive(new AsyncCallback(recv), null);
}

上面的代码有效,但问题是:我一直收到相同的字节数组。

 ...
  [114][51][57][48][48][77][72][112]

  [114][51][57][48][48][77][72][112]

  [114][51][57][48][48][77][72][112]

  [114][51][57][48][48][77][72][112]

  [114][51][57][48][48][77][72][112]
 ...

据我所知,请再次原谅我的网络知识不足,我必须以某种方式向该传感器发送回确认,因此它开始向我发送“'real'”数据。

欢迎任何提示或建议!

这里至少有两种可能。

首先,这可能只是温度,并没有发生变化。在这种情况下,您需要按照传感器规范规定的方式解析字节。

其次,如果这确实是需要确认的数据包,那么您将需要找出传感器侦听的端口(来自规范),以及确认数据包应该是什么样子(来自规范)并将其发送到该端口。

这里的关键是查看传感器随附的文档。 新代码将位于 recv 方法内并类似于以下内容:

private static void recv(IAsyncResult res) 
{ 
    IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
    byte[] received = Client.EndReceive(res, ref RemoteIpEndPoint);

    //Pseudo code
    //start_packet is the packet of bytes above from the sensor
    If (received == start_packet)
    {
        //send acknowledgement
    }

    //Process codes
    Client.BeginReceive(new AsyncCallback(recv), null); 
}