9.UDP
发短信:不用连接,需要知道对方的地址!就像发射导弹,我需要知道轰炸地点,但不需要告诉对方,秘密轰炸,嘿嘿。
需要了解DatagramPacket,DatagramSocket两个类
发送端:
1 package com.Inet.lesson3; 2 3 import java.net.DatagramPacket; 4 import java.net.DatagramSocket; 5 import java.net.InetAddress; 6 7 //不需要连接服务器 8 public class UdpClientDemo01 { 9 public static void main(String[] args) throws Exception { 10 //1.建立一个Socket 11 DatagramSocket socket = new DatagramSocket(); 12 13 //2.建个包 14 String msg = "你好啊,服务器"; 15 16 //发送给谁 17 InetAddress localhost = InetAddress.getByName("localhost"); 18 int port = 9090; 19 DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port); 20 21 //3.发送包 22 socket.send(packet); 23 24 //4.关闭流 25 socket.close(); 26 } 27 }
接收端
1 package com.Inet.lesson3; 2 3 import java.net.DatagramPacket; 4 import java.net.DatagramSocket; 5 6 //还是要等待客户端的链接! 7 public class UdpServerDemo01 { 8 public static void main(String[] args) throws Exception { 9 //开放端口 10 DatagramSocket socket = new DatagramSocket(9090); 11 12 //接收数据包 13 byte[] buffer = new byte[1024]; 14 DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);//接收 15 16 socket.receive(packet);//阻塞接收 17 18 System.out.println(packet.getAddress().getHostAddress()); 19 System.out.println(new String(packet.getData(), 0, packet.getLength())); 20 21 //关闭连接 22 socket.close(); 23 } 24 } 25 26 //先启动接收端,再启动发送端 27 结果: 28 127.0.0.1 29 你好啊,服务器