PROWAREtech

articles » current » dot-net » tutorial » sockets » page-2

.NET: TCP/IP Sockets API Tutorial - Page 2 - UDP Sockets

Using the UdpClient class in C#.

UDP Sockets

UDP is more efficient than TCP having less overhead making it ideal for small communications between client and server. There is one .NET class used by both the server and client: UdpClient.

UdpClient for Server Applications

  1. Create a UdpClient object and specify the port to listen on.
  2. Use the Receive() method to receive a datagram packet.
  3. The Receive() method has a reference to an IPEndPoint object as an argument.
  4. Send and receive datagram packets using the Send() and Receive() methods.
using System;
using System.Net;
using System.Net.Sockets;

class UdpServerExample
{
	static void Main()
	{
		WaitClient();
	}

	static private void WaitClient()
	{
		int port = 1234;

		Console.WriteLine("Listening...");
		try
		{
			using (UdpClient client = new UdpClient(port))
			{
				IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 0);

				while (true)
				{
					try
					{
						byte[] bytes = client.Receive(ref ipep);
						Console.WriteLine("Connected to client " + ipep.ToString());

						// simply send an echo of the datagram that the client sent
						client.Send(bytes, bytes.Length, ipep);
						Console.WriteLine("{0} bytes sent", bytes.Length);
					}
					catch (Exception ex)
					{
						Console.WriteLine(ex.Message);
					}
				}
			}
		}
		catch (Exception ex)
		{
			Console.WriteLine(ex.Message);
		}
	}
}

UdpClient for Client Applications

  1. Create a UdpClient object.
  2. Use the Send() and Receive() methods to exchange datagrams.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

class UdpClientExample
{
	static void Main()
	{
		ConnectToServer("hello");
		while (true)
		{
			Console.Write("ENTER MESSAGE: ");
			string echo = Console.ReadLine();
			ConnectToServer(echo);
		}
	}

	static private void ConnectToServer(string message)
	{
		string server = "localhost";
		int port = 1234;

		byte[] msg = Encoding.ASCII.GetBytes(message);

		try
		{
			using (UdpClient client = new UdpClient())
			{
				// send the string to the server and it will be echoed back
				client.Send(msg, msg.Length, server, port);

				IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 0);

				byte[] recvd = client.Receive(ref ipep);

				Console.WriteLine(Encoding.ASCII.GetString(recvd));
			}
		}
		catch (Exception ex)
		{
			Console.WriteLine(ex.Message);
		}
	}
}
<<<[Page 2 of 3]>>>

PROWAREtech

Hello there! How can I help you today?
Ask any question

PROWAREtech

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
ACCEPT REJECT