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,是以進行廣播,其他幀同理。