一、UDP简介
UDP 为应用程序提供了一种无需建立连接就可以发送封装的 IP 数据报
的方法。
- 特点:无连接、不可靠、快速传输。
- 类别:传输层协议。
- 用途:发送IP数据包。
- UDP并不像TCP一样严格区分客户端与服务端,而是接收端和发送端。
二、模拟UDP网络通信
接收端:
package 模拟UDP协议下的网络通信;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class Receive接收端 {
public static void main(String[] args) throws IOException {
System.out.println("接收端已开启");
// 创建Receive接收端DatagramSocket对象
DatagramSocket ds = new DatagramSocket(777);
// 为数据包设置参数
byte[] buf = new byte[100];
int length = buf.length;
// 数据包
DatagramPacket p = new DatagramPacket(buf, length);
// 接收数据(阻塞的)
ds.receive(p);
byte[] data = p.getData();
System.out.println(new String(data));
// 关闭流对象
ds.close();
}
}
发送端:
package 模拟UDP协议下的网络通信;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketAddress;
import java.net.SocketException;
public class Send发送端 {
public static void main(String[] args) throws IOException {
System.out.println("发送端已开启");
// 创建send发送端DatagramSocket对象
DatagramSocket ds = new DatagramSocket();
String str = "Good morning!";
// 为数据包设置参数
byte[] buf = str.getBytes();
int length = buf.length;
InetAddress address = InetAddress.getByName("10.255.96.129");
int port = 777;
// 数据包
DatagramPacket p = new DatagramPacket(buf, length, address, port);
// 发送数据
ds.send(p);
// 关闭流对象
ds.close();
}
}
程序运行后在接收端接到了发送端的信息。