最近温故一下工做没有使用过的一些知识点,下面就是练习中使用的代码,提供给你们分享java
客户端服务器
// 客户端 public class UDPClient { public static void main(String[] args) throws IOException { DatagramSocket ds = null;// 定义接受数据的对象 byte[] data = new byte[1024]; // 开辟空间,接受数据 DatagramPacket dp = null; // 声明DatagramPacket对象 // 服务器端和客户端的要一致 ds = new DatagramSocket(9000); // 端口号 dp = new DatagramPacket(data, 1024); // 全部信息使用data保存 ds.receive(dp); // 接受数据 // dp的内容信息 String str = new String(dp.getData(), 0, dp.getLength()) + " from " + dp.getAddress().getLocalHost() + ":" + dp.getPort(); System.out.println(str);// 输出内容 } }
服务器端spa
// 服务端 public class UDPServer { public static void main(String[] args) throws IOException { DatagramSocket ds = null; DatagramPacket dp = null; ds = new DatagramSocket(3000); String str = "hello World!"; // 构造数据报包,用来将长度为 length 的包发送到指定主机上的指定端口号。 dp = new DatagramPacket(str.getBytes(), str.length(), InetAddress.getByName("localhost"), 9000); System.out.println("发送信息"); ds.send(dp); // 服务端发送消息 ds.close(); } }
总结code
1.UDP中主要使用的是数据报协议发送的。对象
2.UDP是属于不可靠协议,服务器端发送的消息,客户端不必定能收的到。get
3.UDP主要使用DatagramPacket和DatagramSocket两个类。io
4.DatagramPacket主要用于封装消息。class
5.DatagramSocket用于发送和接受消息。服务器端
7.注意
总结
运行的时候,须要先运行客户端,而后再运行服务器端。