UDP发送消息
1.发送端
package shapes; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub try { // 创建DatagramSocket DatagramSocket ds = new DatagramSocket(); //创建数据并打包 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; while((line = br.readLine()) != null) { // 输入886取消发送数据 if(line.equals("886")) { break; } // 创建数据 byte[] bys = line.getBytes(); DatagramPacket dp = new DatagramPacket(bys,bys.length,InetAddress.getByName("192.168.90.114"),10086); // 发送数据 ds.send(dp); } // 关闭发送端 ds.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
2.接收端
package shapes; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class UDPDemo { public static void main(String[] args) { // TODO Auto-generated method stub try { // 创建DatagramSocket DatagramSocket ds = new DatagramSocket(10086); // 创建数据包 byte[] bys = new byte[1024]; DatagramPacket dp = new DatagramPacket(bys, bys.length); while(true) { // 接收数据 try { ds.receive(dp); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 解析数据包 System.out.println("数据是:" + new String(dp.getData(), 0, dp.getLength())); } //关闭接收端 //ds.close(); } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
3.结果:
参阅:https://www.bilibili.com/video/BV1vk4y117fU?p=348