locked
Simple UDP example code RRS feed

  • Question

  • In my quest to figure out how to use UDP and networking, I have found some example code and simplified and simplified it further.  The two examples below are a talker and a listener.  To use them, create a console application within C# Express and paste the code from here into and replacing the initial code that Express creates.  Build it and run it.  Run both the talker and listener at the same time.  Run both on multiple computers that are on the same LAN.  Each sent message should be received by all listener programs on all computers.  I have a problem with one of my computers as noted in a related post, but I am reasonably sure that is not a defect in these two programs.

    Do the readers think that this is worth putting somewhere for easy access?  Does anyone have any comments for improvement.  Remember, this is to be as simple to understand as possible.  Other than a catch statement there is no error checking or validation to cloud the concepts.

    The original came from some Microsoft Express help files that I found somewhere and cannot find again.  While it may sound pompous, I hold or claim no copyright and give usage to anyone and everyone.  Do I need to say this?

    In the talker code I defined a few regions around the comments so they can be hidden making the code easier to see.

    I went through the code one time restoring indents, but did not get it right and it looked worse than before the edits.  I did a test and found that when I copied the code from a post and paste it into C#, the editor formats and indents it.  That said, I will leave it in a left jusitified format in this post.

    Here is the talker



     
    /*
    * The purpose of this program is to provide a minimal example of using UDP to
    * send data.
    * It transmits broadcast packets and displays the text in a console window.
    * This was created to work with the program UDP_Minimum_Listener.
    * Run both programs, send data with Talker, receive the data with Listener.
    */

    using System;

    using System.Net;

    using System.Net.Sockets;

    using System.Text;

    class Program

    {
    static void Main(string[] args)
    {
    Boolean done = false;
    Boolean exception_thrown = false;

    #region comments
    // Create a socket object. This is the fundamental device used to network

    // communications. When creating this object we specify:

    // Internetwork: We use the internet communications protocol

    // Dgram: We use datagrams or broadcast to everyone rather than send to

    // a specific listener

    // UDP: the messages are to be formated as user datagram protocal.

    // The last two seem to be a bit redundant.

    #endregion

    Socket sending_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
    ProtocolType.Udp);

    #region comments
    // create an address object and populate it with the IP address that we will use

    // in sending at data to. This particular address ends in 255 meaning we will send

    // to all devices whose address begins with 192.168.2.

    // However, objects of class IPAddress have other properties. In particular, the

    // property AddressFamily. Does this constructor examine the IP address being

    // passed in, determine that this is IPv4 and set the field. If so, the notes

    // in the help file should say so.

    #endregion

    IPAddress send_to_address = IPAddress.Parse("192.168.2.255");

    #region comments
    // IPEndPoint appears (to me) to be a class defining the first or final data

    // object in the process of sending or receiving a communications packet. It

    // holds the address to send to or receive from and the port to be used. We create

    // this one using the address just built in the previous line, and adding in the

    // port number. As this will be a broadcase message, I don't know what role the

    // port number plays in this.

    #endregion

    IPEndPoint sending_end_point = new IPEndPoint(send_to_address, 11000);

    #region comments
    // The below three lines of code will not work. They appear to load

    // the variable broadcast_string witha broadcast address. But that

    // address causes an exception when performing the send.

    //

    //string broadcast_string = IPAddress.Broadcast.ToString();

    //Console.WriteLine("broadcast_string contains {0}", broadcast_string);

    //send_to_address = IPAddress.Parse(broadcast_string);

    #endregion

    Console.WriteLine("Enter text to broadcast via UDP.");
    Console.WriteLine("Enter a blank line to exit the program.");
    while (!done)
    {
    Console.WriteLine("Enter text to send, blank line to quit");
    string text_to_send = Console.ReadLine();
    if (text_to_send.Length == 0)
    {
    done =
    true;
    }
    else

    {
    // the socket object must have an array of bytes to send.

    // this loads the string entered by the user into an array of bytes.

    byte[] send_buffer = Encoding.ASCII.GetBytes(text_to_send);

    // Remind the user of where this is going.

    Console.WriteLine("sending to address: {0} port: {1}",
    sending_end_point.Address,
    sending_end_point.Port );
    try

    {
    sending_socket.SendTo(send_buffer, sending_end_point);
    }
    catch (Exception send_exception )
    {
    exception_thrown =
    true;
    Console.WriteLine(" Exception {0}", send_exception.Message);
    }
    if (exception_thrown == false)
    {
    Console.WriteLine("Message has been sent to the broadcast address");
    }
    else

    {
    exception_thrown =
    false;
    Console.WriteLine("The exception indicates the message was not sent.");
    }
    }
    }
    // end of while (!done)

    } // end of main()

    } // end of class Program
     


     

    Here is the listener



    /*
    * The purpose of this program is to provide a minimal example of using UDP to
    * receive data.
    * It picks up broadcast packets and displays the text in a console window.
    * This was created to work with the program UDP_Minimum_Talker.
    * Run both programs, send data with Talker, receive the data with Listener.
    * Run multiple copies of each on multiple computers, within the same LAN of course.
    * If the broadcast packet contains numbers or binary data or anything other than
    * plain text it may well crash and burn.
    * Adding code to handle unexpected conditions such as that would defeat the
    * simplistic nature of this example program. So would adding code for a gracefull
    * exit. Just kill it.
    */

    using System;

    using System.Net;

    using System.Net.Sockets;

    using System.Text;

    public class UDPListener

    {
    private const int listenPort = 11000;
    public static int Main()
    {
    bool done = false;
    UdpClient listener = new UdpClient(listenPort);
    IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
    string received_data;
    byte[] receive_byte_array;
    try

    {
    while (!done)
    {
    Console.WriteLine("Waiting for broadcast");
    // this is the line of code that receives the broadcase message.

    // It calls the receive function from the object listener (class UdpClient)

    // It passes to listener the end point groupEP.

    // It puts the data from the broadcast message into the byte array

    // named received_byte_array.

    // I don't know why this uses the class UdpClient and IPEndPoint like this.

    // Contrast this with the talker code. It does not pass by reference.

    // Note that this is a synchronous or blocking call.

    receive_byte_array = listener.Receive(ref groupEP);
    Console.WriteLine("Received a broadcast from {0}", groupEP.ToString() );
    received_data =
    Encoding.ASCII.GetString(receive_byte_array, 0, receive_byte_array.Length);
    Console.WriteLine("data follows \n{0}\n\n", received_data);
    }
    }
    catch (Exception e)
    {
    Console.WriteLine(e.ToString());
    }
    listener.Close();
    return 0;
    }
    }
    // end of class UDPListener

     

    Thursday, December 28, 2006 5:39 PM

