Electrofriends

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

by Ranjith | April 30th, 2010.

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();
	}
}

Share and Enjoy:
  • Digg
  • Technorati
  • StumbleUpon
  • Twitter
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Reddit
  • Mixx
  • Yahoo! Buzz
  • LinkedIn
  • NewsVine
  • RSS
  • email
Similar Posts:

Leave a Reply

Share and enjoy

    • Digg
    • Facebook
    • Technorati
    • StumbleUpon
    • Twitter
    • Reddit
    • del.icio.us
    • Yahoo! Buzz
Copyright©2009 www.electrofriends.com All Rights Reserved. Powered by Dhyeya