发送类

//udp不需要连接服务器
public class send implements Runnable {
//建立一个socket
DatagramSocket socket = null;
BufferedReader reader = null;

private String toIP;
private int toPort;

public send(String toIP, int toPort) {
this.toIP = toIP;
this.toPort = toPort;
try {
socket = new DatagramSocket();
//建立包,从控制台读取System.in
reader = new BufferedReader(new InputStreamReader(System.in));
} catch (SocketException e) {
e.printStackTrace();
}
}

@Override
public void run() {
try {
while (true) {
String data = reader.readLine();
//发送
DatagramPacket packet = new DatagramPacket(data.getBytes(), 0, data.getBytes().length, InetAddress.getByName(this.toIP), this.toPort);
socket.send(packet);
//判断是否断开
if (data.equals("over")) {
System.out.println("结束");
break;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}

接收类

//udp不需要连接服务器
public class receive implements Runnable {
//建立一个socket
DatagramSocket socket = null;
private int port;
private String msgFrom;

public receive(int port, String msgFrom) {
this.port = port;
this.msgFrom = msgFrom;
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
}

@Override
public void run() {
try {
while (true) {
//创建Buffer
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
//阻塞接收
socket.receive(packet);
//接收数据
String data = new String(packet.getData(), 0, packet.getLength());
//判断是否断开
if (data.equals("over")) {
System.out.println("结束");
break;
}
System.out.println(msgFrom + ":" + data);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}

客户端1

public class student {
public static void main(String[] args) {
new Thread(new send("localhost",6666)).start();
new Thread(new receive(8888,"老师")).start();
}
}

客户端2

public class teacher {
public static void main(String[] args) {
new Thread(new send("localhost",8888)).start();
new Thread(new receive(6666,"学生")).start();
}
}

PS:两边都要发over,才能关掉两个线程