package cn.charp3; import java.net.DatagramSocket; import java.net.SocketException; public class charDemo { public static void main(String[] args) throws Exception { DatagramSocket send=new DatagramSocket(); DatagramSocket rece=new DatagramSocket(10001); new Thread(new Send(send)).start(); new Thread(new Rece(rece)).start(); } } package cn.charp3; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class Send implements Runnable { private DatagramSocket ds; public Send(DatagramSocket ds) { this.ds=ds; } @Override public void run() { try { BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in)); String line=null; while((line=bufr.readLine())!=null) { byte[] buf=line.getBytes(); DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.0.255"), 10001); ds.send(dp); } } catch (Exception e) { // TODO: handle exception } } } package cn.charp3; import java.net.DatagramPacket; import java.net.DatagramSocket; public class Rece implements Runnable { private DatagramSocket ds; public Rece(DatagramSocket ds) { this.ds=ds; } @Override public void run() { try{ while(true) { byte[] buf=new byte[1024]; DatagramPacket dp=new DatagramPacket(buf,buf.length); ds.receive(dp); String ip=dp.getAddress().getHostAddress(); int port=dp.getPort(); String text=new String(dp.getData(),0,dp.getLength()); System.out.println(ip+""+port+""+text); if(text.equals("886")){ System.out.println(ip+"退出了"); } } }catch(Exception e) { } } }