一、Student测试类
import java.net.InetAddress;
import java.net.UnknownHostException;
public class StudentTest {
//学生即可以给老师说话也可以听老师说话
public static void main(String[] args) throws UnknownHostException {
//开启发送线程,参数:接收方的ip、接收方的端口
new Thread(new SendThread(InetAddress.getByName("127.0.0.1"),9090)).start();
//开启接收线程,参数:放送方的名称,接收方的端口
new Thread(new ReceiveThread("Teacher",9595)).start();
}
}
二、Teacher测试类
import java.net.InetAddress;
import java.net.UnknownHostException;
public class TeacherTest {
//老师即可以给学生说话也可以听学生说话
public static void main(String[] args) throws UnknownHostException {
//启动接收线程,参数:发送方的名称,接收方的端口
new Thread(new ReceiveThread("Student",9090)).start();
//启动发送线程,参数:接收方的ip,接收方的端口
new Thread(new SendThread(InetAddress.getByName("127.0.0.1"),9595)).start();
}
}
三、发送线程
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class SendThread implements Runnable{
//数据报套接字
DatagramSocket socket = null;
//输入流,读取键盘的输入
BufferedReader bf = null;
//接收方ip
InetAddress inetAddress = null;
//接收方端口
int port;
public SendThread(InetAddress inetAddress,int port){
this.inetAddress = inetAddress;
this.port = port;
try {
socket = new DatagramSocket();
} catch (SocketException e) {
e.printStackTrace();
}
bf = new BufferedReader(new InputStreamReader(System.in));
}
@Override
public void run() {
try{
while(true){
//读取键盘输入
String data = bf.readLine();
//构造数据包
byte[] bytes = data.getBytes();
DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length, this.inetAddress,this.port);
//发送数据包
socket.send(packet);
//当发送bye时,跳出循环
if(data.equals("bye")){
break;
}
}
}catch(Exception e){
e.printStackTrace();
}finally {
if(bf!=null){
try {
bf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//关闭数据报套接字
socket.close();
}
}
}
四、接收线程
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class ReceiveThread implements Runnable {
//数据包套接字
DatagramSocket socket = null;
//接收数据的端口
int port;
//发送方的名称
String from;
public ReceiveThread(String from,int port){
this.from = from;
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try{
while (true){
//构造数据包
byte[] bytes = new byte[1024];
DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length);
//阻塞式接收数据包
socket.receive(packet);
//将接收的数据包的内容打印出来
byte[] receivebytes = packet.getData();
String data = new String(receivebytes,0,receivebytes.length).trim();
System.out.println(from+":"+data);
//若数据包内容为bye,则跳出循环
if(data.equals("bye")){
break;
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
socket.close();
}
}
}