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();
}
} |
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();
}
} |
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();
}
}
Editorial Team
We are a group of young techies trying to provide the best study material for all Electronic and Computer science students. We are publishing Microcontroller projects, Basic Electronics, Digital Electronics, Computer projects and also c/c++, java programs.
plzz explain the output
plzz explain the output for this program