Adam
Adam

Reputation: 81

UDPclient in WinForms?

I have used this code example, http://msdn.microsoft.com/en-us/library/tst0kwb1.aspx, to make a console UDP server capable of receiving and sending messages.

But I do not want this to a be a console application, I want to use Forms. I have successfully implemented the sending messages feature in my application, but I do not know how to make the listener work.

Here is the code for receiving messages, it doesn't do anything.
Note: I put this code right under the button click event code.

private void StartListener()
    {
        bool done = false;
        UdpClient listener = new UdpClient(listenPort);
        IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);

        try
        {
            while (!done)
            {
                this.lblMessage.Text = "Waiting for broadcast";
                byte[] bytes = listener.Receive(ref groupEP);

                this.lblRecieve.Text = Encoding.ASCII.GetString(bytes, 0, bytes.Length);
            }

        }
        catch (Exception e)
        {
            this.lblMessage.Text = e.ToString();
        }
        finally
        {
            listener.Close();
        }
    }

This code is obviously wrong, but I have never done anything in C# before and this console sample code was the only guide I could find about UDP servers.

Here is the code for sending messages, it works perfectly.

private void btnSend_Click(object sender, EventArgs e)
    {
        Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        IPAddress broadcast = IPAddress.Parse("192.168.0.105");
        byte[] sendbuf = Encoding.ASCII.GetBytes("test");
        IPEndPoint ep = new IPEndPoint(broadcast, listenPort);
        s.SendTo(sendbuf, ep);
        this.lblMessage.Text = "Sent Message";
    }

EDIT:

I appreciate the help I have got from you, but instead of tweaking my own broken code to work, I found another code to tweak so that it works like I want.

UDP datagram code for server client application in C#

This is the code I borrowed and it works perfectly, except that stop() doesn't work properly, but it's not a major problem and shouldn't be hard to fix with google.

I still learnt a lot from the links you guys gave me.

Upvotes: 0

Views: 3059

Answers (2)

Hans Passant
Hans Passant

Reputation: 941218

It probably works, you just can't see it. You hang up the UI thread with an endless loop, the form goes entirely dead. Won't paint either so you can't see the label updates.

You'll need to either start using UdpClient.BeginReceive() or create a thread to run this code. If you use a thread then you'll need to use Control.BeginInvoke() to update the label.

Upvotes: 3

Chathuranga Chandrasekara
Chathuranga Chandrasekara

Reputation: 20906

You would have to register a listener. Just check the following article.

Events Tutorial

Upvotes: 0

Related Questions