UDP基本概念
用户数据报协议(UDP)是 OSI 参考模型中一种无连接的传输层协议,提供面向事务的简单不可靠信息传送服务。 UDP 协议基本上是 IP 协议与上层协议的接口。 UDP 协议适用端口分别运行在同一台设备上的多个应用程序。
UDP协议有如下的特点:
1、UDP传送数据前并不与对方建立连接,即UDP是无连接的,在传输数据前,发送方和接收方相互交换信息使双方同步。
2、UDP不对收到的数据进行排序,在UDP报文的首部中并没有关于数据顺序的信息(如TCP所采用的序号),而且报文不一定按顺序到达的,所以接收端无从排起。
3、UDP对接收到的数据报不发送确认信号,发送端不知道数据是否被正确接收,也不会重发数据。
4、UDP传送数据较TCP快速,系统开销也少。
从以上特点可知,UDP提供的是无连接的、不可靠的数据传送方式,是一种尽力而为的数据交付服务。
Java使用UDP服务实现数据的传输
package javase.day18;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UdpDemo {
public static void main(String[] args) throws Exception {
//输出本机的主机名和IP地址
System.out.println(InetAddress.getLocalHost());
}
}
class UdpSend{
public static void main(String[] args) throws Exception{
//通过DatagramSocket对象创建UDP服务
DatagramSocket ds= new DatagramSocket();
//确定数据,并封装成数据包
byte[] buf="hello world".getBytes();
DatagramPacket dp = new DatagramPacket(buf,0,buf.length,InetAddress.getByName("192.168.1.2"),10000);
//通过socket服务,将已有的数据包发送出去
ds.send(dp);
//关闭资源
ds.close();
}
}
class UdpReceive{
public static void main(String[] args) throws Exception{
//通过DatagramSocket对象创建UDP服务
DatagramSocket ds= new DatagramSocket(10000);
//定义数据包用于存储数据
byte[] buf= new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,0,buf.length);
//通过服务的receive方法将收到的数据存入数据包中
ds.receive(dp);
//通过数据包中的方法获取其中的数据
int port=dp.getPort();
String receiveData=new String(dp.getData(),0,dp.getLength());
System.out.println("port:"+port+" data:"+receiveData);
//关闭资源
ds.close();
}
}
相关链接
http://www.javvin.com/protocol/rfc768.pdf:User Datagram Protocol(UDP) Specifications
http://www.iana.org/assignments/port-numbers:UDP and TCP port numbers