Hello, in this article I am going to show you how we can implement UDP through C#. So, UDP stands for User Datagram Protocol and it is a connectionless protocol. It uses datagrams instead of streams. It is an alternative Protocol to Transmission Control Protocol (TCP).
Implementation of UDP using C#,
// Server-Side Implementation Of UDP using c#:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Configuration;
class OfficeUDPServer
{
public static void Main()
{
UdpClient udpc = new UdpClient(7878);
Console.WriteLine("Server Started and servicing on port no. 7878");
IPEndPoint ep = null;
while (true){
byte[] receivedData = udpc.Receive(ref ep);
string studentName = Encoding.ASCII.GetString(receivedData);
string msg = ConfigurationSettings.AppSettings[OfficeName];
if (msg == null) msg = "No such Office available for conversation";
byte[] sdata = Encoding.ASCII.GetBytes(msg);
udpc.Send(sdata, sdata.Length, ep);
}
}
}
// Client-Side Implementation Of UDP using c#:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class OfficeUDPClient
{
public static void Main(string[] args)
{
UdpClient udpc = new UdpClient("PC-NAME", 7878);
IPEndPoint ep = null;
while (true)
{
Console.Write("Enter Your Office Name: ");
string studentName = Console.ReadLine();
// Check weather Office entered name to start conversation
if (OfficeName == ""){
Console.Write("You did not enter your name. Closing...");
break;
}
// Data to send
byte[] msg = Encoding.ASCII.GetBytes(OfficeName);
udpc.Send(msg, msg.Length);
// received Data
byte[] rdata = udpc.Receive(ref ep);
string bp = Encoding.ASCII.GetString(rdata);
Console.WriteLine(bp);
}
}
}
It is very useful for servers answering small queries for a large number of clients. Hope it will help you.
Thanks.