1、简介
UDP(UserDatagramProtocol)是一个简单的面向消息的传输层协议。
UDP 是无连接的,知道对方的IP和端口号直接进行传输就行,不需要建立连接
UDP 不可靠,没有任何可靠机制,即便发送失败也不会返回任何错误信息
UDP 面向数据报,发多少就收多少,原样发送,交给UDP的报文,UDP不会拆分或合并
UDP 没有拥塞控制,网络出现的拥塞不会使源主机的发送速率降低。
UDP 支持一对一、一对多、多对一和多对多的交互通信
缓冲区:只有接收缓冲区,没有发送缓冲区,接收缓冲区满了,多的直接丢弃
2. 首部说明:
首部由四个字段构成,每个字段都是 2byte
源端口: 源端口号,需要对方回信时选用,不需要时全部置0.
目的端口:目的端口号,在终点交付报文的时候需要用到。
长度:UDP的数据报的长度(包括首部和数据)其最小值为8(只有首部),由于长度只有16位,所有UDP一次能发送的数据最大就是 64K
校验和:检测UDP数据报在传输中是否有错,有错则丢弃。
3. 回显服务器代码案例 echoServer
UdpServer
package echo; import java.net.*; import java.util.Arrays; import java.io.IOException; public class UdpServer { private static int PORT = 2222; private DatagramSocket socket; public UdpServer() throws SocketException { socket = new DatagramSocket(PORT); } public void start() throws IOException { byte[] bytes = new byte[2048]; DatagramPacket receivePacket = new DatagramPacket(bytes, bytes.length); socket.receive(receivePacket); System.out.printf("ClientAddress: %s\nClientPort: %d\n", receivePacket.getAddress(),receivePacket.getPort()); System.out.println("ClientData:"+ new String(receivePacket.getData(),"utf-8")); DatagramPacket sendPacket = process(receivePacket); socket.send(sendPacket); } public DatagramPacket process(DatagramPacket packet){ DatagramPacket packet1 = new DatagramPacket(packet.getData(),packet.getLength(), packet.getSocketAddress()); return packet1; } public static void main(String[] args) throws IOException { UdpServer server = new UdpServer(); server.start(); } }
UdpClient
package echo; import java.net.*; import java.io.IOException; import java.util.Scanner; public class UdpClient { public void start() throws IOException { DatagramSocket socket = new DatagramSocket(); byte[] bytes = new byte[2048]; System.out.println("请输入你想发送给服务器的信息:"); Scanner scanner = new Scanner(System.in); String str =scanner.nextLine(); bytes = str.getBytes(); DatagramPacket sendPacket = new DatagramPacket(bytes,bytes.length, new InetSocketAddress("localhost",2222)); socket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(new byte[2048],2048); socket.receive(receivePacket); System.out.println(new String(receivePacket.getData(),"utf-8")); } public static void main(String[] args) throws IOException { UdpClient client = new UdpClient(); client.start(); } }