共需要四个类
- 消息发送类
- 消息接收类
- 老师类
- 学生类
这里用到了多线程
- 消息发送类
public class UdpTalkSend implements Runnable{
DatagramSocket socket =null;
BufferedReader reader = null;
int fromPort;
String toIP;
int toPort;
public UdpTalkSend(int fromPort,String toIP,int toPort) {
this.fromPort=fromPort;
this.toIP=toIP;
this.toPort=toPort;
try{
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[] datas = data.getBytes();
DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress(this.toIP, this.toPort));
socket.send(packet);
if(data.equals("bye")){
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
- 消息接收类
public class UdpTalkReceive implements Runnable{
DatagramSocket socket =null;
int port;
String msgFrom;
public UdpTalkReceive(int port,String msgFrom) {
this.port = port;
this.msgFrom=msgFrom;
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(msgFrom+":"+receiveData);
if(receiveData.equals("bye")){
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
- 学生类
public class UdpTalkStudent {
public static void main(String[] args) {
new Thread(new UdpTalkSend(6666,"localhost",8888)).start();
new Thread(new UdpTalkReceive(9999,"学生")).start();
}
}
- 老师类
public class UdpTalkTeacher {
public static void main(String[] args) {
new Thread(new UdpTalkSend(7777,"localhost",9999)).start();
new Thread(new UdpTalkReceive(8888,"老师")).start();
}
}