简体   繁体   中英

How to get information from a remote UDP socket? C# & IPv4

I have hardware that sends information to the address 192.168.0.255 at approximately 5 second intervals (In the following image, the Wireshark software showing the device with IP address 192.168.0.241 sending the message " Hallo " to the address 192.168.0.255 on port 7000):

在此处输入图像描述

On the other hand, I have a desktop app made in C # that tries to read that information as follows:

int PORT = 7000;
udpClient = new UdpClient();
udpClient.Client.Bind(new IPEndPoint(IPAddress.Any, PORT));


private async Task<string> getData()
{
   try
   {
        var from = new IPEndPoint(0, 0);
        while (true)
        {
           var recvBuffer = udpClient.Receive(ref from);
           string result= Encoding.UTF8.GetString(recvBuffer);
           if (result != null && resultado.Length > 0)
           {
               return result;
           }
        }
   }
   ...
}

It doesn't work (udpClient.Receive never returns information, it is similar to that there is no socket information yet), but if I open a software tool from my PC that allows me to write information to a UDP scoket, the code works wonderfully (udpClient.Receive captures the sent information.)

在此处输入图像描述

Any suggestions or comments?

    UdpClient client;
    IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, PORT);

private void Connect()
{
    client = new UdpClient(7000);
    client.Connect(endPoint);
    client.BeginReceive(ReceiveCallback, null);
}

    private void ReceiveCallback(IAsyncResult _result)
    {
        try
        {
            byte[] _data = client.EndReceive(_result, ref endPoint);
            socket.BeginReceive(ReceiveCallback, null);

            if (_data.Length < 4)
            {
                //disconnected
                return;
            }
    //now data is anything received and if you want to view it as a string do:
    string result = Encoding.Default.GetString(data);
    //you can also convert it to other things like ints, float, etc
        }
        catch
        {
            //disconnected
        }
    }

Thanks to @MarkusSafar's suggestion, I put the desktop app on another PC and from there it manages to capture the hardware message. I'm not sure why it doesn't work on my PC, but the next step is to test this same code for an app developed for Android (Xamarin), I hope it works there too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM