我们将里面的IP地址 例如 192.168.2.143改成192.168.2.255就是将内容发送给192.168.2.(0-254)里面的所有人
package Intnet; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.security.interfaces.DSAKey; public class Thresend implements Runnable { private DatagramSocket send; public Thresend(DatagramSocket send) { super(); this.send = send; } @Override public void run() { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = null; try { while((line = br.readLine()) != null) { byte buf[] = line.getBytes(); try { DatagramPacket dp = new DatagramPacket(buf, buf.length,InetAddress.getByName("192.168.2.255"),1150); send.send(dp); if(line.equals("再见臭弟弟"))break; } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } package Intnet; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class Threrece implements Runnable { private DatagramSocket rece; public Threrece(DatagramSocket rece) { super(); this.rece = rece; } @Override public void run() { // TODO Auto-generated method stub while(true) { byte buf[] = new byte [1024]; DatagramPacket dp = new DatagramPacket(buf, buf.length); try { rece.receive(dp); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } String ip = dp.getAddress().getHostAddress(); int port = dp.getPort(); String text = new String(dp.getData(),0,dp.getLength()); System.out.println(ip + ":" + port + ":" + text); } } } package Intnet; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class Thredemo { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub DatagramSocket send = new DatagramSocket(); DatagramSocket rece = new DatagramSocket(1150); Thresend s = new Thresend(send); Threrece r = new Threrece(rece); new Thread(s).start(); new Thread(r).start(); } }