| byte[] buf = new byte[1000]; 
 DatagramSocket ds = new DatagramSocket(12345);
 
 //开始监视12345端口
 
 DatagramPacket ip = new DatagramPacket(buf, buf.length);
 
 //创建接收数据报的实例
 
 while (true)
 
 {
 
 ds.receive(ip);
 
 //阻塞,直到收到数据报后将数据装入IP中
 
 System.out.println(new String(buf));
 
 }
 
 {发送数据的客户端}
 
 InetAddress target = InetAddress.getByName(“www.xxx.com“);
 
 //得到目标机器的地址实例
 
 DatagramSocket ds = new DatagramSocket(9999);
 
 //从9999端口发送数据报
 
 String hello = “Hello, I am come in!”;
 
 //要发送的数据
 
 byte[] buf = hello.getBytes();
 
 //将数据转换成Byte类型
 
 op = new DatagramPacket(buf, buf.length, target, 12345);
 
 //将BUF缓冲区中的数据打包
 
 ds.send(op);
 
 //发送数据
 
 ds.close();
 
 //关闭连接
 希望对你有帮助
 |