Sunday, May 30, 2010

programs on user datagram protocol

10.3 User Datagram Protocol


UDP is not very reliable (but fast) connectionless protocol.

Example. The UDPServer1.cs file is given by

// UDPServer1.cs

using System;

using System.Net;

using System.Net.Sockets;

using System.Text;

using System.Configuration;

class ServerUDP

{

public static void Main()

{

UdpClient udpc = new UdpClient(2055);

Console.WriteLine("Server started servicing on port 2055");

IPEndPoint ep = null;

while(true)

{

byte[] rdata = udpc.Receive(ref ep);

string name = Encoding.ASCII.GetString(rdata);

string job = ConfigurationManager.AppSettings[name];

if(job==null) job = "No such employee";

byte[] sdata = Encoding.ASCII.GetBytes(job);

udpc.Send(sdata,sdata.Length,ep);

} // end while

} // end Main

}

The xml-file UDPServer1.exe.config is given by

















146 CHAPTER 10. SOCKETS PROGRAMMING

The UDPClient1.cs file is given by

// UDPClient1.cs

using System;

using System.Net;

using System.Net.Sockets;

using System.Text;

class ClientUDP

{

public static void Main()

{

UdpClient udpc = new UdpClient("152.106.40.84",2055);

IPEndPoint ep = null;

while(true)

{

Console.Write("Name: ");

string name = Console.ReadLine();

if(name == "") break;

byte[] sdata = Encoding.ASCII.GetBytes(name);

udpc.Send(sdata,sdata.Length);

byte[] rdata = udpc.Receive(ref ep);

string job = Encoding.ASCII.GetString(rdata);

Console.WriteLine("job = " + job);

} // end while

} // end Main

}

We include an xml-file (UDPServer1.exe.config) on the Server side we can query

from the Client. On the Server side we first compile

csc UDPServer1.cs

Next we compile the Client side

csc UDPClient1.cs

Then on the Server side we start running the exe-file UDPServer1 and finally we

start the exe-file UDPClient1 on the Client side.

No comments:

Post a Comment