UDP通讯简单案例、单条消息发送、多次消息发送
// 单条发送
1 public static void main(String[] args) throws Exception { 2 System.out.println("==============客户端启动============"); 3 // 创建发送对象、发送端自带默认端口号, 4 DatagramSocket socket = new DatagramSocket(); 5 // 可以自己设置端口号 6 //DatagramSocket socket = new DatagramSocket(6666); 7 // 创建一个数据包对象封装数据 8 /** 9 * public DatagramPacket(byte buf[], int length, InetAddress address, int port) 10 * 参数一:封装要发送的数据 11 * 参数二:发送数据的大小 12 * 参数三:服务端的主句IP地址 13 * 参数四:服务端的端口 14 */ 15 byte[] buffer = "天王盖地虎啊盖地虎~" .getBytes(); 16 DatagramPacket packet = new DatagramPacket(buffer, buffer.length, InetAddress.getLocalHost(), 8888); 17 // 发送数据出去 18 socket.send(packet); 19 socket.close(); 20 }
1 public static void main(String[] args) throws Exception { 2 System.out.println("==============服务器端启动============"); 3 // 创建接收对象 4 DatagramSocket socket = new DatagramSocket(8888); 5 // 创建数据包接收对象 6 byte[] buffer = new byte[1024 * 61]; 7 DatagramPacket packet = new DatagramPacket(buffer, buffer.length, InetAddress.getLocalHost(), 8888); 8 // 接收数据 9 socket.receive(packet); 10 11 // 取到数据即可 12 int len = packet.getLength(); 13 String s = new String(buffer, 0, len); 14 System.out.println("收到了:" + s); 15 16 // 获取对方IP 17 String ip = packet.getSocketAddress().toString(); 18 System.out.println("对方IP地址:" + ip); 19 20 // 获取对方 端口号 21 int port = packet.getPort(); 22 System.out.println("对方端口号: "+ port); 23 24 socket.close(); 25 }
多发
1 // 多条发送 2 public class ClintDemo { 3 public static void main(String[] args) throws Exception { 4 System.out.println("==============客户端启动============"); 5 // 创建发送对象、发送端自带默认端口号, 6 DatagramSocket socket = new DatagramSocket(); 7 // 可以自己设置端口号 8 //DatagramSocket socket = new DatagramSocket(6666); 9 // 创建一个数据包对象封装数据 10 /** 11 * public DatagramPacket(byte buf[], int length, InetAddress address, int port) 12 * 参数一:封装要发送的数据 13 * 参数二:发送数据的大小 14 * 参数三:服务端的主句IP地址 15 * 参数四:服务端的端口 16 */ 17 Scanner sc = new Scanner(System.in); 18 19 while (true) { 20 System.out.println("发送的内容:"); 21 String msg = sc.nextLine(); 22 23 if ("exit".equals(msg)){ 24 System.out.println("退出当前会话"); 25 socket.close(); 26 } 27 byte[] buffer = msg.getBytes(); 28 DatagramPacket packet = new DatagramPacket(buffer, buffer.length, InetAddress.getLocalHost(), 8888); 29 // 发送数据出去 30 socket.send(packet); 31 } 32 } 33 }
1 public class ServerDemo { 2 public static void main(String[] args) throws Exception { 3 System.out.println("==============服务器端启动============"); 4 // 创建接收对象 5 DatagramSocket socket = new DatagramSocket(8888); 6 // 创建数据包接收对象 7 byte[] buffer = new byte[1024 * 61]; 8 DatagramPacket packet = new DatagramPacket(buffer, buffer.length, InetAddress.getLocalHost(), 8888); 9 10 // 取到数据即可 11 while (true) { 12 // 接收数据 13 socket.receive(packet); 14 int len = packet.getLength(); 15 String s = new String(buffer, 0, len); 16 System.out.println("收到了来自:" + packet.getAddress() + ",端口号:" 17 + packet.getPort() + "的消息:" + s); 18 } 19 } 20 }