###发送端
import java.io.IOException;
import java.net.*;
public class send {
public static void main(String[] args) throws IOException {
//1.获取套接字
DatagramSocket socket = new DatagramSocket();
//2.创建数据报包
DatagramPacket packet = new DatagramPacket("how are you ?".getBytes(), "how are you ?".length(), InetAddress.getByName("127.0.0.1"), 11111);
//3.发送数据报包
socket.send(packet);
//4.释放资源
socket.close();
}
}
###接收端
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class receive {
public static void main(String[] args) throws IOException {
//1.获取套接字对象
DatagramSocket socket = new DatagramSocket(11111);
//2.创建数据报包
DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
//3.接收数据报包,将数据报包放进新建的数据报包中
socket.receive(packet);
//4.从数据报包中获取数据,然后打印 (这个new String()具备解码功能)
System.out.println(new String(packet.getData(),0,packet.getLength()));
//5.释放资源
socket.close();
###下面的代码相当于第四步(把代码简写)
// InetAddress address = packet.getAddress();
// System.out.println(address);
//data数据需要通过new String()解码 byte[] data = packet.getData();
// int length = packet.getLength();
// String s = new String(data, 0, length);
// System.out.println(s);
}
}