Java中UDP协议的基本原理和简单用法

   UDP协议是非面向连接的,相对于TCP协议效率较高,但是不安全。UDP协议类似发信息的过程,不管接收方是在线还是关机状态,都会把信息发送出去。但是如果接收方不处于接收信息的状态,发送出去的数据包就会丢失。

convert()方法是用来转换字节数组和基本类型。

/**
 * 创建基于udp协议的服务接受端
 * @author wxisme
 *
 */

public class MyServer {

	public static void main(String[] args) throws IOException {
		//创建服务端端口
		DatagramSocket server = new DatagramSocket(9898);
		//准备接受数据的容器
		byte[] container = new byte[1024];
		//把数据封装成包
		DatagramPacket packet = new DatagramPacket(container, container.length);
		//接收数据
		server.receive(packet);
		//分析数据
		//byte[] data = packet.getData();
		double data = convert(packet.getData());
		int len = packet.getLength();
		//System.out.println(new String(data, 0, len));
		System.out.println(data);
		//释放资源
		server.close();
	}
	/**
	 * 转换为基本类型
	 * @param data
	 * @return
	 * @throws IOException 
	 */
	public static double convert(byte[] data) throws IOException {
		DataInputStream dis = new DataInputStream(
				new ByteArrayInputStream(data));
		double num = dis.readDouble();
		return num;
		
	}

}
/**
 * 创建基于udp协议的客户发送数据端
 * @author wxisme
 */

public class MyClient {

	public static void main(String[] args) throws IOException {
		//创建服务端端口
		DatagramSocket client = new DatagramSocket(6868);
		//准备数据
		//String str = "UDP Protocol";
		double num = 216.35;
		//byte[] data = str.getBytes();
		byte[] data = convert(num);
		//数据打包
		DatagramPacket packet = new DatagramPacket(
				data, data.length, new InetSocketAddress("localhost", 9898));
		//发送数据
		client.send(packet);
		//关闭资源
		client.close();
		System.exit(0);
	}
	
	/**
	 * 将基本类型转换成字节数组
	 * @param num
	 * @return
	 * @throws IOException 
	 */
	public static byte[] convert(double num) throws IOException {
		byte[] data = null;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream(bos);
		dos.writeDouble(num);
		dos.flush();
		
		data = bos.toByteArray();
		dos.close();
		
		return data;
		
	}

}
原文地址:https://www.cnblogs.com/wxisme/p/4393734.html