All replies

  • Thank you for posting this.

     

    Mariya

    Wednesday, March 28, 2007 7:25 PM
    Moderator
  • The basics are here but I disagree with some of the comments. The fact that you said that the program will 'crash and burn' if you send anything other than 'plain text' means you have to question your knowledge of data types. Anything can be represented as 'plain text', because really, plain text is just a string of bytes. A number, a picture, a sound, are all collections of bytes and can be sent over a network.

    Just one way to improve it also, I am unsure of how to gather the correct information but with the router's IP and the subnet mask, you should be able to automatically generate a broadcast address which would make this program a lot better.

    Wednesday, December 22, 2010 8:31 PM
  • Man, this thread is more that 3 years old.

    Replying to such an old thread with pedantic comments means you have to question your knowledge of internet forums.


    Luc Morin, T.P. http://www.stlm.ca
    Saturday, December 25, 2010 3:04 PM
  • Hey Luc, thanks for teaching me the word pedantic, a perfect word for us crazy, attention deficit disordered programmers.
    Javaman
    Monday, December 27, 2010 10:06 AM
  • Thank you so much for this. I wrote a few programs using TCP sockets but wanted to switch to UDP for a boost in speed. For some reason I could never get it to work, but your code worked perfectly! I only had to change the IP address for the UDP Talker to match my network. Now I will be able to update my programs using your code as an example.
    Friday, December 28, 2012 1:43 AM