JavaSE-21.2.2【案例-UDP通信程序(“多人聊天室”)】
1 package day12.lesson2.p1; 2 3 import java.io.BufferedReader; 4 import java.io.FileReader; 5 import java.io.IOException; 6 import java.io.InputStreamReader; 7 import java.net.DatagramPacket; 8 import java.net.DatagramSocket; 9 import java.net.InetAddress; 10 import java.net.SocketException; 11 12 /* 13 2.3 案例-UDP通信程序 14 15 UDP发送数据:数据来自于键盘录入,直到输入的数据是886,发送数据结束 16 UDP接收数据:因为接收端不知道发送端什么时候停止发送,故采用死循环接收 17 18 */ 19 public class SendDemo { 20 public static void main(String[] args) throws IOException { 21 DatagramSocket ds = new DatagramSocket(); 22 23 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 24 String line; 25 while ((line=br.readLine()) != null){ 26 if("886".equals(line)){ 27 break; 28 } 29 30 byte[] bytes = line.getBytes(); 31 DatagramPacket dp = new DatagramPacket( 32 bytes, 33 bytes.length, 34 InetAddress.getByName("MSI-YUBABY"), 35 12345 36 ); 37 38 ds.send(dp); 39 } 40 41 ds.close(); 42 } 43 }
1 package day12.lesson2.p1; 2 3 import java.io.IOException; 4 import java.net.DatagramPacket; 5 import java.net.DatagramSocket; 6 7 public class ReceiveDemo { 8 public static void main(String[] args) throws IOException { 9 DatagramSocket ds = new DatagramSocket(12345); 10 11 while (true){ 12 byte[] bytes = new byte[1024]; 13 DatagramPacket dp = new DatagramPacket(bytes, bytes.length); 14 15 ds.receive(dp); 16 17 System.out.println("接收到的数据:" + new String( 18 dp.getData(), 19 0, 20 dp.getLength() 21 )); 22 } 23 24 // ds.close(); 25 //启动一个ReceiveDemo-main,启动多个SendDemo-main,即可组成“聊天室” 26 } 27 }