//UdpReceive.java

/*
定义udp的接收端。
思路:
1.定义udpSocket服务。一般会监听一个端口,事实上就是这个接收网络应用程序定义一个数字标示。
2.定义一个数据包。用来存储接收到的字节数据。
由于数据包对象中有特有功能能够提取字节数据中不同数据信息。

3.通过Socket服务的receive方法将收到的数据存入已定义好的数据包中。 4.通过数据包对象的特有功能将这些不同的数据取出。打印到控制台上。 5.关闭资源。

*/ import java.net.*; public class UdpReceive { public static void main(String[] args) throws Exception { //1.创建udp socket,建立端点。 DatagramSocket ds =new DatagramSocket(10000); //2.定义数据包。用于存储数据。 byte[] buf = new byte[1024]; DatagramPacket dp =new DatagramPacket(buf,buf.length); //3.通过socket服务的receive方法将收到的数据存入数据包中。 ds.receive(dp); //4.通过数据包的方法获取当中的数据。

String ip = dp.getAddress().getHostAddress(); String data = new String(dp.getData(),0,dp.getLength()); int port = dp.getPort(); System.out.println(ip+":"+data+" port:"+port); //5.关闭资源。 ds.close(); } }


//UdpSend.java

/*
定义udp的发送端。

需求:通过udp传输方式。将一段文字数据发送出去。
思路:
1.建立UDPSocket服务。
2.提供数据。并将数据封装到数据包中。
3.通过socket服务的发送功能,将数据包发出去。
4.关闭资源。
*/
import java.net.*;

public class UdpSend
{
  public static void main(String[] args) throws Exception
  {
    //1.创建udp服务。通过DatagramSocket对象。
    DatagramSocket ds = new DatagramSocket(8888);

    //2.确定数据。并封装成数据包。
    byte[] buf = " 网络连通了!!!

".getBytes();//将一个字符串转化为一个字节数组 DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.111"),10000); //3.通过socket服务,将已有的数据包发送出去,通过send方法。 ds.send(dp); //4.关闭资源。 ds.close(); } }