没有写界面,但是主要的代码都已经写出。
import java.io.*; import java.net.*; class ChatDemo { public static void main(String [] args)throws Exception { DatagramSocket send1 = new DatagramSocket(); DatagramSocket rece1 = new DatagramSocket(10001); new Thread(new send(send1)).start(); new Thread(new rece(rece1)).start(); } } class send implements Runnable { private DatagramSocket ds; public send(DatagramSocket ds) { this.ds = ds; } public void run() { try { BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));//读取键盘输入 String line = null; while((line = buf.readLine())!=null)//如果不为空,就继续读 { byte [] b = line.getBytes(); DatagramPacket dp = new DatagramPacket(b,b.length,InetAddress.getByName("192.168.33.1"),10001);//构造数据包,发送到指定主机端口 ds.send(dp); } ds.close(); } catch (Exception e) { throw new RuntimeException("发送端失败"); } } } class rece implements Runnable { private DatagramSocket ds; public rece(DatagramSocket ds) { this.ds = ds; } public void run() { try { while(true) { byte [] b = new byte[1024*64]; DatagramPacket dp = new DatagramPacket(b,b.length);//接收发送过来的数据 ds.receive(dp); String ip = dp.getAddress().getHostAddress();//读取IP String data = new String(dp.getData(),0,dp.getLength());//读取数据 System.out.println(ip+":"+data); } } catch (Exception e) { throw new RuntimeException("接收端失败"); } } }