title: UDPclient in WinForms?
body: <p>I have used this code example, <a href="http://msdn.microsoft.com/en-us/library/tst0kwb1.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/tst0kwb1.aspx</a>, to make a console UDP server capable of receiving and sending messages. </p>
  
  <p>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.</p>
  
  <p>Here is the code for receiving messages, it doesn't do anything.<br>
  Note: I put this code right under the button click event code.</p>
  
  <pre><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();
          }
      }
  </code></pre>
  
  <p>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.</p>
  
  <p>Here is the code for sending messages, it works perfectly.</p>
  
  <pre><code>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";
      }
  </code></pre>
  
  <p>EDIT:</p>
  
  <p>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.</p>
  
  <p><a href="https://stackoverflow.com/questions/10076658/udp-datagram-code-for-server-client-application-in-c-sharp">UDP datagram code for server client application in C#</a></p>
  
  <p>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.</p>
  
  <p>I still learnt a lot from the links you guys gave me.</p>