什么是UDP
UDP是User Datagram Protocol的简称,中文名是用户数据报协议,是OSI参考模型中的传输层协议,它是一种无连接的传输层协议,提供面向事务的简单不可靠信息传送服务。
UDP的正式规范是IETF RFC768。UDP在IP报文的协议号是17。
简单的UPD代码demo
//不需要连接服务器
public class UdpClientDemo01 {
public static void main(String[] args) {
//建立一个Socket
DatagramSocket socket = null;
try{
socket = new DatagramSocket();
//建个包
String msg = "服务器你好,我是客户端信息";
//发生给谁
InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
DatagramPacket datagramPacket = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,inetAddress,9999);
//发生包
socket.send(datagramPacket);
}catch (Exception e) {
e.printStackTrace();
}finally {
//关闭流
if(socket != null)
socket.close();
}
}
}
//等待客户的连接
public class UdpServerDemo01 {
public static void main(String[] args) {
DatagramSocket socket = null;
try{
//开放端口
socket = new DatagramSocket(9999);
//接收数据
byte [] bytes = new byte[1024];
DatagramPacket datagramSocket = new DatagramPacket(bytes, 0, bytes.length);
socket.receive(datagramSocket);
System.out.println(new String(datagramSocket.getData(),0,datagramSocket.getLength()));
}catch (Exception e){
e.printStackTrace();
}finally {
if(socket != null)
socket.close();
}
}
}