datagrampacket datagramsocket
program based on client-server in java.
server program save in one file:
import java.net.*;
class hi_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();
}
}
client program save in as different java file
import java.net.*;
class hi_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();
}
}
output of the program:
server program save in one file:
import java.net.*;
class hi_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();
}
}
client program save in as different java file
import java.net.*;
class hi_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();
}
}
output of the program:
Comments
Post a Comment