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; } }
作者:Pickle
声明:对于转载分享我是没有意见的,出于对博客园社区和作者的尊重一定要保留原文地址哈。
致读者:坚持写博客不容易,写高质量博客更难,我也在不断的学习和进步,希望和所有同路人一道用技术来改变生活。觉得有点用就点个赞哈。
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112835275-168981902.gif)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112841431-2047172832.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112847494-1544911856.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112904385-918783221.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111120143119-1302805212.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112856369-1466718103.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112830416-794416355.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111113919510-1155220901.gif)