import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; //================================================= // File Name : UDPServer_demo //------------------------------------------------------------------------------ // Author : Common //主类 //Function : UDPServer_demo public class UDPServer_demo { public static void main(String[] args) throws Exception{ // TODO 自动生成的方法存根 DatagramSocket ds = null; //声明DatagramSocket对象 DatagramPacket dp = null; //声明DatagramPacket对象 ds = new DatagramSocket(3000); String str = "HelloWord"; dp = new DatagramPacket(str.getBytes(),str.length(),InetAddress.getByName("localhost"),9000); System.out.println("发送信息"); ds.send(dp); ds.close(); } }
import java.net.DatagramPacket; import java.net.DatagramSocket; //================================================= // File Name : UDPClient_demo //------------------------------------------------------------------------------ // Author : Common //主类 //Function : UDPClient_demo public class UDPClient_demo { public static void main(String[] args) throws Exception{ // TODO 自动生成的方法存根 DatagramSocket ds = null; //声明DatagramSocket对象 byte[] buf = new byte[1024]; //定义接收数据的字节数据 DatagramPacket dp = null; //声明DatagramPacket对象 ds = new DatagramSocket(9000); //此客户端在9000端口监听 dp = new DatagramPacket(buf,1024); //指定接收数据的长度为1024 System.out.println("等待接收数据"); ds.receive(dp); //接收数据 String str = new String(dp.getData(),0,dp.getLength())+" from" +dp.getAddress().getHostAddress()+" : "+dp.getPort(); //接收数据 System.out.println(str); //输出数据 ds.close(); } }
时间: 2024-12-28 12:31:45