DatagramSocket and DatagramPacket (Client-Server Program using UDP/IP)

Program : DatagramSocket and DatagramPacket (Client-Server Program using UDP/IP)
By : Kapil Lohia

Program 1 :

 
import java.net.*;
 
class udpip_server
{
	public static DatagramSocket ds;
	public static byte buffer[]=new byte[1024];
 
	public static void Myserver() throws Exception
	{
		int pos=0;
		while(true)
		{
			int c=System.in.read();
			switch(c)
			{
				case -1: System.out.println("Server quits");
				return;
				case '\r':break;
				case '\n':ds.send(new DatagramPacket(buffer,pos,InetAddress.getLocalHost(),777));
				           pos=0;
				break;
				default:
				buffer[pos++]=(byte) c;
			}
		}
	}
 
	public static void main(String args[]) throws Exception
	{
		System.out.println("Server ready..\n Please type here");
		ds=new DatagramSocket(888);
		Myserver();
	}
}

Program 2:

 
import java.net.*;
 
class udpip_client
{
	public static DatagramSocket ds;
	public static byte buffer[]=new byte[1024];
 
	public static void Myclient() throws Exception
	{
		while(true)
		{
			DatagramPacket p=new DatagramPacket(buffer,buffer.length);
			ds.receive(p);
			System.out.println(new String(p.getData(),0,p.getLength()));
		}
	}
 
	public static void main(String args[]) throws Exception
	{
		System.out.println("Client - Press CTRL+C to quit");
		ds=new DatagramSocket(777);
		Myclient();
	}
}

5 Responses to “DatagramSocket and DatagramPacket (Client-Server Program using UDP/IP)”

Leave a Reply