0

I have a simple UDP Client pointing to 127.0.0.1:15000 and I have a Provider who sends me information through UDP and he says, he broadcasts the signals through the network and that he does not know what clients are listening and that I should be able to receive the signals if I point to the correct port. I know this sounds a little confusing, but what is wrong here? Is my provider wrong or I am not listening correctly to the broadcast?

    private int port;
    private UdpClient udp;
    public UdpReceiver(int port)
    {
        this.port = port;
        udp = new UdpClient(port);
        StartListening();
    }
    private void StartListening()
    {
        this.udp.BeginReceive(Receive, new object());
    }
    private void Receive(IAsyncResult ar)
    {
        if (udp != null)
        {
            IPEndPoint ip = new IPEndPoint(IPAddress.Any, port);
            byte[] bytes = udp != null ? udp.EndReceive(ar, ref ip) : null;
            if (bytes != null)
            {
                string message = Encoding.ASCII.GetString(bytes);
                MessageBox.Show(message);
                StartListening();
            }
        }
    }
Joe Almore
  • 4,036
  • 9
  • 52
  • 77

1 Answers1

0

There are a few issues with your code.

First of all, use new AsyncCallback(Receive) instead of Receive as BeginReceive param.

Second, by default socket is created with broadcast send/receive being disabled. Turn it on with udp.EnableBroadcast = true; before StartListening in constructor.

Third, Receive method would run at thread pool thread, and you can't easily call MessageBox.Show there. Substitute it with Console.Write for testing and get informed about the topic.

lilo0
  • 895
  • 9
  • 12