package test; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class Server { public static void main(String[] args) throws IOException { DatagramSocket ds=new DatagramSocket(3000); String str="Hello"; DatagramPacket dp=new DatagramPacket(str.getBytes(),str.length(),InetAddress.getByName("localhost"),9000); ds.send(dp); ds.close(); } }
package test; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; public class Client{ public static void main(String args[]) throws IOException{ DatagramSocket ds=new DatagramSocket(9000); byte b[]=new byte[1024]; DatagramPacket dp=new DatagramPacket(b,1024); ds.receive(dp); String str=new String(dp.getData(),0,dp.getLength())+"from"+dp.getAddress().getHostAddress()+":"+dp.getPort(); System.out.println(str); ds.close(); } };