1、 写一个程序来模拟网桥功能。
模拟实现网桥的转发功能,以从文件中读取帧模拟网桥从网络中收到一帧,即从两个文 件中读入一系列帧,从第一个文件中读入一帧然后从第二个文件中再读入一帧,如此下去。 对每一帧,显示网桥是否会转发,及显示转发表内容。
要求:Windows 或 Linux 环境下运行,程序应在单机上运行。
分析:用程序模拟网桥功能,可以假定用两个文件分别代表两个网段上的网络帧数据。而两 个文件中的数据应具有帧的特征,即有目的地址,源地址和帧内数据。程序交替读入帧的数 据,就相当于网桥从网段中得到帧数据。 对于网桥来说,能否转发帧在于把接收到的帧与网桥中的转发表相比较。判断目的地址后才决定是否转发。由此可见转发的关键在于构造转发表。这里转发表可通过动态生成。
参考代码
Main.java:运行时程序的入口
public class Main {
public static void main(String[] args) {
try {
// 文件流,第一个文件
File file1 = new File("C:/Users/DELL/Desktop/a.txt");
Reader reader1 = new InputStreamReader(new FileInputStream(file1));
// 文件流,第二个文件
File file2 = new File("C:/Users/DELL/Desktop/b.txt");
Reader reader2 = new InputStreamReader(new FileInputStream(file2));
// 读取开始
int i = 0;
char[] chars1 = new char[4];
char[] chars2 = new char[4];
// 交替读取文件里的数据(帧)
while((i = reader1.read(chars1))!=-1) {
String frame1 = new String(chars1);
// 转发
FowardingTable.forward(new Frame(frame1));
while((i = reader2.read(chars2))!=-1) {
String frame2 = new String(chars2);
// 转发
FowardingTable.forward(new Frame(frame2));
}
}
reader1.close();
reader2.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Frame.java:帧
/**
* 帧
* 规定为4个字符,格式为:源地址(1)+目标地址(1)+数据(2)
* @Author DELL
* @create 2020/5/7 8:50
*/
public class Frame {
public Frame(String frame) throws Exception {
if(frame.length() != 4) {
throw new Exception("帧的长度错误,应为4");
}
this.source = frame.substring(0,1);
this.target = frame.substring(1,2);
this.data = frame.substring(2,4);
}
/**
* 源地址
*/
private String source;
/**
* 目标地址
*/
private String target;
/**
* 数据
*/
private String data;
//省略get、set和toString方法
}
ForwardingTable.java:负责转发
/**
* 转发表
* @Author DELL
* @create 2020/5/7 8:59
*/
public class FowardingTable {
public static Set<String> address = new LinkedHashSet<>();
public static void forward(Frame frame) {
System.out.println("-------------------------");
System.out.println("路由检测到帧:"+frame.getFrame());
// 路由表将地址存储
address.add(frame.getSource());
// 目的地址与源地址相同
if(frame.getTarget().equals(frame.getSource())) {
System.out.println("目的地址与源地址相同,不转发");
} else {
// 路由表中含有目标地址,进行转发
if (address.contains(frame.getTarget())) {
System.out.println(frame.getSource() + "转发到" + frame.getTarget() + "成功,数据为" + frame.getData());
} else {
System.out.println("查找失败,"+frame.getSource() + "转发到除" + frame.getSource() + "以外的其他地址");
}
}
// 输入转发表里面的内容
System.out.print("转发表:");
for(String addr:address) {
System.out.print(addr+" ");
}
System.out.println();
System.out.println("-------------------------");
}
}
程序含有详细注释,这里就不详细解释了。以下是运行前提前准备的两个文件
程序运行结果如下:
轮流从a.txt和b.txt读取数据,第一个帧AA00不转发,并将A加入路由表,第二个帧BACD,由于路由表有A,转发成功,并将B加入路由表。第四个帧在路由表找不到C,因此进行广播,其他帧同理。