使用UDPClient&侦听特定端口获取传输的数据包

时间:2017-02-18 15:52:34

标签: c# network-programming udp udpclient

首先,我为错误使用术语而道歉。

我的本​​地网络上有一个传感器。它通过端口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]
 ...

据我所知,再次,原谅我糟糕的网络知识,我必须以某种方式向这个传感器发回一个确认信息,所以它开始向我发送“真实的”数据。

欢迎任何提示或建议!

1 个答案:

答案 0 :(得分:1)

这里至少有两种可能性。

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

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

这里的关键是检查传感器附带的文件。 新代码将位于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); 
}
相关问题