1、写一个接收消息的类
public class ReceiveMsg implements Runnable{
DatagramSocket socket = null;
private int port;
private String roleType;
public ReceiveMsg(int port, String roleType) {
this.port = port;
this.roleType = roleType;
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
try {
//准备接收包裹
byte[] container = new byte[1024];
DatagramPacket packet = new DatagramPacket(container, 0, container.length);
socket.receive(packet);
//断开连接
byte[] data = packet.getData();
String receiveData = new String(data, 0, data.length);
System.out.println(this.roleType + ":" + receiveData);
if ("bye".equals(receiveData)) {
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
2、写一个发送消息的类
public class SendMsg implements Runnable {
BufferedReader reader = null;
DatagramSocket socket = null;
private int fromPort;
private String toIp;
private int toPort;
public SendMsg(int fromPort, String toIp, int toPort) {
this.fromPort = fromPort;
this.toIp = toIp;
this.toPort = toPort;
try {
//创建socket
socket = new DatagramSocket(fromPort);
//读取消息内容
reader = new BufferedReader(new InputStreamReader(System.in));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
try {
String data = reader.readLine();
//消息转换成字节流
byte[] dataBytes = data.getBytes();
//声明包
DatagramPacket packet = new DatagramPacket(dataBytes, 0,
dataBytes.length, new InetSocketAddress(this.toIp, this.toPort));
//发送包
socket.send(packet);
if ("bye".equals(data)) {
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
3、创建一个学生类
public class Student {
public static void main(String[] args) {
new Thread(new SendMsg(7777, "localhost", 9999)).start();
new Thread(new ReceiveMsg(8888, "老师")).start();
}
}
4、创建一个老师类
public class Teacher {
public static void main(String[] args) {
new Thread(new SendMsg(5555, "localhost", 8888)).start();
new Thread(new ReceiveMsg(9999, "学生")).start();
}
}