UDP实现多人聊天
发送端
package com.zy.exercise; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.util.Scanner; public class send1 { public static void main(String[] args) throws Exception { DatagramSocket datagramSocket = new DatagramSocket(); InetAddress byName = InetAddress.getByName("127.0.0.1");//如果别的主机要测试此处ip应该为192.168.219.61,即服务器的ip System.out.println("欢迎来到多人聊天室"); Scanner scanner = new Scanner(System.in); String username=scanner.nextLine(); while(true){ System.out.println("请输入:"); String str=scanner.nextLine(); str=username+"说:"+str; // System.out.println(str); byte b[]=str.getBytes(); DatagramPacket datagramPacket = new DatagramPacket(b, b.length, byName, 8888); datagramSocket.send(datagramPacket); if(str.equals("拜拜")) { System.out.println("退出"); break; } } datagramSocket.close(); } }
服务器端(分发个多个主机)
package com.zy.exercise; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; public class server { //分发给该段网络的所有服务器 public static void main(String[] args) throws Exception { DatagramSocket datagramSocket = new DatagramSocket(8888); byte b[]=new byte[1024]; while(true){ DatagramPacket datagramPacket = new DatagramPacket(b, b.length); datagramSocket.receive(datagramPacket); System.out.println(new String(b)); for (int i = 1; i < 100; i++) { DatagramSocket datagramSocket2 = new DatagramSocket(); InetAddress byName = InetAddress.getByName("192.168.219."+i); DatagramPacket datagramPacket2 = new DatagramPacket(b, b.length, byName, 10086); datagramSocket2.send(datagramPacket2); } } // datagramSocket.close(); } }
接收端
package com.zy.exercise; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class receive1 { public static void main(String[] args) throws Exception { System.out.println("xxxx聊天群"); DatagramSocket datagramSocket = new DatagramSocket(10086); byte b[]=new byte[1024]; while(true){ DatagramPacket datagramPacket = new DatagramPacket(b, b.length); datagramSocket.receive(datagramPacket); System.out.println(new String(b)); } } }
结果