11.13 Communicate Using UDP


Problem

You need to send data between two computers on a network using a User Datagram Protocol (UDP) stream.

Solution

Use the System.Net.Sockets.UdpClient class, and use two threads: one to send data and the other to receive it.

Discussion

UDP is a connectionless protocol that doesn't include any flow control or error checking. Unlike TCP, UDP shouldn't be used where reliable communication is required. However, because of its lower overhead, UDP is often used for "chatty" applications where it's acceptable to lose some messages. For example, imagine you want to create a network in which individual clients send information about the current temperature at their locations to a server every few minutes. You might use UDP in this case because the communication frequency is high and the damage caused by losing a packet is trivial (because the server can just continue to use the last received temperature reading).

The application shown in the following code uses two threads: one to receive messages and one to send them. To test this application, load two instances at the same time. On computer A, specify the IP address for computer B. On computer B, specify the address for computer A. You can then send text messages back and forth at will. (You can simulate a test on a single computer by using two different ports and the loopback IP address 127.0.0.1.)

 using System; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; public class UdpTest {     private static int localPort;     private static void Main() {         // Define endpoint where messages are sent.         Console.Write("Connect to IP: ");         string IP = Console.ReadLine();         Console.Write("Connect to port: ");         int port = Int32.Parse(Console.ReadLine());         IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP),            port);         // Define local endpoint (where messages are received).         Console.Write("Local port for listening: ");         localPort = Int32.Parse(Console.ReadLine());         Console.WriteLine();         // Create a new thread for receiving incoming messages.         Thread receiveThread = new Thread(           new ThreadStart(ReceiveData));         receiveThread.IsBackground = true;         receiveThread.Start();         UdpClient client = new UdpClient();         try {             string text;             do {                 text = Console.ReadLine();                 // Send the text to the remote client.                 if (text != "") {                     // Encode the data to binary using UTF8 encoding.                     byte[] data = Encoding.UTF8.GetBytes(text);                     // Send the text to the remote client.                     client.Send(data, data.Length, remoteEndPoint);                 }             } while (text != "");         } catch (Exception err) {             Console.WriteLine(err.ToString());         }         Console.ReadLine();     }     private static void ReceiveData() {         UdpClient client = new UdpClient(localPort);         while (true) {             try {                 // Receive bytes.                 IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);                 byte[] data = client.Receive(ref anyIP);                 // Convert bytes to text using UTF8 encoding.                 string text = Encoding.UTF8.GetString(data);                 // Display the retrieved text.                 Console.WriteLine(">> " + text);             } catch (Exception err) {                 Console.WriteLine(err.ToString());             }         }     } } 

Notice that UDP applications can't use the NetworkStream abstraction that TCP applications can. Instead, they must convert all data to a stream of bytes using an encoding class, as described in recipe 2.2.

You can test this application with clients on the local computer using the loopback alias 127.0.0.1, provided you use different listening ports. For example, imagine a situation with two UDP clients, client A and client B. Here's a sample transcript for client A:

 Connect to IP: 127.0.0.1 Connect to port: 8001 Local port for listening: 8080 Hi there! 

And here's the corresponding transcript for client B (with the received message):

 Connect to IP: 127.0.0.1 Connect to port: 8080 Local port for listening: 8001 >> Hi there! 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net